Skip to content
LF Cert Trainer

Lesson 62 · Section 6: Cluster Maintenance

Lesson 62: OS upgrades: taking a node out of service safely

What happens to Pods when a node goes down, and how to plan for it: cordon, drain and uncordon, the five-minute eviction wait, which Pods a drain moves, skips or destroys, and how PodDisruptionBudgets can block it. · 16 min read · 4 min video

1/10OS upgrades
0:00 / 3:35

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why this matters

Nodes are ordinary machines. They need kernel patches, security updates, new container runtime packages, firmware and the occasional reboot. Each of those means the node stops running Pods for a while. Kubernetes is built to survive a node going away, but there is a large difference between a node that vanishes and a node that you empty first.

This lesson is about that difference, and about the three commands that control it: kubectl cordon, kubectl drain and kubectl uncordon. They are also the first and last steps of every cluster upgrade, which the next lessons cover.

What happens when a node just goes down

Suppose node01 is rebooted without any preparation. The control plane cannot tell a reboot from a crash; all it sees is that the kubelet has stopped reporting.

A node goes down without warningsilenttaintsNoExecute5 minreplaceno ownernode01 goes downkubelet is silentNode controllerwaits about 50 sTaint on node01unreachablePods tolerate itfor 300 secondsPods deletedafter 5 minutesReplicaSetnew Pod on node02Bare Podgone for good
A node goes down without warning. Nothing moves for about six minutes: first the control plane has to notice, then every Pod waits out its five-minute toleration. Only then are replacements created, and only for Pods that have an owner.

Parts:

  • node01 goes down (kubelet is silent)
  • Node controller (waits about 50 s)
  • Taint on node01 (unreachable)
  • Pods tolerate it (for 300 seconds)
  • Pods deleted (after 5 minutes)
  • ReplicaSet (new Pod on node02)
  • Bare Pod (gone for good)

Connections:

  • node01 goes down to Node controller: silent
  • Node controller to Taint on node01: taints
  • Taint on node01 to Pods tolerate it: NoExecute
  • Pods tolerate it to Pods deleted: 5 min
  • Pods deleted to ReplicaSet: replace
  • Pods deleted to Bare Pod: no owner
  1. The node controller waits. The kubelet renews a heartbeat every few seconds. When none arrives for the node monitor grace period (--node-monitor-grace-period on kube-controller-manager, 50 seconds by default), the node's Ready condition becomes Unknown and kubectl get nodes shows NotReady.

  2. The node is tainted. The controller adds node.kubernetes.io/unreachable with the effects NoSchedule and NoExecute. Nothing new is scheduled there.

  3. The Pods wait five minutes. Every Pod is created with two tolerations that you never wrote:

    tolerations:
      - key: node.kubernetes.io/not-ready
        operator: Exists
        effect: NoExecute
        tolerationSeconds: 300
      - key: node.kubernetes.io/unreachable
        operator: Exists
        effect: NoExecute
        tolerationSeconds: 300
    

    So each Pod stays bound to the silent node for 300 seconds. During that time Services stop sending traffic to it, because its endpoints are marked not ready, but no replacement is created.

  4. The Pods are evicted. After five minutes the Pods are marked for deletion. A ReplicaSet, Deployment or Job sees that it is short of Pods and creates new ones on healthy nodes. A Pod that nobody owns is not recreated by anyone.

What happens next depends on when the node returns:

The node comes backResult
Within about five minutesThe taint is removed. The kubelet restarts the same Pods in place; you see their restart count go up.
After the Pods were evictedThe kubelet finds its Pods deleted and cleans up. The node is Ready but empty, apart from DaemonSet Pods and static Pods. Bare Pods are lost.

Relying on this is a gamble. You do not know whether an upgrade takes two minutes or twenty. For up to six minutes the application runs short of replicas, the containers get no chance to shut down cleanly, and anything that existed only as a single bare Pod is gone. The alternative is to move the workloads before you touch the machine.

The three commands

CommandWhat it changesEffect on running Pods
kubectl cordon node01Sets spec.unschedulable: true on the nodeNone. They keep running.
kubectl drain node01Cordons the node, then evicts its PodsPods are terminated gracefully and their owners recreate them elsewhere.
kubectl uncordon node01Sets spec.unschedulable back to falseNone. Nothing moves back.

Cordon: no new Pods

Cordoning a node flips one field, spec.unschedulable. The node controller mirrors it as the taint node.kubernetes.io/unschedulable:NoSchedule, and the scheduler stops choosing the node. The status column shows it:

