kubectl patch: Changing Kubernetes Objects in Place

What Is the kubectl patch Command? 

kubectl patch is a command line option for updating Kubernetes API objects. You can use it to update a running configuration by specifying a section to update, instead of providing a completely new configuration.

The kubectl patch command is a versatile utility that allows you to update live objects in your Kubernetes cluster. Think of it as an essential tool for making quick, precise changes to your Kubernetes resources without having to delve into full-scale configuration edits.

The command works by “patching” changes onto the current resource configuration. Unlike a kubectl replace operation, the patch operation only modifies specific fields in the resource configuration. There are three types of patching: strategic merge, JSON merge patch, and JSON patch. Strategic merge type tries to “do the right thing” when merging a given spec with the current spec.

An alternative to kubectl patch is to use kubectl apply to update an object in Kubernetes, changing only specific settings, while keeping the rest of the object configuration unchanged.

This is part of a series of articles about kubectl cheat sheet.

kubectl patch vs. kubectl edit vs. kubectl apply: What Is the Difference? 

Let’s review the differences between three commands that have a similar purpose: kubectl patch, edit, and apply.

kubectl edit allows you to directly edit any resource live on the server. While this can be handy for making quick changes, it can also lead to accidental alterations. This is because kubectl edit opens up the entire configuration for editing, and it’s easy to unintentionally modify something else in the process.

kubectl apply manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster. This approach is great for tracking changes to configurations over time. However, it is more suitable for situations where you have a new configuration file that you want to apply, rather than for making selective changes.

kubectl patch strikes a balance between the two. It allows for precise, quick modifications without exposing the entire configuration or needing a new configuration file.

How kubectl patch Works 

The kubectl patch command works by taking in three arguments: the type of the resource, the name of the resource, and the patch string. The patch string is a JSON format string that describes the changes to be made to the resource.

For instance, if you want to change the image of a deployment named ‘myapp’ to ‘nginx:1.16’, you would use the following command:

kubectl patch deployment python-app -p '{"spec": {"template": {"spec": {"containers": [{"name": "testapp", "image": "nginx:1.16"}]}}}}'

This command tells Kubernetes to find the deployment named ‘myapp’ and change the image to ‘nginx:1.16’.

There are three primary strategies for patching in Kubernetes:

  • JSON patch allows you to specify an array of operations that should be applied to the resource in a specific order.
  • Merge patch is a simple way to declare the changes you want to make. You simply provide a partial resource specification that includes the changes you want, and Kubernetes will merge your changes with the existing resource.

Strategic merge patch is a more complex and powerful strategy. It allows for more sophisticated modifications, like adding or removing elements from a list.

Use Cases for kubectl patch with Examples 

Updating Container Image

One common use case for the kubectl patch command is updating the image of a running container. This is often necessary when you’ve pushed a new version of your application and want to update the image without causing downtime.

To update the image of a deployment named ‘myapp’ to ‘nginx:1.16’, you can use the kubectl patch command as follows:

kubectl patch deployment python-app -p '{"spec": {"template": {"spec": {"containers": [{"name": "testapp", "image": "nginx:1.18"}]}}}}'

This will cause Kubernetes to create a new ReplicaSet with the new image and slowly roll it out according to your deployment strategy.

Scaling Replicas

Another common use case for the kubectl patch command is scaling the number of replicas for a deployment. This is often necessary when you need to handle increasing load, but don’t want to manually update the deployment configuration.

To scale the number of replicas of a deployment named ‘myapp’ to 5, you can use the kubectl patch command as follows:

kubectl patch deployment python-app -p '{"spec": {"replicas": 5}}'

This will tell Kubernetes to adjust the number of replicas for the ‘myapp’ deployment to 5, effectively scaling up your application.

Enabling or Disabling Features

One of the most common use cases for the kubectl patch command is enabling or disabling features of a running application. For instance, you might have a feature flag that controls whether a particular feature is active or not. With the kubectl patch command, you can easily switch this flag on or off without having to redeploy your application.

