Share with friends
Managing resources in a Kubernetes cluster is the most important aspect of orchestrating containerized applications. Whether you are deploying, scaling, or updating your application, having the right tools to perform these processes is essential.
One such powerful tool in the Kubernetes arsenal is the kubectl patch command. In this guide, we will take a closer look at the kubectl patch command, its types & how to use them, and much more.
In this blog, we will dive into the world of the kubectl patch command and explore how it empowers Kubernetes administrators and developers to perform updates to resources, unlocking a new level of flexibility and efficiency in resource management.
We will also uncover the workings of the kubectl patch command, understand its syntax, and showcase real-world examples to demonstrate its prowess.
What is Kubectl Patch?
As the name suggests, Kubectl Patch is a command line tool that allows you to update/change specific fields of Kubernetes resources without altering the whole definition, after they have been created.
If you communicate with Kubernetes clusters via kubectl CLI, then you might be familiar with the kubectl edit or kubectl apply subcommands.
Similarly, the kubectl patch command enables you to change part of a resource specification, specifying the changed part on CLI.
The kubectl patch command is used to alter a specific field of a Kubernetes resource when it already has been created or running in real-time.
In this way, you will not need to destroy or rebuild the whole resource which would save time and resources.
So instead of using kubectl apply where you would have to provide a whole new configuration for updating a small section, you can use kubectl patch.
Also Read: Kubernetes Clusters using Kubeadm
Types of Kubectl Patch & How to Use Them (with Examples)
There are three Kubectl Patch commands: Strategic Patch, JSON, and JSON Merge.
In this section, we will dive deep into these types of the kubectl patch command with real-life examples.
Strategic Patch
Strategic Patch is the default patch type and will basically either replace or merge values based on the object's patchStrategy
as defined in the Kubernetes source code.
Use Strategic Merge Patch when you want to update specific fields of a resource while preserving the unmentioned fields and their values.
Let's look at a quick example.
Create a sample Node.js application deployment by making a deployment file for it.
For this, create a deployment file with the following commands and save it as deployment.yaml, and the name of the deployment will be “node-application-deployment” as shown.
apiVersion: apps/v1
kind: Deployment
metadata:
name: node-application-deployment
spec:
replicas: 2
selector:
matchLabels:
app: node-app
template:
metadata:
labels:
app: node-app
spec:
containers:
- name: node-app-container
image: node:latest
ports:
- containerPort: 3000
Now, deploy it using the command
kubectl apply -f deployment.yaml
After checking the status of the pod which is up and running, if you want to change any field of this deployment like “No. of replicas”, you can do it through the Strategic Patch type of the kubectl patch command.
Create another file and name it is as “node_patch_replica.yaml” with the following content in it.
For changing the number of replicas from 2 to 5 or any desired no. you can have the following content in this file.
spec:
replicas: 5
Let's patch the above file named “node_patch_replica.yaml”. Use the following kubectl patch command to do so:
kubectl patch deployment node-application-deployment --patch-file node_patch_replica.yml
Now, if you check the instances which are running, they will be 5 - as per the changes you made.
This is how the strategic patch type of the kubectl patch command works.
Also Read: The Only Kubectl Cheatsheet You'll Ever Need
JSON
In JSON, you can provide a JSON or a YAML document which will include all the information regarding the changes you want to apply.
You should use JSON Patch when you need to perform fine-grained updates and want full control over the changes applied to a resource.
This JSON document contains an array of JSON Patch operations, each describing a specific change.
The three properties which are involved in each operation are “op”, “path”, and “value”.
Let's look at an example.
For changing the image version in the deployment file from “node:latest” to “alpine:3.17”, you will write a YAML file - “node_json_patch.yml”.
- op: replace
path: "/spec/template/spec/containers/0/image"
value: alpine:3.17
Here is the complete explanation of all the properties used, so that you can use them appropriately for each purpose.
- “op”: This signifies the type of operation which can be “add”, “remove”, or “replace”.
- “path”: The path defines the target location, where the operation has to be performed.
- “value”: As the name suggests, the value property contains the value and it is used for “add”, “remove” and “replace” operations.
- “from”: This operation is used for “move” and “copy” operations.
Now, using the kubectl patch command you can replace the image in the following way:
kubectl patch deployment node-application-deployment --type JSON --patch-file node_patch_json.yml
The above kubectl patch command and its respective output will look something like this:
Now, if you observe the file “node_patch_json.yml”, the image has been changed from “node:latest” to “alpine:3.17”.
You can confirm this by using the following command:
kubectl get deployment node-application-deployment -o=jsonpath='{.spec.template.spec.containers[0].image}'
The output of the above command will be “alpine:3.17”.
Strategic Merge Patch and JSON Patch might look similar but they clearly have their differences.
Strategic Merge Patch is more intuitive and human-friendly than JSON patches, as it allows you to focus on the fields you want to change without worrying about the rest.
JSON Patch is ideal for automated or programmatic updates, and also in cases when you require a detailed history of changes made to the resource.
Also Read: When to Use Kubectl Proxy Command
Merge or JSON Merge
The next type for the kubectl patch command is Merge (also called JSON Merge).
It allows you to naively override keys in an object i.e. it will blindly just replace the whole configuration code of the resource with the code provided by you.
Unlike its name, JSON merge does not merge the new code but totally replaces it.
You can use JSON Merge Patch when you want to replace the entire resource with a new set of values, leaving out any fields not explicitly specified.
For understanding it in a good way, you can add a new environment variable in your deployment with the name “MY_ENV_VAR” and a value “my_value”.
Create a file “json_merge_patch.yml” with the following content in it, which will create a new environment variable.
spec:
template:
spec:
containers:
- name: node-app-container
image: alpine:3.17
env:
- name: MY_ENV_VAR
value: "my-value"
While using the JSON type of the kubectl patch
command, the image was altered to “alpine:3.17”.
This is the reason why this image name is used in the “json_merge_patch.yml” file.
Now, the command for merging this file will be
kubectl patch deployment node-application-deployment --type merge --patch-file json_merge_patch.yml
You can confirm this by using the following command, which will give the output in this case “my-value” i.e. the value of the environment variable.
kubectl get deployment node-application-deployment -o=jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="MY_ENV_VAR")].value}'
JSON Merge Patch is convenient for quick modifications, but you have to be cautious to avoid inadvertently losing essential fields.
Is Using Kubectl Patch a Good Practice?
Using the kubectl patch command can be a good practice in certain situations, but like any tool or approach, it has its pros and cons.
Here are the advantages and disadvantages of using Kubect Patch.
Advantages of Using the Kubectl Patch Command
- Targeted updates: It works really well when you want to change some specific fields of the resource as it only works on the targeted areas.
- Fast: As it works on specific areas, the process is quite fast and faster than the kubectl apply command.
Also Read: When to Use Terraform Apply
Disadvantages of Kubectl Patch
- Complexity: It depends on the complexity of the update you want to offer, as the complexity increases it will lead to more nested structures and relationships. And it can be difficult to incorporate all this again and again in JSON or YAML formats.
- Validation: The moment you patch a code (YAML or JSON), the process will start, it will not check for the validation and hence it can carry some incorrections too.
- Tracking of Changes: Since the kubectl patch makes changes directly to the resource, hence it can be a little difficult to track those changes and especially in production environments.
Also Read: When to Use Kubectl Exec
Kubectl Patch vs Apply vs Edit vs Replace
All these Kubernetes commands (edit, replace, patch, and apply) are used for managing, updating, and monitoring your resources.
Here is a detailed explanation of these commands with their syntaxes and examples.
Kubectl Patch Command
kubectl patch is the command about which the whole blog has been entirely about. It works on targeted areas of Kubernetes resources so that we can change or update or add some fields in runtime.
Also Read: Top Container Runtimes to Choose From
Kubectl Edit Command
The kubectl edit command allows you to make changes to the resources interactively, by opening the default text editor present on your system.
Here is an example of how can use the edit command:
Let's say you have a deployment “sample-application-deployment” in the namespace “default” and you want to change the number of replicas from 3 to 5.
So, you can use the kubectl edit command to make this change as follows:
kubectl edit deployment sample-application-deployment -n default
This command will open the default text editor (e.g. vim, Nano, etc.) in your system from where we can make all the changes and save it.
Also Read: How to Use Kubectl Rollout Restart
Kubectl Apply Command
The kubectl apply
command is used to create resources like deployments.
You can also use kubectl apply
to update an existing resource by changing the configuration settings in the given manifest file.
The command set kubectl apply is used at a terminal's CLI window to create or modify Kubernetes resources defined in a manifest file.
In this case, the manifest file will be “my_deployment.yaml”.
kubectl apply -f my_deployment.yaml
Also Read: How to Use Kubectl Port Forward in Kubernetes
Kubectl Replace Command
The kubectl replace command allows you to replace a resource completely with a new one which means that you can have a fresh start by doing everything once again.
This is useful when you have created a lot of hassle in the configuration and now you have to start with a clean slate.
Here's how you can use the kubectl replace command.
Let's say you have a deployment file called “my_deployment.yml” and you forgot to add an environment variable to it.
You can make a new file naming it “new_my_deployment.yml” with the updated code and then use the following command.
kubectl replace -f new_my_deployment.yml
Kubectl Patch Command: Final Words
To summarise it all, the kubectl patch
command offers a powerful and granular approach to updating Kubernetes resources, preserving existing configurations, and reducing resource usage.
Alongside kubectl apply
, kubectl edit
, and kubectl replace
, it adds versatility to Kubernetes resource management.
Understanding when to use each command is crucial for effective Kubernetes administration.
You can use the flexibility of the kubectl patch
for small, targeted updates, and leverage other commands when dealing with complex changes or more extensive resource modifications.
Share with friends