NAME           STATUS                     ROLES           AGE   VERSION
controlplane   Ready                      control-plane   41d   v1.34.1
node01         Ready,SchedulingDisabled   <none>          41d   v1.34.1
node02         Ready                      <none>          41d   v1.34.1

The node is still Ready and its Pods are untouched. Cordon alone is useful when you want to freeze a node as it is: while you investigate a problem on it, or just before a drain that you want to start later.

Two kinds of Pod still arrive on a cordoned node, because the scheduler's check does not stop them: DaemonSet Pods, which tolerate the unschedulable taint, and Pods that set spec.nodeName themselves, as you saw in the manual scheduling lesson.

Drain: cordon, then evict

What kubectl drain doesfirstthenevictedskipped--force onlykubectl drainnode011. CordonSchedulingDisabled2. Evict Podsone request eachDeployment Podsrecreated elsewhereDaemonSet Podsstay on the nodeBare Podsdeleted, not replaced
What kubectl drain does. Drain cordons the node first, then asks the API server to evict each Pod. What happens next depends on who owns the Pod.

Parts:

  • kubectl drain (node01)
  • 1. Cordon (SchedulingDisabled)
  • 2. Evict Pods (one request each)
  • Deployment Pods (recreated elsewhere)
  • DaemonSet Pods (stay on the node)
  • Bare Pods (deleted, not replaced)

Connections:

  • kubectl drain to 1. Cordon: first
  • kubectl drain to 2. Evict Pods: then
  • 2. Evict Pods to Deployment Pods: evicted
  • 2. Evict Pods to DaemonSet Pods: skipped
  • 2. Evict Pods to Bare Pods: --force only

kubectl drain does two things in order. It cordons the node, so that the Pods it is about to remove cannot be rescheduled onto the same node. Then it lists the Pods on the node and asks the API server to evict each one.

An evicted Pod goes through normal graceful termination: its containers receive SIGTERM and get the Pod's terminationGracePeriodSeconds to finish. Meanwhile the Pod's owner sees one Pod fewer and creates a replacement, which the scheduler places on another node. Strictly speaking nothing is "moved": the old Pod dies and a new Pod with a new name and IP address is born elsewhere.

Drain treats Pods differently depending on who owns them:

Pod on the nodeWhat drain doesFlag you need
Owned by a ReplicaSet, Deployment, StatefulSet or JobEvicts it; the owner creates a replacement on another nodeNone
Owned by a DaemonSetLeaves it running. Refuses to start unless you acknowledge this--ignore-daemonsets
Static Pod (mirror Pod)Leaves it alone; it cannot be deleted through the APINone
Bare Pod with no controllerRefuses to start. With the flag, deletes it and nobody recreates it--force
Any Pod using an emptyDir volumeRefuses to start. With the flag, evicts it and the volume's data is deleted--delete-emptydir-data

The refusals are deliberate. Each one is a case where draining loses something, so kubectl makes you say that you understand before it removes any Pod. A drain that hits one of these stops before the first eviction.

Why are DaemonSet Pods skipped rather than evicted? Their controller wants one Pod on every node and ignores the unschedulable taint, so an evicted DaemonSet Pod would be recreated on the same node a second later. They are node services such as kube-proxy and the network plugin, and they belong on the node for as long as it is in the cluster.

Drain waits until every evicted Pod has finished terminating, then prints node/node01 drained. Only then is it safe to work on the machine.

Uncordon: back in service

A drained node stays cordoned. The reboot does not change that, because spec.unschedulable is stored in the API, not on the machine. When the node is Ready again:

kubectl uncordon node01

Uncordoning makes the node schedulable and nothing more. Pods do not move back. The replacements are running happily on other nodes and Kubernetes never moves a running Pod to balance the cluster. The node fills up again only as new Pods are created: by scaling, by rollouts, or by draining the next node.

PodDisruptionBudgets: when a drain has to wait

An eviction can be refusedevictchecks200 OKbudget at limitkubectl drainwants web-1 goneAPI servereviction requestPDB webminAvailable: 2Allowed3 healthy beforeRefused (429)retry after 5 s
An eviction can be refused. Drain does not delete Pods directly. It asks for an eviction, and the API server says no while a PodDisruptionBudget would be broken. Drain then waits and asks again.

Parts:

  • kubectl drain (wants web-1 gone)
  • API server (eviction request)
  • PDB web (minAvailable: 2)
  • Allowed (3 healthy before)
  • Refused (429) (retry after 5 s)

