When managing applications in Kubernetes, you may need to update the container image in a deployment to apply new changes or fixes. This tutorial covers different methods to update the image in a Kubernetes deployment.
Update the Image Using kubectl set image
Kubernetes provides a simple way to update the image of a running deployment without modifying the YAML file.
Command:
kubectl set image deployment/<deployment-name> <container-name>=<new-image>:<tag>
Example:
kubectl set image deployment/nginx-deployment nginx-container=nginx:1.21
This updates the nginx-container
inside the nginx-deployment
to use the nginx:1.21
image.
Check the rollout status:
kubectl rollout status deployment/nginx-deployment
Rollback in case of failure:
If something goes wrong, you can roll back to the previous version:
kubectl rollout undo deployment/nginx-deployment
Update the Image by Modifying the Deployment YAML File
If you prefer to update the image in the deployment configuration file, follow these steps:
- Edit the Deployment YAML File (
deployment.yaml
)
apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: template: spec: containers: - name: nginx-container image: nginx:1.21 # Update the image here
2. Apply the Changes
kubectl apply -f deployment.yaml
Force a Deployment Update Without Changing the YAML
If you’re using an image tag like latest
and need Kubernetes to pull the new version, you can force a restart using the following command:
kubectl patch deployment <deployment-name> -p \ '{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubernetes.io/restartedAt":"'$(date +%Y-%m-%dT%H:%M:%S%z)'"}}}}}'
This triggers a new rollout without modifying the YAML file.
Verify the Update
After updating the image, ensure the pods are running the new version:
kubectl get pods kubectl describe pod <pod-name>
You can also check the logs to confirm the updated container is working correctly:
kubectl logs -f <pod-name>