Skip to Content

Kubernetes Field Guide · Chapter 4 of 16

Deployments: rollouts, rollbacks and self-healing

You almost never create pods by hand. A Deployment keeps the right number running and replaces them, a few at a time, when you ship a new version. Learn to roll out without downtime, notice a bad release and roll it back in one command.

  • 40 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Kubernetes in production. Updated .

Deployment: webimage v2, replicas 3ReplicaSet v1scaling down 3 → 1v1v1v1ReplicaSet v2scaling up 0 → 3v2v2v2Old pods leave only after new ones are ready.kubectl rollout undo brings v1 back the same way
The chapter in one pictureA rollout is two ReplicaSets trading places, one pod at a time.

By the end you can

0 of 5

Deployments and ReplicaSets

A Deployment manages ReplicaSets, and each ReplicaSet manages identical pods. You only ever touch the Deployment:

  • The ReplicaSet keeps exactly N pods matching one pod template alive. That is the reconcile loop from chapter 1.
  • The Deployment creates a new ReplicaSet every time the pod template changes (a new image, an env var, a resource change) and shifts pods from the old one to the new one.

That is why pod names look like web-6c9b8d7f5d-4xk2p: Deployment name, then a hash of the pod template that names the ReplicaSet, then a random suffix.

web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 4
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app: web
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.26
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: 50m
              memory: 64Mi
            limits:
              memory: 128Mi
Which pods this Deployment owns. Must match the template labels and cannot be changed later.
How many old ReplicaSets to keep for rollbacks. The default is 10.
At most one pod above the replica count during a rollout.
Never drop below 4 ready pods. Safest, but needs room for the surge pod.
The pod from chapter 3. Changing anything here triggers a rollout.

Rolling updates

The default strategy replaces pods gradually. Two numbers control the pace: maxSurge (how many extra pods may exist) and maxUnavailable (how many may be missing). Both default to 25%, rounded up for surge and down for unavailable. Try the combinations, then ship a broken version:

Interactive

Rolling update, one tick at a time