Connections:

  • kubectl drain to API server: evict
  • API server and PDB web: checks
  • API server to Allowed: 200 OK
  • API server to Refused (429): budget at limit

Drain uses the Eviction API instead of deleting Pods because an eviction can be refused. A PodDisruptionBudget (PDB) tells the API server how many Pods of an application must stay available during voluntary disruptions such as a drain:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web
spec:
  minAvailable: 2            # or maxUnavailable: 1
  selector:
    matchLabels:
      app: web

For each eviction request the API server answers:

  • 200 OK when the eviction keeps the budget. The Pod is deleted.
  • 429 Too Many Requests when it would break the budget. Drain prints the refusal, waits five seconds and tries again.

With three healthy web replicas and minAvailable: 2, one Pod can be evicted. The next eviction is refused until the replacement is Ready on another node. That is the budget doing its job: the drain is slower, and the application never drops below two replicas.

evicting pod default/web-6d5f7c9b8-4kq2p
error when evicting pods/"web-6d5f7c9b8-4kq2p" -n "default" (will retry after 5s):
Cannot evict pod as it would violate the pod's disruption budget.

A budget that can never be met blocks the drain for ever. The usual causes are minAvailable equal to the replica count (or maxUnavailable: 0), a single-replica application with minAvailable: 1, or replacements that cannot become Ready because the other nodes are full or cordoned. kubectl get pdb shows the problem in one column:

NAME   MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
web    2               N/A               0                     12d

ALLOWED DISRUPTIONS: 0 means no eviction will be accepted right now. Fix the cause: scale the application up, free capacity, or relax the budget. A PDB only guards voluntary disruptions. It does nothing when a node crashes.

Under the hood · Voluntary and involuntary disruptions

Kubernetes separates two ways a Pod can disappear:

  • Involuntary: hardware failure, kernel panic, the machine is deleted, the node runs out of memory and the kubelet evicts Pods. Nobody asked for it and no budget can prevent it.
  • Voluntary: an administrator drains a node, the cluster autoscaler removes one, somebody deletes a Pod or updates a Deployment. These are choices, and the ones that go through the Eviction API respect PDBs.

Deleting a Pod directly (kubectl delete pod) is voluntary but does not check PDBs. Neither does kubectl drain --disable-eviction, which switches drain from evicting to deleting. Treat that flag as a last resort: it empties the node whatever the budgets say.

Under the hood · Stateful Pods on a dead node, and node shutdown features

When a node dies and never returns, evicted Pods stay in Terminating, because no kubelet is left to confirm that the containers have stopped. A Deployment does not mind and creates replacements anyway. A StatefulSet waits: it will not create db-0 again while the old db-0 might still be running and writing to its volume. To recover, you remove the node object (kubectl delete node node01), force-delete the Pod, or mark the node with the taint node.kubernetes.io/out-of-service:NoExecute, which tells the control plane that the machine is truly off so Pods can be deleted and volumes detached at once.

The kubelet also has a graceful node shutdown feature. With shutdownGracePeriod set in the kubelet configuration, the kubelet delays an operating system shutdown and terminates its Pods in order first. It is off by default (the value is 0s), it does not check PodDisruptionBudgets, and it is no replacement for a drain.

Using it

  1. kubectl drain
  2. Upgrade and reboot
  3. Node is Ready
  4. kubectl uncordon
Maintenance on one node

Example · Patch and reboot a worker node

Look at what runs on the node before you empty it:

kubectl get pods -A -o wide --field-selector spec.nodeName=node01

Drain it. --ignore-daemonsets is needed on practically every node:

kubectl drain node01 --ignore-daemonsets
node/node01 cordoned
Warning: ignoring DaemonSet-managed Pods: kube-system/kube-flannel-ds-x2x9k, kube-system/kube-proxy-7hx4q
evicting pod default/web-6d5f7c9b8-4kq2p
evicting pod default/web-6d5f7c9b8-9tm5c
pod/web-6d5f7c9b8-4kq2p evicted
pod/web-6d5f7c9b8-9tm5c evicted
node/node01 drained

Now do the operating system work on the machine itself:

ssh node01
sudo apt-get update && sudo apt-get upgrade -y
sudo reboot

Back on the control plane, wait for the node and put it back in service:

kubectl get nodes -w                        # node01: NotReady,SchedulingDisabled, then Ready,SchedulingDisabled
kubectl uncordon node01
kubectl get nodes                           # node01: Ready

Example · A drain that refuses to start

