Kubernetes Deployments: Rolling Updates and Rollbacks
Deployments are the standard way to manage stateless applications in Kubernetes. They provide declarative updates, rollbacks, and scaling capabilities.
Creating Deployments
# Imperative command
kubectl create deployment nginx --image=nginx:1.19 --replicas=3
# Generate YAML
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deploy.yamlYAML Definition
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.19
ports:
- containerPort: 80Scaling
# Scale deployment
kubectl scale deployment nginx --replicas=5
# Autoscale based on CPU
kubectl autoscale deployment nginx --min=3 --max=10 --cpu-percent=80Rolling Updates
Update Strategy
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Max pods over desired
maxUnavailable: 0 # Max pods unavailablePerforming Updates
# Update image
kubectl set image deployment/nginx nginx=nginx:1.20
# Edit deployment directly
kubectl edit deployment nginx
# Watch rollout status
kubectl rollout status deployment/nginxRollbacks
# Check rollout history
kubectl rollout history deployment/nginx
# View specific revision
kubectl rollout history deployment/nginx --revision=2
# Rollback to previous version
kubectl rollout undo deployment/nginx
# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=1Pausing and Resuming
# Pause rollout (for multiple changes)
kubectl rollout pause deployment/nginx
# Make changes
kubectl set image deployment/nginx nginx=nginx:1.21
kubectl set resources deployment/nginx -c=nginx --limits=memory=256Mi
# Resume rollout
kubectl rollout resume deployment/nginxDeployment Strategies
Rolling Update (Default)
Gradually replaces old pods with new ones.
Recreate
All old pods deleted before new ones created. Use for breaking changes.
spec:
strategy:
type: RecreateCommon Exam Tasks
- Create deployment with specific replicas
- Update deployment image
- Rollback to previous version
- Scale deployment
- View rollout history
Practice Deployments
Deployment management is heavily tested in CKA and CKAD. Practice with Sailor.sh.