Kubernetes Deployments
Kubernetes Deployments
Section titled “Kubernetes Deployments”A Deployment manages a set of identical pod replicas. It ensures the desired number of pods are running, handles rolling updates, and enables rollback.
Deployment YAML
Section titled “Deployment YAML”apiVersion: apps/v1kind: Deploymentmetadata: name: my-appspec: replicas: 3 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: containers: - name: my-app image: myrepo/my-app:1.0 ports: - containerPort: 8080 resources: requests: cpu: "100m" memory: "128Mi" limits: cpu: "500m" memory: "256Mi"kubectl apply -f deployment.yamlkubectl get deploymentskubectl get podsRolling Update Strategy
Section titled “Rolling Update Strategy”The default strategy replaces pods gradually with zero downtime:
strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 # max pods that can be down during update maxSurge: 1 # max extra pods above desired countRecreate is the alternative — it kills all old pods before starting new ones (causes downtime, useful when you cannot run two versions simultaneously).
Deploying a New Version
Section titled “Deploying a New Version”Update the image tag in the manifest and apply, or use kubectl set image:
kubectl set image deployment/my-app my-app=myrepo/my-app:2.0
# Watch the rollout progresskubectl rollout status deployment/my-appRollback
Section titled “Rollback”# Undo to the previous versionkubectl rollout undo deployment/my-app
# Undo to a specific revisionkubectl rollout history deployment/my-appkubectl rollout undo deployment/my-app --to-revision=2Scaling
Section titled “Scaling”# Scale to 5 replicaskubectl scale deployment my-app --replicas=5
# Or update replicas in the manifest and re-applyHorizontal Pod Autoscaler
Section titled “Horizontal Pod Autoscaler”Automatically scale based on CPU/memory:
kubectl autoscale deployment my-app --min=2 --max=10 --cpu-percent=70Or in YAML:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: my-app-hpaspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: my-app minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70Pausing and Resuming Rollouts
Section titled “Pausing and Resuming Rollouts”Useful when applying multiple changes at once:
kubectl rollout pause deployment/my-appkubectl set image deployment/my-app my-app=myrepo/my-app:2.0kubectl set env deployment/my-app ENVIRONMENT=productionkubectl rollout resume deployment/my-appCommon Commands
Section titled “Common Commands”kubectl get deploymentskubectl describe deployment my-appkubectl delete deployment my-appkubectl rollout history deployment/my-appkubectl rollout status deployment/my-app