Skip to content
LF Cert Trainer

Lesson 136 · Section 11: Helm & Kustomize

Lesson 136: Kustomize patches and overlays: one base, one folder per environment

Change one object with a patch (strategic merge or JSON 6902, from a file or inline, aimed with a target), then organise manifests as a base plus overlays for dev and prod, with replicas, generated config and optional components per environment. · 20 min read · 2 min video

Official competency this lesson covers

1/7Patches and overlays
0:00 / 1:54

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Beyond "every object"

Lesson 203 changed every object at once: namespace, prefix, labels, images. Many changes are aimed at one object: production needs four replicas of web and a higher memory limit, dev needs a debug environment variable. Those are patches. And once dev and prod each have their own patches, you organise them as overlays on a shared base.

Patches

Two kinds of patchmerged by nameops on pathsDeployment webfrom the baseStrategic mergepartial YAMLJSON 6902op, path, valuePatched objectin the build
Two kinds of patch. A strategic merge patch looks like a piece of the object and is merged into it. A JSON 6902 patch is a list of operations on exact paths. Both go in the patches field; JSON 6902 always needs a target.

Parts:

  • Deployment web (from the base)
  • Strategic merge (partial YAML)
  • JSON 6902 (op, path, value)
  • Patched object (in the build)

Connections:

  • Strategic merge to Deployment web: merged by name
  • JSON 6902 to Deployment web: ops on paths
  • Deployment web to Patched object

All patches go in the patches field. Each entry gives the patch (path: to a file, or patch: inline) and, optionally, a target that selects which objects it applies to.

Strategic merge patch

It looks like a fragment of the object: apiVersion, kind, metadata.name, and only the fields to change.

# memory.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  template:
    spec:
      containers:
        - name: web                 # lists of containers are merged by name
          resources:
            limits:
              memory: 512Mi
          env:
            - name: LOG_LEVEL       # env is merged by name too: added or replaced
              value: debug
# kustomization.yaml
patches:
  - path: memory.yaml

"Strategic" means Kubernetes-aware: lists such as containers, env, volumes and ports are merged by their key (the name, or the port), so the patch adds or changes one entry without repeating the others. This is the same merge kubectl patch --type strategic uses.

To remove something, use the $patch: delete directive:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  template:
    spec:
      containers:
        - name: log-shipper
          $patch: delete            # remove this sidecar in this environment

JSON 6902 patch

A list of operations on exact paths, from RFC 6902. It always needs a target, because the operations do not name the object.

patches:
  - target:
      kind: Deployment
      name: web
    patch: |-
      - op: replace
        path: /spec/replicas
        value: 4
      - op: add
        path: /spec/template/spec/containers/0/args/-
        value: --cache-size=256
      - op: remove
        path: /spec/template/metadata/annotations/debug
opDoes
addAdd a field, or insert into a list (/- appends at the end)
replaceChange a field that must already exist
removeDelete a field or a list item
copy, move, testRarely needed

A / inside a key is written ~1: the label app.kubernetes.io/version is the path /metadata/labels/app.kubernetes.io~1version.

Which one to use

SituationChoose
Change fields of a container, add an env var, a volume, a portStrategic merge
Append to a plain list (args, command) or address an item by indexJSON 6902
The same change on many objectsEither, with a target using kind, labelSelector or a name regex
Only replicas or an image tagNeither: use the replicas or images field

A target can also aim a strategic merge patch at several objects: with a target, the name in the patch file is ignored and the patch is applied to every object the target selects.

patches:
  - path: no-privilege.yaml
    target:
      kind: Deployment
      labelSelector: tier=backend

Bases and overlays

A base and two overlaysresourcesresourcesbase/deployment, serviceoverlays/dev/ns dev, 1 replicaoverlays/prod/ns prod, 4 replicasNamespace devapply -k overlays/devNamespace prodapply -k overlays/prod
A base and two overlays. The base holds the manifests every environment shares. Each overlay points at the base and adds only what differs. You apply an overlay, never the base on its own.

Parts:

  • base/ (deployment, service)
  • overlays/dev/ (ns dev, 1 replica)
  • overlays/prod/ (ns prod, 4 replicas)
  • Namespace dev (apply -k overlays/dev)
  • Namespace prod (apply -k overlays/prod)

Connections:

  • overlays/dev/ to base/: resources
  • overlays/prod/ to base/: resources
  • overlays/dev/ to Namespace dev
  • overlays/prod/ to Namespace prod
