Replacing a Container Using a JSON 6902 Patch
To update the container by changing its name and image, you can use a JSON 6902 patch. In yourkustomization.yaml file, the patch targets the specific Deployment object and applies a replace operation on the container at index 0. Remember that list indexes start at 0; hence, the first (and only) container is at index 0.
Replacing a Container Using a Strategic Merge Patch
Alternatively, a strategic merge patch can update a container. With this method, you create a separate patch file (for example,label-patch.yaml) that specifies the container properties to be merged with the original configuration. The patch file identifies the container by name (in this case, “nginx”) and details the new image.
Assuming your original deployment configuration is as shown above, your label-patch.yaml might look like this:
kustomization.yaml file, reference the patch as follows:
Adding a Container to the List Using a JSON 6902 Patch
To add a second container to your Deployment, you can use a JSON 6902 patch with an “add” operation. The dash (-) at the end of the path indicates that the new container should be appended to the existing list.
Given the initial one-container configuration, the following patch adds a second container:
containers/ signals Kustomize to append the new container. After applying the patch, the Deployment will include two containers: the original “nginx” container and the added “haproxy” container.
Below is a representation of the final configuration after adding the new container:
Deleting a Container from the List Using a JSON 6902 Patch
Next, we demonstrate how to remove an item from the list. Consider a Deployment configuration with two containers—one named “web” running nginx and another named “database” running mongo:If you are working with multiple containers, always verify the correct index of the container you want to modify. Misidentifying the index can lead to unexpected configuration errors.
Deleting a Container Using a Strategic Merge Patch
Another method to remove a container is by using a strategic merge patch. In this approach, you create a patch file (for example,label-patch.yaml) and leverage the $patch: delete directive, which explicitly marks the container for removal. Using the previous configuration that contains both “web” and “database” containers, the patch to delete the “database” container is as follows:
kustomization.yaml like so:
Each patch example in this guide illustrates how to manipulate list items in a Kubernetes configuration—whether replacing, adding, or deleting containers—using both JSON 6902 patches and strategic merge patches. For more information on Kubernetes patching techniques, please refer to the Kubernetes Documentation. Happy patching!