available 4/4pods 4serving v1

    Filled pods are ready and receive traffic. Dashed pods are starting, failing or terminating.

    Three things to notice:

    • A broken release does not take you down. Old pods are removed only when new pods become ready, so a crashing version stalls with the old one still serving. This only works if "ready" means something, which is why readiness probes (chapter 10) matter so much.
    • Surge is a capacity cost. maxSurge: 1, maxUnavailable: 0 is the safest setting but needs room for one more pod. On a full cluster, the surge pod sits Pending and the rollout cannot start.
    • Stuck rollouts are reported, not fixed. After progressDeadlineSeconds (600 by default) the Deployment's condition says ProgressDeadlineExceeded. Kubernetes does not roll back by itself.

    Rollbacks and revision history

    Because each version is a ReplicaSet, rolling back is just scaling the previous ReplicaSet up again. It is fast because the old image is usually still cached on the nodes.

    Terminal
    kubectl rollout history deployment/web
    kubectl rollout undo deployment/web
    kubectl rollout undo deployment/web --to-revision=2
    
    history
    Lists revisions. The CHANGE-CAUSE column shows the kubernetes.io/change-cause annotation if you set it.
    undo
    Back to the previous revision.
    --to-revision
    Back to a specific one.

    Recreate, blue-green and canary

    A rolling update is one way to ship. Play the same release four ways and watch two things: whether the traffic bar ever goes red (nothing serving), and how many pods you are paying for at the peak.

    Interactive · Strategy race

    One release, four strategies. Same four replicas.

    v1 v2 starting · bar: share of traffic on v2

    In short:

    StrategyHowUse whenCost
    Rolling updateReplace pods a few at a timeThe default for stateless appsRoom for the surge pods
    RecreateStop all old pods, then start newTwo versions must never run together, such as a single-writer volumeDowntime, no extra capacity
    Blue-greenRun a full new copy, then switch the Service selectorYou need instant switch and instant rollbackDouble the compute during the switch
    CanarySend a small share of traffic to the new version firstHigh-traffic services where metrics can judge a releaseA few extra pods, plus tooling such as Argo Rollouts

    Plain Deployments do rolling and recreate. Blue-green and canary need either two Deployments and a manual switch, or a controller such as Argo Rollouts or Flagger that shifts traffic and checks metrics for you.

    In production: safe rollouts

    • Spread replicas. Four replicas on one node is one replica as far as a node failure is concerned. Use topologySpreadConstraints to spread them across nodes and zones.
    • Protect against drains. Cluster upgrades and autoscalers drain nodes. A PodDisruptionBudget stops them evicting too many of your pods at once:
    pdb.yaml
    apiVersion: policy/v1
    kind: PodDisruptionBudget
    metadata:
      name: web
    spec:
      minAvailable: 3
      selector:
        matchLabels:
          app: web
    Drains must wait until evicting a pod would still leave 3 running. Never set it equal to replicas, or drains can never proceed.
    • Restart without changing anything. kubectl rollout restart deployment/web rolls every pod, for example to pick up a changed Secret.
    • Pin images by tag or digest so a rollback means something. Rolling back to latest rolls back to nothing.

    Hands-on: roll out, break and roll back

    Live lab · no install

    Roll out, break and roll back

    Ship two versions, one of them broken, and watch the rolling update protect you.

    kind-learn
    1. Tasks0/7
    2. Apply the Deployment and wait for it

      web.yaml is in the Files tab: 4 replicas, maxSurge 1, maxUnavailable 0.

      kubectl apply -f web.yaml
      kubectl rollout status deployment/web
    3. Ship v1.27 and record why

      Watch the map: one new pod appears, becomes ready, then one old pod goes. Never fewer than 4 ready.

      kubectl set image deployment/web nginx=nginx:1.27
      kubectl annotate deployment/web kubernetes.io/change-cause="nginx 1.27"
    4. Find both ReplicaSets

      The old one is scaled to 0 but kept, which is what makes rollbacks instant.

      kubectl get rs -l app=web
    5. Ship a broken release

      This tag does not exist. Predict: how many users notice?

      kubectl set image deployment/web nginx=nginx:1.27-oops
      kubectl rollout status deployment/web --timeout=20s

      Stuck, but 4 old pods still serve. maxUnavailable: 0 did its job.

    6. Roll back
      kubectl rollout undo deployment/web
      kubectl rollout status deployment/web
    7. Read the history

      Rolling back created a new revision from an old template.

      kubectl rollout history deployment/web
    8. Protect it from drains with a PDB

      Then drain a node and see the budget make the drain wait its turn.

      kubectl create pdb web --selector=app=web --min-available=3
    9. Lab complete. Keep experimenting, or press Reset to start again.
    ↑↓ history · Tab complete · Ctrl+C stop
    Cluster map live
    • ready
    • starting / not ready
    • failing
    • terminating
    Prefer your own machine? The same steps on a local cluster

    Remove the web Deployment from chapter 1, save the manifest above as web.yaml and apply it.

    Terminal
    kubectl delete deployment web --ignore-not-found
    kubectl apply -f web.yaml
    kubectl rollout status deployment/web
    deployment.apps/web created
    Waiting for deployment "web" rollout to finish: 3 of 4 updated replicas are available...
    deployment "web" successfully rolled out

    Ship a new version and record why. In a second terminal, run kubectl get pods -l app=web -w to watch pods being replaced one at a time.

    Terminal
    kubectl set image deployment/web nginx=nginx:1.27
    kubectl annotate deployment/web kubernetes.io/change-cause="nginx 1.27"
    kubectl rollout status deployment/web
    kubectl get rs -l app=web
    NAME             DESIRED   CURRENT   READY   AGE
    web-5d8f7c6b9a   4         4         4       40s
    web-7f9c4d8b6e   0         0         0       5m
    set image
    Changes the pod template, so a new ReplicaSet is created.
    get rs
    The old ReplicaSet is scaled to 0 but kept for rollbacks.

    Now a bad release. The tag does not exist, so the new pods can never start:

    Terminal
    kubectl set image deployment/web nginx=nginx:1.27-oops
    kubectl rollout status deployment/web --timeout=45s
    kubectl get pods -l app=web
    Waiting for deployment "web" rollout to finish: 1 out of 4 new replicas have been updated...
    error: timed out waiting for the condition
    NAME                   READY   STATUS             RESTARTS   AGE
    web-5d8f7c6b9a-2hxkq   1/1     Running            0          3m
    web-5d8f7c6b9a-8sv4n   1/1     Running            0          3m
    web-5d8f7c6b9a-kq7zr   1/1     Running            0          3m
    web-5d8f7c6b9a-x9w2m   1/1     Running            0          3m
    web-6b7d9f8c5c-p4t6l   0/1     ImagePullBackOff   0          50s
    4 Running
    maxUnavailable 0 kept every old pod. Users saw nothing.
    --timeout
    Makes rollout status fail in CI instead of waiting forever.
    Terminal
    kubectl rollout undo deployment/web
    kubectl rollout history deployment/web
    

    Mini mission

    Ship a release that drains safely

    Add the PodDisruptionBudget above, then change the strategy to maxSurge: 0, maxUnavailable: 1 and roll out nginx:1.27 again. Watch how the order changes. Which setting would you use on a cluster with no spare capacity?

    Reveal one safe solution
    Terminal
    kubectl apply -f pdb.yaml
    kubectl patch deployment web -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":0,"maxUnavailable":1}}}}'
    kubectl set image deployment/web nginx=nginx:1.27
    kubectl get pods -l app=web -w
    

    Now an old pod is removed first and its replacement started after, so you briefly run 3. That needs no spare capacity, which is the right choice for a full cluster, at the price of less headroom during the rollout. The PDB does not affect rollouts; it only limits evictions such as kubectl drain.

    Check yourself

    Quiz

    0 of 5 answered

    1. 1. A Deployment has 4 replicas, maxSurge 1 and maxUnavailable 0. What is true during a rollout?
    2. 2. Your new version crashes on start. What does a rolling update do?
    3. 3. What does kubectl rollout undo restore?
    4. 4. Which strategy briefly doubles your compute bill?
    5. 5. What does a PodDisruptionBudget protect against?

    Further reading