Scaling and updating applications on Kubernetes: rolling updates, blue/green, canary, PDB, and HPA
How to update and scale applications without downtime: maxSurge and maxUnavailable, rollout status/history/undo/pause/resume, Recreate, blue/green with a selector switch, basic canary, PodDisruptionBudget, HPA v2 with behavior, and StatefulSets.
Kubernetes$ kubectl rollout undo deploy/web▍Getting a Deployment running is the easy part. The hard part is switching versions at three in the afternoon, under traffic, without taking anyone down, and being able to go back in seconds if the new version is broken. This guide picks up where deploying and scaling nginx left off and covers the update and scaling strategies Kubernetes offers, with real output from a kind cluster running Kubernetes 1.37, upgrading nginx from 1.28 to 1.29.
Rolling update: the default, but with the right parameters
RollingUpdate is the Deployment’s default strategy. It creates a new ReplicaSet and swaps pods gradually, guided by two parameters:
| Parameter | What it controls | Default |
|---|---|---|
maxSurge |
How many pods above replicas may exist during the switch |
25% |
maxUnavailable |
How many pods may be unavailable during the switch | 25% |
minReadySeconds |
How long a pod must stay ready to count as available | 0 |
progressDeadlineSeconds |
Time without progress before the rollout is marked as failed | 600 |
With maxSurge: 1 and maxUnavailable: 0, capacity never drops: Kubernetes starts a new pod, waits for it to be ready, and only then removes an old one. It is the safest setting for small services, at the cost of a slower rollout.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
annotations:
kubernetes.io/change-cause: "initial version nginx 1.28"
spec:
replicas: 4
revisionHistoryLimit: 5
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.28-alpine
ports:
- containerPort: 80
readinessProbe:
httpGet:
path: /
port: 80
periodSeconds: 2
The readinessProbe is what makes all of this meaningful. Without it, the pod counts as ready as soon as the container starts, and the rollout moves on even if the application does not respond yet.
Updating and following the rollout
kubectl -n d-rollout set image deploy/web nginx=nginx:1.29-alpine
kubectl -n d-rollout annotate deploy/web kubernetes.io/change-cause="update nginx to 1.29" --overwrite
kubectl -n d-rollout rollout status deploy/web
The Deployment’s events show exactly how maxSurge: 1 and maxUnavailable: 0 play out, one pod at a time:
$ kubectl -n d-rollout events --for deploy/web
Scaled up replica set web-65cd658cdf from 0 to 1
Scaled down replica set web-6dc4f8c478 from 4 to 3
Scaled up replica set web-65cd658cdf from 1 to 2
Scaled down replica set web-6dc4f8c478 from 3 to 2
Scaled up replica set web-65cd658cdf from 2 to 3
Scaled down replica set web-6dc4f8c478 from 2 to 1
Scaled up replica set web-65cd658cdf from 3 to 4
Scaled down replica set web-6dc4f8c478 from 1 to 0
The old --record flag is deprecated; today the way to record the reason for each revision is the kubernetes.io/change-cause annotation, which shows up in the history:
$ kubectl -n d-rollout rollout history deploy/web
REVISION CHANGE-CAUSE
1 initial version nginx 1.28
2 update nginx to 1.29
When the new version breaks: undo
We simulated a typo in the tag. With maxUnavailable: 0, the rollout gets stuck on the first new pod and the four old ones keep serving:
$ kubectl -n d-rollout set image deploy/web nginx=nginx:1.29-alpine-typo
$ kubectl -n d-rollout get pods
NAME READY STATUS RESTARTS AGE
web-58b596b478-6jswl 0/1 ImagePullBackOff 0 25s
web-65cd658cdf-9wwxh 1/1 Running 0 32s
web-65cd658cdf-dmdfl 1/1 Running 0 42s
web-65cd658cdf-jkx68 1/1 Running 0 37s
web-65cd658cdf-sp9p4 1/1 Running 0 48s
$ kubectl -n d-rollout rollout undo deploy/web
Warning: resource deployments/web was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, ...
deployment.apps/web rolled back
$ kubectl -n d-rollout rollout history deploy/web
REVISION CHANGE-CAUSE
1 initial version nginx 1.28
3 wrong tag
4 update nginx to 1.29
Two details. First, undo does not “go back” to revision 2: it promotes it as revision 4. Use rollout history --revision=N to inspect a revision and rollout undo --to-revision=N to pick the target. Second, take kubectl’s warning seriously: if you manage the Deployment with kubectl apply or GitOps, fix the manifest in Git right after, or the next apply will undo the rollback. With Argo CD, a rollback is usually a revert in the repository.
pause and resume
To batch several changes into a single rollout, pause the Deployment, apply everything, and resume:
kubectl -n d-rollout rollout pause deploy/web
kubectl -n d-rollout set image deploy/web nginx=nginx:1.28-alpine
kubectl -n d-rollout set resources deploy/web -c nginx --requests=cpu=50m,memory=32Mi
kubectl -n d-rollout rollout resume deploy/web
While paused, no pods are replaced. After the resume, the result was a single new ReplicaSet with both changes:
NAME REV IMG REQ DESIRED
web-58b596b478 3 nginx:1.29-alpine-typo <none> 0
web-65cd658cdf 4 nginx:1.29-alpine <none> 0
web-86546b65d8 6 nginx:1.28-alpine 50m 4
Readiness gates
Sometimes “the container responds” is not enough: the pod should only get traffic after an external system, such as a cloud load balancer, has registered it. That is what readinessGates are for. The pod declares an extra condition, and an external controller sets it to True:
spec:
readinessGates:
- conditionType: "example.com/lb-registered"
In the lab, with the container already ready, the pod stayed out of rotation until someone updated the condition:
Ready=False ReadinessGatesNotReady
ContainersReady=True
The AWS Load Balancer Controller uses this mechanism to hold the rollout until the target is healthy in the ALB.
Recreate: when two versions can’t coexist
With strategy.type: Recreate, Kubernetes takes down all old pods before creating the new ones. In the lab, right after set image, all four pods were Terminating and no new ones existed. There is downtime, but it is the right choice when the application cannot run two versions at once, for example because of an incompatible schema migration or a ReadWriteOnce volume.
Blue/green: two Deployments and a selector switch
In blue/green, the new version (green) comes up in full next to the current one (blue), and the cutover is a change to the Service’s selector:
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
version: blue
ports:
- port: 80
targetPort: 80
The web-blue (nginx 1.28) and web-green (nginx 1.29) Deployments use the labels app: web and version: blue|green. We checked the version through the Server header, with curl from a curlimages/curl pod inside the cluster:
$ curl -sI http://web | grep -i ^server
Server: nginx/1.28.3
$ kubectl -n d-rollout patch svc web -p '{"spec":{"selector":{"app":"web","version":"green"}}}'
$ curl -sI http://web | grep -i ^server
Server: nginx/1.29.8
Rollback is the reverse patch, and it is instant because blue is still running. The cost is keeping double the capacity during the validation window.
Basic canary with a replica ratio
Without any extra tooling, you can run a canary by removing the version label from the selector and controlling the ratio through the replica count. With 3 blue replicas and 1 green, 40 requests split like this:
30 Server: nginx/1.28.3
10 Server: nginx/1.29.8
That is 25%, as expected. The limitation is that granularity depends on replicas: for 1% of traffic you would need 100 pods. For percentage-based canaries with metric analysis and automatic promotion, use tools such as Argo Rollouts or Flagger, or split traffic with Gateway API or a service mesh. Argo Rollouts fits well into the Argo CD workflow.
PodDisruptionBudget: protecting against voluntary disruptions
Deployment rollouts respect maxUnavailable, but node drains, cluster upgrades, and the node autoscaler use the eviction API, which respects the PodDisruptionBudget:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-blue
spec:
maxUnavailable: 1
selector:
matchLabels:
app: web
version: blue
We tested it by calling the eviction API directly on two pods in a row. The first was accepted; the second was refused:
$ kubectl -n d-rollout get pdb
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
web-blue N/A 1 1 2s
{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Success","code":201}
Error from server (TooManyRequests): Cannot evict pod as it would violate the pod's disruption budget.
Watch out for impossible PDBs, such as minAvailable equal to the replica count: they block kubectl drain and node upgrades. The cluster upgrade guide shows where this usually hurts.
HPA v2: autoscaling with behavior
The autoscaling/v2 HorizontalPodAutoscaler adjusts replicas based on metrics, and the behavior block controls how fast it scales up and down:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-blue
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-blue
minReplicas: 3
maxReplicas: 12
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
- type: Pods
value: 4
periodSeconds: 30
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60
It scales up fast and down slowly, which avoids flapping. averageUtilization is relative to the CPU requests, so the pods must declare requests. And a resource-based HPA needs metrics-server. The lab cluster has no metrics-server, and this is the result:
$ kubectl -n d-rollout get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
web-blue Deployment/web-blue cpu: <unknown>/70% 3 12 3
Warning FailedGetResourceMetric failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)
To scale on queues, events, or external metrics, see KEDA. To adjust requests and limits automatically, there is the Vertical Pod Autoscaler (VPA), a separate project. Avoid running HPA and VPA on the same CPU metric for the same workload.
StatefulSets: partition and OnDelete
StatefulSets update one pod at a time, in descending index order. Two useful options:
RollingUpdatewithpartition: only pods with an index greater than or equal to the partition are updated, which works as a canary for databases and queues.OnDelete: nothing is replaced until you delete the pod manually.
With partition: 2 and 3 replicas, only the last pod got the new version:
POD IMAGE
db-0 nginx:1.28-alpine
db-1 nginx:1.28-alpine
db-2 nginx:1.29-alpine
Lower the partition to 0 when you are happy with the updated pod.
Checklist
- A
readinessProbeon every Deployment that receives traffic -
maxSurgeandmaxUnavailableset on purpose, not inherited from the defaults -
kubernetes.io/change-causeon every change and a tunedrevisionHistoryLimit - Rollback tested, with the manifest fixed in Git right afterward
- An achievable PodDisruptionBudget for every critical workload
- HPA with declared
requests, metrics-server installed, and a tunedbehavior - A strategy chosen per workload: rolling, Recreate, blue/green, or canary
A good rollout is boring: nobody notices it happened, and rolling back takes less time than explaining the problem.