Working with Kustomize
1. Understanding Kustomize Concepts
| Concept | Detail |
|---|---|
| base | Common manifests |
| overlay | Env-specific patches |
| No templating | Pure YAML + strategic merge |
2. Creating kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: prod
namePrefix: prod-
commonLabels: { env: prod, owner: platform }
resources:
- deployment.yaml
- service.yaml
patches:
- path: replica-patch.yaml
images:
- name: nginx
newTag: 1.27-alpine
3. Applying Kustomize Manifests
kubectl apply -k overlays/prod
kubectl diff -k overlays/prod
kubectl delete -k overlays/prod
4. Using Strategic Merge Patches
# replica-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata: { name: web }
spec:
replicas: 5
5. Using JSON Patches
patches:
- target: { kind: Deployment, name: web }
patch: |-
- op: replace
path: /spec/template/spec/containers/0/image
value: nginx:1.27
- op: add
path: /metadata/annotations/owner
value: platform
6. Configuring Name Prefixes
namePrefix: prod-
nameSuffix: -v2
7. Generating ConfigMaps
configMapGenerator:
- name: app-config
literals: [LOG_LEVEL=info, FEATURE_X=true]
files: [config.yaml]
options: { disableNameSuffixHash: false }
Note: Hash suffix triggers automatic rolling restart when content changes.
8. Generating Secrets
secretGenerator:
- name: db
type: Opaque
envs: [.env.prod]
options: { disableNameSuffixHash: false }
9. Setting Common Labels
commonLabels:
app.kubernetes.io/managed-by: kustomize
env: prod
commonAnnotations:
owner: platform-team
10. Using Overlays
app/
├── base/
│ ├── kustomization.yaml
│ ├── deployment.yaml
│ └── service.yaml
└── overlays/
├── dev/kustomization.yaml # resources: [../../base]
├── stage/kustomization.yaml
└── prod/kustomization.yaml
11. Configuring Image Tags
images:
- name: my-app
newName: registry.io/team/my-app
newTag: v2.3.1
digest: sha256:abcd...
12. Building Kustomize Output
kustomize build overlays/prod
kustomize build overlays/prod | kubectl apply -f -
kustomize build overlays/prod --enable-helm # render Helm charts