Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 78 ยท Packaging and Delivery

Kustomize

Customize Kubernetes manifests without templates: bases and overlays, patches, generators, image and name changes, plus a Python model of strategic merge patching.

Sooner or later you have the same application in several places: a small dev setup with one replica and a debug image, staging, and a big prod with ten replicas and different limits. Copying the YAML for each environment works for a week; then someone fixes a bug in one copy and forgets the others.

Kustomize solves this without templates. You keep one plain, valid set of manifests (the base) and describe each environment as a small overlay that says only what is different. Kustomize merges them and prints ordinary YAML. It is built into kubectl (kubectl kustomize and kubectl apply -k), so there is nothing extra to install, and it works on any manifests, even ones you did not write. The other big approach, templating with Helm, comes in Helm: Charts and Releases.

Kustomize needs a cluster only at the very end, when you apply the result. Everything on this page is therefore read-only commands plus a Python model that shows how the merging works.

Layout: base and overlays

A typical repository looks like this:

TEXT
shop/
  base/
    kustomization.yaml
    deployment.yaml
    service.yaml
  overlays/
    dev/
      kustomization.yaml
    prod/
      kustomization.yaml
      replica-patch.yaml

The base lists its files in a kustomization.yaml:

YAML
# base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml

An overlay refers to the base and adds changes:

YAML
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - ../../base
namespace: shop-prod
namePrefix: prod-
labels:
  - pairs:
      env: prod
    includeSelectors: true
images:
  - name: registry.example.com/shop/web
    newTag: "1.4.2"
replicas:
  - name: web
    count: 10
patches:
  - path: replica-patch.yaml

Why Kustomize

Plain YAML The base is valid on its own.
Overlays Each environment lists only differences.
No templates No placeholders, no template language.
Built into kubectl kubectl apply -k just works.
1 / 2

Building and applying

These commands only read files until the last step:

CONSOLE
$ kubectl kustomize overlays/prod        # print the final YAML
$ kubectl diff -k overlays/prod          # what would change in the cluster
$ kubectl apply -k overlays/prod         # send it to the cluster
$ kubectl delete -k overlays/prod        # remove everything it created

The standalone kustomize build overlays/prod does the same as kubectl kustomize, often with a newer version. Because the output is plain YAML, you can check it in review, run policy checks on it, or commit it for GitOps.

Transformers: global changes

A few fields change every object at once:

  • namespace sets the namespace of every namespaced resource.
  • namePrefix / nameSuffix rename every resource. Kustomize also updates references, for example a Deployment's reference to a ConfigMap, so nothing breaks.
  • labels adds labels to every object. With includeSelectors: true it also adds them to selectors and pod templates. Be careful: selectors are immutable on a Deployment, so adding a label to an existing app's selector forces you to recreate it. Use includeSelectors: false for labels that are only metadata. The older commonLabels field always touches selectors, which is why it is deprecated.
  • commonAnnotations does the same for annotations.
  • images changes the name, tag or digest of an image wherever it appears in a pod spec. This is the field a CI pipeline updates after building a new image: kustomize edit set image registry.example.com/shop/web=registry.example.com/shop/web:1.4.3.
  • replicas sets the replica count by resource name.

Patches

When a field is not covered by a transformer, use a patch. There are two styles.

Strategic merge patch. You write a partial manifest. Kustomize finds the target by kind and name and merges your fields into it. Maps are merged key by key, and lists of objects with a merge key (such as containers, merged by name) are merged item by item instead of replaced.

YAML
# overlays/prod/replica-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  template:
    spec:
      containers:
        - name: web
          resources:
            requests: {cpu: 500m, memory: 512Mi}
            limits: {memory: 1Gi}

JSON 6902 patch. An explicit list of add, replace and remove operations on JSON paths. It is more precise, and it is the way to edit lists that have no merge key:

YAML
patches:
  - target:
      kind: Deployment
      name: web
    patch: |-
      - op: replace
        path: /spec/template/spec/containers/0/args/1
        value: "--log-level=warn"
      - op: add
        path: /metadata/annotations/team
        value: payments

A target can select by kind, name (a regex), labelSelector and other fields, so one patch can change many objects. In a strategic merge patch, the special line $patch: delete removes an element from a list or an entire object.

Generators

Kustomize can create ConfigMaps and Secrets from literals or files:

YAML
configMapGenerator:
  - name: web-config
    literals:
      - LOG_LEVEL=info
    files:
      - app.properties
secretGenerator:
  - name: web-secrets
    envs:
      - secrets.env     # keep this file out of Git!

By default Kustomize adds a content hash to the name, such as web-config-7b9kd2f5tm, and rewrites every reference to it. The effect is valuable: when the content changes, the name changes, so the Deployment's pod template changes and a rolling update happens automatically. (A plain ConfigMap edit does not restart pods; see ConfigMaps.) You can turn the hash off with generatorOptions: {disableNameSuffixHash: true} if something outside Kustomize needs a fixed name. For production secrets, do not keep real values in Git; use one of the approaches in External Secrets and Config Patterns.

How the merge works: a Python model

The real Kustomize is written in Go, but its core idea is easy to model. The first stand-in implements a strategic merge on dictionaries: nested maps merge, and lists of dicts that have a name merge by that name. It also supports the $patch: delete directive.

Python Strategic merge patch in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the output: replicas became 10; the web container kept its image but got new args (a plain list is replaced as a whole) and merged resources (cpu changed, memory added); the debug-shell container vanished; and metrics was appended. That mix of merging and replacing is why it matters whether a list has a merge key. If you need to change a single argument in a list without a key, use a JSON 6902 patch.

The second stand-in strings several transformers together, the way a kustomization.yaml does, to build a prod overlay from a base and shows how references follow a renamed object.

Python Base plus overlay: prefix, image, replicas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The most important point is the rename: the Deployment's envFrom now points to prod-web-config because Kustomize understands references. The stand-in implements only a handful of Kustomize's transformers, with no hash suffixes and no JSON patches; real Kustomize knows many more field paths and resource types.

When to choose Kustomize

Kustomize shines when you own the base manifests and the differences between environments are modest: replicas, resources, images, a few config values. It struggles when the differences are structural (many optional components, loops over lists), where a templating tool like Helm is more natural. Many teams combine them: render a third-party Helm chart, then adjust it with Kustomize overlays. Argo CD and Flux both support Kustomize directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main idea behind Kustomize?

    Kustomize works on plain YAML. The base stays valid on its own, and overlays add changes through transformers, patches and generators.
  2. 2. Which command prints the final YAML for an overlay without changing the cluster?

    kubectl kustomize (or kustomize build) renders the result. apply -k sends it to the cluster.
  3. 3. In a strategic merge patch, how are the items of the containers list combined with the base?

    Lists with a merge key such as containers (key: name) are merged per item. Lists without a key, like args, are replaced as a whole.
  4. 4. Why does a configMapGenerator add a hash to the ConfigMap's name?

    Kustomize rewrites all references to the hashed name, so editing the data rolls out new pods automatically.

Summary

  • Kustomize customizes plain YAML with a base plus overlays, with no templates, and is built into kubectl (-k).
  • Transformers (namespace, namePrefix, labels, images, replicas) change everything at once and fix references for you.
  • Patches come as strategic merge (partial manifests, lists merged by name) or JSON 6902 (explicit operations).
  • Generators create ConfigMaps and Secrets and add a content hash so that changes trigger rollouts.
  • Use kubectl kustomize and kubectl diff -k before kubectl apply -k.

Next: the templating alternative used by most public software, Helm: Charts and Releases.