kubectl drain node01 --ignore-daemonsets
node/node01 cordoned
error: unable to drain node "node01" due to error: [cannot delete Pods that declare no controller
(use --force to override): default/hr-app, cannot delete Pods with local storage
(use --delete-emptydir-data to override): default/cache-5c9d8f7b6-x8kzp], continuing command...
There are pending nodes to be drained:
 node01

Read it before you reach for more flags. It names two Pods and two different problems:

  • default/hr-app is a bare Pod. With --force it is deleted and not recreated. If the application matters, save it first (kubectl get pod hr-app -o yaml > hr-app.yaml) or, better, run it under a Deployment.
  • default/cache-... uses an emptyDir volume. Its replacement starts with an empty volume. For a cache that is fine.

No Pod has been evicted yet, but the node is cordoned. If you accept both losses:

kubectl drain node01 --ignore-daemonsets --delete-emptydir-data --force

If you do not, and you decide to leave the node alone, undo the cordon with kubectl uncordon node01.

Example · A drain that hangs on a PodDisruptionBudget

The drain keeps printing the same line every five seconds:

error when evicting pods/"web-6d5f7c9b8-4kq2p" -n "default" (will retry after 5s):
Cannot evict pod as it would violate the pod's disruption budget.

Find the budget and see how much room it leaves:

kubectl get pdb -A
kubectl describe pdb web
kubectl get deploy web                      # how many replicas are there?

Suppose web has 2 replicas and the budget says minAvailable: 2: no eviction can ever be allowed. Give the budget room by adding a replica, then let the drain continue (it is still retrying in the other terminal):

kubectl scale deployment web --replicas=3

As soon as the third replica is Ready on another node, the next retry succeeds. To stop waiting after a set time instead of for ever, start the drain with --timeout=120s.

Example · Stop new Pods without removing the old ones

A node shows disk errors and you want to look at it before deciding anything. Freeze it:

kubectl cordon node01
kubectl get nodes                           # Ready,SchedulingDisabled
kubectl describe node node01 | grep -i -A2 taints
Taints:             node.kubernetes.io/unschedulable:NoSchedule
Unschedulable:      true

Existing Pods keep serving. New Pods go elsewhere. When you are done, either kubectl uncordon node01 or go on to kubectl drain node01 --ignore-daemonsets.

Tricks

Common mistakes

  • Forgetting to uncordon. The node is Ready, the upgrade is done, and no Pod ever lands on it. In the exam this costs the whole task: verify with kubectl get nodes that SchedulingDisabled is gone.
  • Adding --force by reflex. It deletes bare Pods permanently. If a task says a Pod must not be lost, the right answer may be to cordon the node and leave that Pod where it is, not to drain.
  • Expecting Pods to return after uncordon. They do not. Nothing rebalances a cluster automatically.
  • Draining several nodes at once without capacity. The evicted Pods need somewhere to go. If the remaining nodes are full, replacements stay Pending and PDBs block the drain. Do one node at a time.
  • Confusing cordon with drain. Cordon alone removes nothing. Rebooting a cordoned node still kills its Pods without warning.
  • Reading a PDB refusal as an error to force through. The retry message means the budget is protecting the application. Look at kubectl get pdb before you think about --disable-eviction.
  • Draining the only control plane node and expecting an outage. The API server, etcd, scheduler and controller manager are static Pods, which drain does not touch. They stop when you reboot the machine, not when you drain it.

Recap

  • A node that goes down unannounced keeps its Pods for about five minutes (tolerationSeconds: 300). Then they are evicted and only Pods with a controller are recreated.
  • Planned maintenance is three steps: kubectl drain, do the work, kubectl uncordon.
  • Drain cordons the node and evicts its Pods. DaemonSet Pods need --ignore-daemonsets, emptyDir Pods need --delete-emptydir-data, and bare Pods need --force and are lost.
  • Evictions respect PodDisruptionBudgets: a drain waits, and retries every five seconds, while a budget would be broken.
  • Cordon only stops new Pods. Uncordon only allows them again. Pods never move back on their own.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

3 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Put a node back into service that was left cordoned, then empty another node for maintenance: past a DaemonSet, a pod with local data and a pod nobody manages.

    Build · Level 2 · standard · target 15 min

  • Section capstone on a kubeadm cluster. Empty a node for repair without hurting a protected app, save an etcd snapshot, unpack an older snapshot next to the live data, and upgrade the control plane node to the next Kubernetes version.

    Build · Level 3 · challenge · target 45 min

  • A drain hangs on a PodDisruptionBudget that allows no disruption at all. Get the node empty without dropping the protection and without the service going down.

    Fix · Level 3 · challenge · target 18 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.