kubectl patch -- Targeted Resource Updates
kubectl patch lets you update specific fields of a resource without replacing the entire object. It supports three patch strategies, each suited for different use cases.
Strategic Merge Patch (Default)
The default patch type merges your changes into the existing resource. You only specify the fields you want to change:
# Update replica count
kubectl patch deployment my-app -p '{"spec":{"replicas":5}}'
# Add an annotation
kubectl patch deployment my-app -p '{"metadata":{"annotations":{"team":"backend"}}}'
# Update a container image
kubectl patch deployment my-app -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image":"nginx:1.27"}]}}}}'
Strategic merge patch is smart about lists. When patching the containers list, it matches by the name field and merges rather than replacing the entire list.
JSON Merge Patch
JSON merge patch replaces objects and arrays entirely rather than merging them:
kubectl patch deployment my-app \
--type merge \
-p '{"spec":{"replicas":3}}'
The key difference: if you patch a list with JSON merge, the entire list is replaced. Use this when you want to overwrite rather than merge.
JSON Patch (RFC 6902)
JSON patch uses an array of explicit operations. It gives you the most control:
# Add a label
kubectl patch deployment my-app --type json \
-p '[{"op":"add","path":"/metadata/labels/version","value":"v2"}]'
# Replace the replica count
kubectl patch deployment my-app --type json \
-p '[{"op":"replace","path":"/spec/replicas","value":5}]'
# Remove an annotation
kubectl patch deployment my-app --type json \
-p '[{"op":"remove","path":"/metadata/annotations/old-annotation"}]'
Supported operations are add, remove, replace, move, copy, and test.
Patching from a File
For complex patches, use a file instead of inline JSON:
# patch.yaml
spec:
template:
spec:
containers:
- name: nginx
resources:
limits:
memory: "512Mi"
cpu: "500m"
kubectl patch deployment my-app --patch-file patch.yaml
Choosing the Right Patch Type
| Scenario | Patch Type |
|---|---|
| Update a simple field | Strategic merge (default) |
| Replace an entire list | JSON merge |
| Add/remove specific list items | JSON patch |
| Complex multi-operation change | JSON patch |
Key Takeaways
- Strategic merge patch (default) is best for most field updates
- JSON merge patch replaces entire objects and arrays
- JSON patch gives operation-level control with add, remove, and replace
- Use
--patch-filefor complex patches to avoid quoting issues - Patch is ideal for scripted, non-interactive updates