Deployments, rollouts & scaling
A Deployment is how you run a stateless app on Kubernetes: it keeps the right number of pods alive, replaces them one by one when you ship a new version, and lets you roll back in one command. This chapter shows a production-shaped Deployment and everything you do with it after the first kubectl apply.
Deployment, ReplicaSet, Pod
A Deployment doesn't create pods itself. It creates a ReplicaSet, whose only job is "keep exactly N pods matching this template running". The pod names show the chain:
$ kubectl get deploy,rs,pods -l app=web
deployment.apps/web 3/3
replicaset.apps/web-7c9d8f6b5 3 # deployment name + template hash
pod/web-7c9d8f6b5-x2kq9 Running # replicaset name + random suffix
Every time you change the pod template (image, env vars, resources...), the Deployment creates a new ReplicaSet and shifts pods from the old one to the new one. Old ReplicaSets are kept, scaled to 0, which is what makes rollback possible. Changing only replicas doesn't start a rollout.
A production-shaped Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
app: web
spec:
replicas: 3
revisionHistoryLimit: 5 # old ReplicaSets kept for rollback (default 10)
selector:
matchLabels:
app: web # can't be changed after creation
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # at most 1 extra pod during a rollout
maxUnavailable: 0 # never go below 3 ready pods
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: demee/app:1.1
ports:
- containerPort: 3000
resources:
requests: # what the scheduler reserves on a node
cpu: 100m # 0.1 of a CPU core
memory: 128Mi
limits: # hard ceiling
cpu: 500m # above this: throttled (slowed down)
memory: 256Mi # above this: container is OOMKilled
startupProbe: # allows up to 30 x 5s = 150s to start
httpGet:
path: /healthz
port: 3000
periodSeconds: 5
failureThreshold: 30
readinessProbe: # ready to receive traffic?
httpGet:
path: /ready
port: 3000
periodSeconds: 5
livenessProbe: # still alive, or stuck?
httpGet:
path: /healthz
port: 3000
periodSeconds: 10
failureThreshold: 3
Requests are used for scheduling: a pod only goes to a node with that much unreserved CPU and memory. Limits are enforced while it runs. CPU is measured in cores or millicores (500m = half a core), memory in Mi/Gi (mebibytes/gibibytes).
Liveness vs readiness vs startup probes
| Probe | Question it asks | When it fails |
|---|---|---|
| startup | Has the app finished starting? | The other two probes wait until it succeeds. If it never does, the container is restarted |
| readiness | Can it handle requests right now? | The pod is taken out of the Service's endpoints (gets no traffic). Not restarted |
| liveness | Is it alive, or hung? | The kubelet kills and restarts the container |
A probe can be httpGet (any 200-399 status passes), tcpSocket, exec (a command must exit 0) or grpc. Defaults if you don't set them: every 10 s, 1 s timeout, 3 failures in a row. Two classic mistakes: a liveness probe that checks the database (the database blips and every pod restarts at once), and a liveness probe with no startup probe on a slow-starting app (it gets killed before it's up, forever: CrashLoopBackOff).
Rolling updates
With RollingUpdate, Kubernetes starts new pods and removes old ones gradually, only moving on as new pods become ready. Two knobs control the pace:
maxSurge: how many pods above the desired count may exist during the rollout.maxUnavailable: how many pods below the desired count may be unavailable.
Both default to 25%; surge rounds up and unavailable rounds down, so with 3 replicas the default is also 1 and 0. The other strategy, Recreate, deletes all old pods before creating new ones: brief downtime, but useful when two versions must never run at the same time.
$ kubectl set image deployment/web web=demee/app:1.2 # or edit the YAML and apply
$ kubectl rollout status deployment/web # waits and reports progress
$ kubectl annotate deployment/web kubernetes.io/change-cause="bump to 1.2"
$ kubectl rollout history deployment/web # revisions + change-cause
$ kubectl rollout history deployment/web --revision=3 # what revision 3 contained
$ kubectl rollout undo deployment/web # back to the previous revision
$ kubectl rollout undo deployment/web --to-revision=2
$ kubectl rollout restart deployment/web # new pods, same spec
If new pods never become ready, the rollout simply stalls: with maxUnavailable: 0 the old pods keep serving. After progressDeadlineSeconds (default 600) rollout status reports that the deployment exceeded its progress deadline. Kubernetes does not roll back by itself; that's your rollout undo. Note that an undo is recorded as a new revision number.
Scaling by hand
$ kubectl scale deployment/web --replicas=5
Remember that the next kubectl apply of your YAML sets replicas back to whatever the file says.
Autoscaling with a HorizontalPodAutoscaler
An HPA changes replicas for you based on metrics:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # % of the pods' CPU *request*
It aims for desired = ceil(current replicas × current usage / target): 3 pods averaging 140% against a 70% target becomes 6. Scaling up is quick; by default it waits 5 minutes of lower load before scaling down, to avoid flapping.
- Utilization is a percentage of requests, so the containers must have CPU requests set.
- It needs metrics-server installed. Test with
kubectl top pods: if that errors, so will the HPA, andkubectl get hpashows<unknown>in the TARGETS column. On minikube:minikube addons enable metrics-server; elsewhere apply the manifest from the metrics-server GitHub releases. - When an HPA owns a Deployment, remove
replicasfrom the Deployment YAML, or every apply will fight the autoscaler.
$ kubectl get hpa web --watch # current vs target, replica count
$ kubectl describe hpa web # events explain every scaling decision