kubectl-patch
Patch live Kubernetes resources
TLDR
Partially patch a secret using a strategic merge JSON patch to remove the finalizer
Partially patch a secret using a strategic merge YAML patch to remove the finalizer
Partially patch a pod's container using a JSON patch with positional arrays
Update a deployment's replicas through the scale subresource using a strategic merge JSON patch
SYNOPSIS
kubectl patch (TYPE NAME | -f FILENAME) --patch PATCH [--type=PATCH_TYPE] [options]
Where:
TYPE NAME: Specifies the kind of resource and its name to patch (e.g., deployment my-app).
-f FILENAME: Specifies one or more files containing the resource definition to patch.
--patch PATCH: The actual patch content, typically a JSON or YAML string, detailing the changes to apply.
--type=PATCH_TYPE: Defines the patch strategy to use. Valid values are strategic, merge, or json. Defaults to strategic.
[options]: Additional flags to control behavior like namespace, output format, or dry-run.
PARAMETERS
TYPE NAME
Identifies the resource to patch by its kind and name (e.g., pod my-pod, deployment my-app).
-f, --filename stringArray
Path to one or more files containing resource definitions to patch, or a directory of files.
--patch string
Required. The patch content. Must be a JSON or YAML string representing the desired changes.
--type string
The type of patch being provided: strategic (default), merge, or json.
-n, --namespace string
If present, the namespace scope for this request. Defaults to the current namespace in the kubeconfig.
--dry-run string
If true, only print the object that would be sent, without sending it. Valid values are 'client', 'server', 'none'.
-o, --output string
Output format. One of: json|yaml|wide|name|go-template|jsonpath, etc. Useful with --dry-run.
--local bool
If true, apply the patch to the local file without sending to the API server. Useful for validating patches against local files.
--subresource string
If specified, patch a subresource of the resource (e.g., 'status', 'scale').
DESCRIPTION
kubectl patch provides a powerful and flexible way to modify specific fields of live Kubernetes objects without needing to retrieve, edit, and reapply the entire resource definition. This command is essential for making targeted updates, such as changing a container image, adding a label, or scaling a deployment, without causing unnecessary disruption or overwriting other configuration changes. It supports various patch strategies—Strategic Merge Patch (default for Kubernetes API objects), JSON Merge Patch, and JSON Patch—allowing users to choose the appropriate method for their specific update requirements. kubectl patch is particularly useful in automation scripts and for quick, iterative adjustments to running resources, offering fine-grained control over resource configuration.
CAVEATS
kubectl patch is a powerful tool but requires careful use due to the direct manipulation of live resources.
Patch Types: Understanding the differences between strategic (default), merge, and json patch types is crucial. Misunderstanding them can lead to unexpected behavior, especially concerning list merging or field deletion. Strategic merge patch attempts to be intelligent about known Kubernetes schema, while JSON merge patch and JSON patch (RFC 6902) offer more predictable but sometimes more verbose control.
Concurrency: When multiple users or automated systems are patching the same resource concurrently, race conditions can occur. It's often safer to use kubectl apply for declarative management where conflicts are handled more gracefully.
Permissions: Proper Role-Based Access Control (RBAC) permissions are required to patch resources. Insufficient permissions will result in authorization errors.
Error Handling: An invalid patch content (e.g., malformed JSON/YAML or attempting to change immutable fields) will result in API server errors. Always test patches, preferably with --dry-run.
UNDERSTANDING PATCH TYPES
Strategic Merge Patch (default): This is the default and most commonly used patch type for Kubernetes API objects. It uses schema information to perform intelligent merges. For instance, lists might be merged based on a key (e.g., container names), or replaced entirely, depending on the schema definition.
JSON Merge Patch (--type=merge): A simpler, RFC 7386 compliant patch. It merges object fields: if a field is present in the patch, it replaces the existing field; if a field is null in the patch, it deletes the existing field. Arrays are always replaced entirely, not merged.
JSON Patch (--type=json): An RFC 6902 compliant patch type. This is the most precise method, allowing specific operations like add, remove, replace, move, copy, and test on exact paths within the JSON document. It requires a more verbose syntax but offers fine-grained control over changes.
EXAMPLES OF USAGE
- Update a deployment's image using Strategic Merge Patch:
kubectl patch deployment my-deployment -p '{"spec":{"template":{"spec":{"containers":[{"name":"my-container","image":"new-image:v2.0"}]}}}}' - Add a label to a service using Strategic Merge Patch:
kubectl patch service my-service -p '{"metadata":{"labels":{"new-label":"new-value"}}}' - Change replica count for a deployment using Strategic Merge Patch:
kubectl patch deployment my-deployment --type='strategic' -p '{"spec":{"replicas":5}}' - Delete a specific environment variable using JSON Patch:
kubectl patch deployment my-deployment --type='json' -p '[{"op": "remove", "path": "/spec/template/spec/containers/0/env/1"}]'
(Note: This requires knowing the exact array index; often kubectl set env is simpler for env var management.) - Replace an entire list (e.g., ports) using JSON Merge Patch:
kubectl patch service my-service --type='merge' -p '{"spec":{"ports":[{"port":8080,"targetPort":80,"protocol":"TCP"}]}}'
(This would replace all existing ports with the one specified.)
HISTORY
The kubectl patch command has been a fundamental part of the kubectl utility since early versions of Kubernetes, providing direct interaction with the Kubernetes API for modifying live objects. Its capabilities have evolved alongside the Kubernetes API itself, with the introduction of different patch strategies (like JSON Patch and JSON Merge Patch in addition to the original Strategic Merge Patch) to offer more granular and robust control over resource updates. It remains a key tool for both manual administrative tasks and automated operational workflows.