If you have a development environment where you frequently need to toggle features, the patch command can save you a lot of time. Instead of editing your YAML files and applying them, you can use a single command to change the state of your application. This not only simplifies the process but also reduces the risk of making mistakes.

For example, let’s say you have a ConfigMap that controls a feature flag. The key is feature-x and you want to turn it on. You can use the kubectl patch command to change the value as follows:

kubectl patch configmap my-configmap -p '{"data": {"feature-x": "on"}}'

Updating Resource Limits/Requests

In a Kubernetes environment, resource management is crucial. You need to ensure that each of your running pods has the resources it needs to function effectively. This is where the kubectl patch command comes in handy.

With this command, you can update the resource limits and requests of your running pods without having to take them down. This means you can scale your applications up or down depending on their current needs without causing any downtime.

This functionality is particularly useful in a production environment where uptime is crucial. By using the patch command, you can ensure that your applications always have the resources they need.For example, if you want to change the CPU request and limit of a deployment named myapp to 1 and 2, respectively, you would use the following command:

kubectl patch deployment python-app -p '{"spec": {"template": {"spec": {"containers": [{"name": "python-app", "image": "nginx:latest", "resources": {"limits": {"cpu": "2"}, "requests": {"cpu": "1"}}}]}}}}'

Learn more in our detailed guide to kubectl scale deployment (coming soon)

Common Issues With kubectl patch and How to Resolve Them 

Invalid Patch Format

One of the most common issues you might run into when using the kubectl patch command is an invalid patch format. This usually happens when the patch you’re trying to apply doesn’t match the format expected by Kubernetes.

To resolve this issue, you first need to understand the different patch formats for JSON patch, JSON merge patch, and strategic merge patch. Refer to the official documentation to learn the correct format for each of these.

Patch Does Not Apply

Another common issue is that your patch might not apply. This can happen for a variety of reasons, such as a conflict between your patch and the current state of the object you’re trying to update.

If you encounter this issue, the first step is to check the error message for details. The message should tell you why the patch failed to apply, which can help you figure out what to do next.

If the patch failed due to a conflict, you might need to fetch the latest version of the object and reapply your patch. Alternatively, you could use a two-way strategic merge patch, which can automatically resolve certain types of conflicts.

Wrong Patch Strategy

Sometimes, the issue might be that you’re using the wrong patch strategy. Kubernetes supports several different patch strategies, and using the wrong one can cause your patch to fail.

If you’re not sure which patch strategy to use, it’s usually best to start with the strategic merge patch. This strategy works well for most use cases and is often the easiest to use.

No Changes Detected

Finally, you might run into an issue where no changes are detected. This can happen if the patch you’re trying to apply doesn’t actually change anything.

To resolve this issue, double-check your patch to make sure it’s correct. If the patch is correct, the issue might be that the object you’re trying to update already has the changes you’re trying to apply.In this case, you might not need to do anything. However, if you want to ensure that your patch applies successfully, you could try using the --force flag. This will force Kubernetes to apply the patch, even if no changes are detected.

Kubernetes Troubleshooting With Komodor

Kubernetes is a complex system, and often, something will go wrong, simply because it can. In situations like this, you’ll likely begin the troubleshooting process by reverting to some of the above kubectl commands to try and determine the root cause. This process, however, can often run out of hand and turn into a stressful, ineffective, and time-consuming task.

This is the reason why we created Komodor, a tool that helps dev and ops teams stop wasting their precious time looking for needles in (hay)stacks every time things go wrong.

Acting as a single source of truth (SSOT) for all of your k8s troubleshooting needs, Komodor offers:

  • Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
  • In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs and etc. All within one pane of glass with easy drill-down options.
  • Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
  • Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.

Related content: Read our guide to kubectl rollout.

If you are interested in checking out Komodor, use this link to sign up for a Free Trial.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.