Most teams reach the same crossroads after their third microservice: dev, staging and prod manifests have drifted, someone copy-pasted a Deployment and forgot to bump the replica count, and the "temporary" sed in the CI pipeline is now load-bearing. The usual reflex is to write an in-house Helm chart. That works, but you now maintain a templating language, a values.yaml schema, and Go template whitespace bugs — for an application that only differs by three fields between environments.
Kustomize is the pragmatic alternative. It is a patching engine, not a templating engine: you keep plain, valid, lintable YAML, and you declare the deltas per environment. It ships inside kubectl and oc, so there is nothing to install on the cluster and no release state to manage.
This article is for people who have never structured a Kustomize repo. By the end you will know how to lay out bases and overlays, how to patch correctly (and why patchesStrategicMerge is deprecated), how to factor cross-cutting concerns into components, and how to propagate values with replacements instead of duplicating them.
The problem: YAML duplication grows faster than your team
A typical "copy the folder per environment" layout looks like this:
manifests/
dev/deployment.yaml # 120 lines
staging/deployment.yaml # 120 lines, 4 differ
prod/deployment.yaml # 120 lines, 7 differ
The cost is not the disk space, it is the drift. A security fix to securityContext must be applied three times. A new probe is added in prod only. Six months later nobody can answer "what is actually different between staging and prod?" without diff -r.
Helm solves this with templates, but it pushes complexity into the chart: every field that might differ becomes {{ if .Values.x }}. Charts for third-party software are great. Charts for your own 3-manifest app are often over-engineering.
Kustomize inverts the model: one source of truth (the base), plus explicit, reviewable deltas (the overlays). The diff between environments is the overlay directory. That is the single biggest readability win.
Kustomize in five minutes
Kustomize is built into kubectl/oc, but the embedded version lags behind upstream. Check both:
# Embedded version
kubectl version --client -o yaml | grep -i kustomize
oc version --client
# Standalone binary (recommended for CI, pinned)
kustomize version
Two commands cover 95% of daily usage:
# Render to stdout — never apply blind
kustomize build overlays/prod
kubectl kustomize overlays/prod # same thing, embedded
# Apply
kubectl apply -k overlays/prod
oc apply -k overlays/prod
# Show what would change against the live cluster
kustomize build overlays/prod | oc diff -f -
Rule number one: kustomize build is your unit test. Run it in CI for every overlay on every pull request.
Structuring the repository
A layout that scales for a single application:
.
├── base
│ ├── kustomization.yaml
│ ├── deployment.yaml
│ ├── service.yaml
│ └── configmap.yaml
├── components
│ ├── monitoring
│ │ ├── kustomization.yaml
│ │ └── servicemonitor.yaml
│ └── high-availability
│ ├── kustomization.yaml
│ └── pdb.yaml
└── overlays
├── dev
│ └── kustomization.yaml
├── staging
│ └── kustomization.yaml
└── prod
├── kustomization.yaml
└── patch-resources.yaml
The base: valid, deployable, opinion-free
The base must be a working manifest set with sane, safe defaults and no environment-specific values (no prod hostname, no 10 replicas).
# base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
app.kubernetes.io/name: web
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: web
template:
metadata:
labels:
app.kubernetes.io/name: web
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: web
image: quay.io/acme/web:0.1.0
ports:
- name: http
containerPort: 8080
envFrom:
- configMapRef:
name: web-config
resources:
requests:
cpu: 50m
memory: 128Mi
limits:
memory: 256Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
readinessProbe:
httpGet:
path: /healthz
port: http
# base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
labels:
- pairs:
app.kubernetes.io/name: web
app.kubernetes.io/part-of: acme-platform
includeSelectors: false
configMapGenerator:
- name: web-config
literals:
- LOG_LEVEL=info
- APP_HOST=web.example.invalid
Two things worth noting. labels with includeSelectors: false replaces the old commonLabels, which mutated spec.selector — a field that is immutable on Deployments and will break upgrades. And configMapGenerator appends a content hash to the ConfigMap name, so changing a literal automatically rolls the Deployment. That alone removes the classic "I updated the ConfigMap but the pods kept the old value" incident.
Overlays: dev is almost empty, prod carries the weight
# overlays/dev/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: acme-dev
namePrefix: dev-
resources:
- ../../base
configMapGenerator:
- name: web-config
behavior: merge
literals:
- LOG_LEVEL=debug
- APP_HOST=web-dev.apps.cluster.example.com
images:
- name: quay.io/acme/web
newTag: main-latest
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: acme-prod
resources:
- ../../base
components:
- ../../components/monitoring
- ../../components/high-availability
configMapGenerator:
- name: web-config
behavior: merge
literals:
- APP_HOST=web.apps.cluster.example.com
images:
- name: quay.io/acme/web
newName: quay.io/acme/web
newTag: "1.4.2"
replicas:
- name: web
count: 4
patches:
- path: patch-resources.yaml
Note replicas: and images: — built-in transformers that cover the two most frequent deltas without writing a patch file at all. In CI you can even do:
cd overlays/prod && kustomize edit set image quay.io/acme/web=quay.io/acme/web@sha256:3f1a...c9
Patching: strategic merge vs JSON 6902
patchesStrategicMerge is deprecated — use patches
Older tutorials use patchesStrategicMerge and patchesJson6902. Since Kustomize v4.5 both are deprecated in favour of a single patches: field, which auto-detects the patch type. Keep this in mind when reading Stack Overflow answers; the behaviour is identical, the field name is not.
A strategic merge patch is a partial manifest. You repeat only enough identity (apiVersion, kind, name) plus the fields you want to change:
# overlays/prod/patch-resources.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
template:
spec:
containers:
- name: web # merge key: lists of containers merge by name
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
memory: 1Gi
The name field is the merge key: without it Kustomize would replace the whole container list. Same pattern for volumes, ports, env.
Inline patches and JSON 6902
For surgical edits — especially on list indices or to delete a field — use a JSON patch, inline in the kustomization:
patches:
- target:
kind: Deployment
name: web
patch: |-
- op: remove
path: /spec/template/spec/containers/0/resources/limits/memory
- op: add
path: /spec/template/spec/tolerations
value:
- key: workload
operator: Equal
value: critical
effect: NoSchedule
You can also target many resources at once with a selector, which is how you apply a rule fleet-wide:
patches:
- target:
kind: Deployment
labelSelector: app.kubernetes.io/part-of=acme-platform
patch: |-
apiVersion: apps/v1
kind: Deployment
metadata:
name: ignored # required by the parser, overridden by target
spec:
template:
spec:
automountServiceAccountToken: false
To remove a key with a strategic merge patch, set it to null:
spec:
template:
spec:
containers:
- name: web
readinessProbe: null
Components: reusable, opt-in feature slices
An overlay answers "which environment?". A component answers "which capability?". Components are the cure for the overlay matrix explosion (prod-eu, prod-us, prod-eu-ha, …).
A component is a kustomization with its own kind:
# components/high-availability/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
resources:
- pdb.yaml
patches:
- patch: |-
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
template:
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app.kubernetes.io/name: web
# components/high-availability/pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web
spec:
minAvailable: 2
selector:
matchLabels:
app.kubernetes.io/name: web
Any overlay opts in with one line under components:. Staging gets monitoring but not HA; prod gets both. No duplicated YAML, and the capability is reviewed once.
A note on ordering: components are evaluated after the overlay's own resources, in the order listed, so a component can patch resources brought in by the base.
Replacements: stop repeating the same hostname
You still have a value appearing in several places — a hostname in a ConfigMap, in an OpenShift Route, and in a CORS environment variable. vars used to handle this; it is deprecated and limited. Use replacements, which copies a field from one rendered resource into others:
# overlays/prod/kustomization.yaml (excerpt)
resources:
- ../../base
- route.yaml
replacements:
- source:
kind: ConfigMap
name: web-config
fieldPath: data.APP_HOST
targets:
- select:
kind: Route
name: web
fieldPaths:
- spec.host
- select:
kind: Deployment
name: web
fieldPaths:
- spec.template.spec.containers.[name=web].env.[name=PUBLIC_URL].value
options:
create: true
# overlays/prod/route.yaml
apiVersion: route.openshift.io/v1
kind: Route
metadata:
name: web
spec:
host: placeholder.example.invalid
to:
kind: Service
name: web
port:
targetPort: http
tls:
termination: edge
insecureEdgeTerminationPolicy: Redirect
The [name=web] syntax selects a list element by field value — far more robust than hardcoding index 0. The hostname is now defined exactly once, in the ConfigMap generator.
Verify before applying:
kustomize build overlays/prod | grep -A2 'kind: Route'
kustomize build overlays/prod | oc apply --dry-run=server -f -
Security best practices
Never commit Secrets, even base64-encoded. secretGenerator with literals puts plaintext in Git. Use it only with envs: pointing at a gitignored file for local work, and in real clusters source secrets from External Secrets Operator, Sealed Secrets, or Vault. If you must keep encrypted secrets in the repo, use SOPS with the KSOPS plugin — and remember that plugins require --enable-alpha-plugins, which you should enable only in a controlled CI image.
Pin remote bases to an immutable ref. resources: - github.com/acme/platform//base?ref=main means your render changes when someone else pushes. Use a tag or commit SHA: ?ref=v1.8.0. Remote bases execute transformer logic from someone else's repository — treat them as a supply-chain dependency and mirror them internally for production.
Pin images by digest in prod. newTag: "1.4.2" can be re-pushed; newName/digest cannot:
images:
- name: quay.io/acme/web
digest: sha256:3f1a9b0c5d2e7f84a1b6c3d9e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8
Keep security defaults in the base, never in overlays. runAsNonRoot, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], seccompProfile: RuntimeDefault belong to the base so every environment inherits them. An overlay that weakens them becomes a visible, reviewable diff. On OpenShift with the restricted-v2 SCC, deliberately omit runAsUser so the platform assigns a UID from the namespace range — hardcoding runAsUser: 1000 will get your pod rejected.
Do not loosen the load restrictor. kustomize build --load-restrictor LoadRestrictionsNone lets a kustomization read files outside its root. It is a common fix for a bad directory layout and a real path-traversal risk in shared CI runners. Restructure instead.
Gate overlays in CI. Render every overlay, validate against the cluster's schemas, and scan the output:
set -euo pipefail
for env in dev staging prod; do
kustomize build "overlays/${env}" > "/tmp/${env}.yaml"
kubeconform -strict -summary "/tmp/${env}.yaml"
conftest test "/tmp/${env}.yaml" # OPA policies: no :latest, limits set, etc.
done
Enforce the namespace in the overlay. Setting namespace: in every overlay kustomization prevents an oc apply -k executed in the wrong current project from landing in production.
Conclusion
Kustomize will not replace Helm for distributing third-party software, but for your own applications it removes an entire layer of templating complexity. The key takeaways:
- Base = the full, safe, environment-agnostic truth. Overlays contain only deltas; if your prod overlay is 300 lines, your base is wrong.
-
Use
patches:, not the deprecatedpatchesStrategicMerge/patchesJson6902. Strategic merge for structural changes, JSON 6902 for surgical ones, andtarget.labelSelectorto patch many resources at once. -
Prefer built-in transformers (
images,replicas,namespace,labels) over hand-written patches — and avoidcommonLabels, which mutates immutable selectors. - Components are capabilities, overlays are environments. That split is what keeps the directory tree from exploding combinatorially.
-
replacementskills the last duplicated values;varsis dead, don't learn it. -
kustomize buildin CI, every PR. Render, validate, policy-check, thenoc diffbefore apply.
Start by converting one application: extract the base, create three nearly empty overlays, and let the differences surface naturally. The diff you get is usually the most honest documentation of your environments you have ever had.
Top comments (1)
Florient, the line I'll keep is 'Components are capabilities, overlays are environments.' That's the split that stops the matrix explosion — prod-eu, prod-us, prod-eu-ha — and it's the part most Kustomize introductions miss entirely. The overlay answers which environment; the component answers which capability, and one line opts an overlay in.
The other detail that earns this post its place: labels with includeSelectors: false replacing commonLabels. Mutating spec.selector is immutable on Deployments, so the old way didn't just look messy, it broke upgrades — and it's exactly the kind of thing you'd only learn after a failed rollout.
One question on your own rule — 'if your prod overlay is 300 lines, your base is wrong.' You also say to pin remote bases to a tag or SHA because ?ref=main moves under you. A tag can be re-pushed too, though. Do you pin to the full commit SHA in practice, and how do you pull in an upstream base fix when you do?