app/
├── base/
│   ├── kustomization.yaml       # resources: deployment.yaml, service.yaml
│   ├── deployment.yaml
│   └── service.yaml
└── overlays/
    ├── dev/
    │   └── kustomization.yaml
    └── prod/
        ├── kustomization.yaml
        └── memory.yaml
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - ../../base
namespace: prod
namePrefix: prod-
labels:
  - pairs:
      env: prod
replicas:
  - name: web
    count: 4
images:
  - name: nginx
    newTag: "1.29"
patches:
  - path: memory.yaml
configMapGenerator:
  - name: app-config
    behavior: merge                # change the base's generated ConfigMap
    literals:
      - LOG_LEVEL=warn
What an overlay build does, in orderBuild baseits own changesOverlay loads itas resourcesGeneratorsmerge configTransformersns, prefix, replicasPatchesone object eachFinal YAMLapply -k overlay
What an overlay build does, in order. Kustomize builds the base first, then the overlay loads that output as its resources and applies its own generators, transformers and patches on top.

Parts:

  • Build base (its own changes)
  • Overlay loads it (as resources)
  • Generators (merge config)
  • Transformers (ns, prefix, replicas)
  • Patches (one object each)
  • Final YAML (apply -k overlay)

Connections:

  • Build base to Overlay loads it
  • Overlay loads it to Generators
  • Generators to Transformers
  • Transformers to Patches
  • Patches to Final YAML

The base is built first, with its own changes. The overlay then treats that output as its resources and applies its own generators, transformers and patches. Patches in an overlay refer to objects by their base names (web, not prod-web): Kustomize tracks the original name through the renaming.

Old kustomizations used a bases: field for this. It still works but is deprecated; resources: takes folders as well as files. Likewise patchesStrategicMerge and patchesJson6902 were folded into patches. kustomize edit fix converts an old file.

Under the hood · Components: optional pieces several overlays share

Sometimes a feature is wanted by some environments and not others: an external database, a monitoring sidecar, LDAP login. Putting it in the base forces it on everyone; copying it into each overlay duplicates it. A component is a reusable bundle of resources, patches and generators with kind: Component:

# components/monitoring/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
patches:
  - path: add-exporter-sidecar.yaml
# overlays/prod/kustomization.yaml
resources:
  - ../../base
components:
  - ../../components/monitoring

Unlike a base, a component is applied to the overlay's resources, so its patches can change objects that came from the base.

Example · Add a staging environment

Task: "add an overlay staging that deploys the base to namespace staging with 2 replicas of web and the environment variable FEATURE_X=on, and apply it."

mkdir -p app/overlays/staging && cd app/overlays/staging
cat > env.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  template:
    spec:
      containers:
        - name: web
          env:
            - name: FEATURE_X
              value: "on"
YAML
cat > kustomization.yaml <<'YAML'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - ../../base
namespace: staging
replicas:
  - name: web
    count: 2
patches:
  - path: env.yaml
YAML
kubectl create namespace staging
kubectl kustomize . | grep -E 'namespace:|replicas:|FEATURE_X' -A1
kubectl apply -k .
kubectl -n staging get deploy web -o jsonpath='{.spec.replicas} {.spec.template.spec.containers[0].env}{"\n"}'

The container name in the patch (web) must match the base, or the patch adds a second, broken container instead of changing the existing one.

Tricks

Common mistakes

  • A container name in the patch that does not match: a strategic merge patch then adds a new container without an image, and the apply fails.
  • replace on a path that does not exist in a JSON 6902 patch: the build fails. Use add.
  • A JSON 6902 patch without a target.
  • Patching by the prefixed name (prod-web) in an overlay: refer to the base name.
  • Applying the base instead of the overlay, so the environment's changes are missing.
  • Indenting a list item wrong in an inline patch: |- block: the patch text is YAML inside YAML.

Recap

  • patches takes a file (path) or inline text (patch) and an optional target.
  • Strategic merge patches are partial objects, merged by name, with $patch: delete to remove; JSON 6902 patches are op/path/value lists and need a target.
  • replicas and images change counts and tags without a patch.
  • A base holds shared manifests; overlays use resources: [../../base] and add their environment's changes; components hold optional features several overlays share.
  • Build with kubectl kustomize overlays/ENV, compare with kubectl diff -k, apply with kubectl apply -k.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Repair a Kustomize overlay that no longer builds, then write the production overlay from the same base.

    Build · Level 2 · standard · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.