Skip to content
Kubernetes day 2 · Chapter 5 of 20 Day 3: Staying reachable – from 21 errors to 0

Day 3: Staying reachable – from 21 errors to 0

Goal: Describe shop so that a drain does not cost a single request, and measure it · Duration: approx. 60 min · Prerequisite: Day 2

Briefing

Four building blocks, each closes one gap from yesterday:

Building block Protects against
Readiness probe Traffic to a Pod that does not respond yet
preStop hook Termination while the Pod is still known as a target
PodDisruptionBudget Eviction of all replicas at once
Topology spread constraints Replicas on the same node

The readiness probe fixes most of the damage. The other three are insurance for what rarely happens in the lab but regularly in production.

Drill 1: Readiness probe, preStop and spread

mkdir -p ~/day2/tag03 && cd ~/day2/tag03
cat > shop.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop, namespace: demo}
spec:
  replicas: 2
  selector: {matchLabels: {app: shop}}
  template:
    metadata: {labels: {app: shop}}
    spec:
      terminationGracePeriodSeconds: 30
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: kubernetes.io/hostname
        whenUnsatisfiable: DoNotSchedule
        matchLabelKeys: [pod-template-hash]
        labelSelector: {matchLabels: {app: shop}}
      containers:
      - name: nginx
        image: nginxinc/nginx-unprivileged:1.29-alpine
        command: [sh, -c, "sleep 10; exec nginx -g \"daemon off;\""]
        ports: [{containerPort: 8080}]
        readinessProbe:
          httpGet: {path: /, port: 8080}
          periodSeconds: 2
        lifecycle:
          preStop:
            sleep: {seconds: 5}
EOF
kubectl apply -f shop.yaml
sleep 3
kubectl -n demo get pods -l app=shop -o wide | cut -c1-80

Expected:

deployment.apps/shop configured
NAME                    READY   STATUS    RESTARTS   AGE     IP             NODE
shop-745bdbb55d-5v5hp   1/1     Running   0          3m39s   10.244.1.180   cp2
shop-745bdbb55d-thdqj   1/1     Running   0          4m19s   10.244.2.149   cp3
shop-76d76f687d-gx5lm   0/1     Running   0          4s      10.244.0.70    cp1

The new Pod shows 0/1 even though its container is running. The probe queries / every two seconds. Only when nginx responds does it become 1/1 and get traffic. The old Pod stays in place until then: the Deployment only replaces what is really ready.

kubectl -n demo rollout status deploy/shop
kubectl -n demo get pods -l app=shop -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName

Expected:

deployment "shop" successfully rolled out
POD                     NODE
shop-76d76f687d-gx5lm   cp1
shop-76d76f687d-qf64k   cp2

matchLabelKeys: [pod-template-hash] makes the scheduler count only Pods of the same revision when spreading. Without this line, the old Pods are counted during a rollout, and the new ones end up unevenly distributed (Day 7 shows this with web).

What does preStop: sleep do? During an eviction, two things happen at the same time: the Pod is removed from the endpoints, and the kubelet starts terminating it. It takes seconds until all kube-proxies and Cilium agents know the new endpoints. The five seconds of sleep keep nginx alive long enough for late requests to still be answered. sleep as a built-in action exists since v1.30, without a sleep binary in the image.

Save your progress? Sign up for free

Drill 2: The PodDisruptionBudget

cat > pdb.yaml <<'EOF'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: {name: shop, namespace: demo}
spec:
  minAvailable: 1
  selector: {matchLabels: {app: shop}}
EOF
kubectl apply -f pdb.yaml
kubectl -n demo get pdb shop

Expected:

poddisruptionbudget.policy/shop created
NAME   MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
shop   1               N/A               1                     1s

ALLOWED DISRUPTIONS 1: of two Pods, exactly one may be evicted at a time. The PDB only applies to voluntary disruptions via the Eviction API, that is, drain and autoscaler. It does not protect against a crashing node.

Save your progress? Sign up for free

Drill 3: The drain, measured again

A new measurement run, then the node with the shop Pod that does not run on cp1:

kubectl -n demo delete pod last
sed "s#http://web.demo#http://shop.demo#" ~/day2/tag00/last.yaml | kubectl apply -f -
kubectl -n demo wait --for=condition=Ready pod/last
kubectl drain cp2 --ignore-daemonsets --delete-emptydir-data

Expected (abridged):

node/cp2 cordoned
evicting pod demo/shop-76d76f687d-qf64k
...
pod/shop-76d76f687d-qf64k evicted
node/cp2 drained

The drain now takes eight seconds instead of two: preStop and the orderly shutdown take their time. Half a minute later:

kubectl -n demo logs last | wc -l
kubectl -n demo logs last | awk '$2 != 200' | wc -l
kubectl uncordon cp2

Expected:

139
0
node/cp2 uncordoned

0 out of 139. Yesterday 21 out of 196. Same application, same drain, just better described.

Save your progress? Sign up for free

Drill 4: A PDB that blocks the drain

A PDB that is too strict is the most common reason why an upgrade gets stuck.

kubectl -n demo patch pdb shop --type=merge -p '{"spec":{"minAvailable":2}}'
kubectl -n demo get pdb shop

Expected:

poddisruptionbudget.policy/shop patched
NAME   MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
shop   2               N/A               0                     80s

ALLOWED DISRUPTIONS 0: no shop Pod may go away anymore. A drain waits forever, so use a time limit:

kubectl drain cp3 --ignore-daemonsets --delete-emptydir-data --timeout=20s

Expected (lines wrapped):

evicting pod demo/shop-76d76f687d-8nsl7
error when evicting pods/"shop-76d76f687d-8nsl7" -n "demo" (will retry after 5s):
Cannot evict pod as it would violate the pod's disruption budget.
...
error: unable to drain node "cp3" due to error: error when evicting
pods/"shop-76d76f687d-8nsl7" -n "demo": global timeout reached: 20s, continuing command...
There are pending nodes to be drained:
 cp3

Without --timeout, kubectl drain hangs here forever and reports the same line every five seconds. Back to a sensible value:

kubectl uncordon cp3
kubectl -n demo patch pdb shop --type=merge -p '{"spec":{"minAvailable":1}}'

Rule of thumb: minAvailable always smaller than the number of replicas, or simply maxUnavailable: 1. A PDB with minAvailable equal to the replicas is not protection but a blockade.

Save your progress? Sign up for free

Drill 5: How much does preStop matter?

Test for yourself what happens when you keep only the readiness probe and leave out preStop. Comment out the three lines starting at lifecycle: in shop.yaml, apply it and measure three drains, each with a new last:

sed -i '/lifecycle:/,/seconds: 5/s/^/#/' shop.yaml
kubectl apply -f shop.yaml && kubectl -n demo rollout status deploy/shop

Expected (three runs in this course’s lab):

lauf 1 (cp2): 139 anfragen, 0 fehler
lauf 2 (cp3): 137 anfragen, 0 fehler
lauf 3 (cp2): 139 anfragen, 0 fehler

No errors even without preStop. At five requests per second, nginx shuts down cleanly enough, and Cilium distributes the new endpoints in milliseconds. So why preStop? Because the lab is the best case: little load, short requests, three nodes. With long requests, hundreds of nodes, kube-proxy in iptables mode or an application that aborts hard on SIGTERM, errors occur in exactly those seconds. preStop costs five seconds per drain and is the cheapest insurance against it. Restore it afterwards:

sed -i 's/^#//' shop.yaml
kubectl apply -f shop.yaml && kubectl -n demo rollout status deploy/shop

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Show for every PDB in the cluster how many disruptions are currently allowed. Target time: 1 min
  2. Find out which condition a Pod with 0/1 does not meet yet. Target time: 2 min
  3. Change the PDB of shop to maxUnavailable: 1. Target time: 2 min

Solution

kubectl get pdb -A
kubectl -n demo describe pod <pod> | sed -n '/Conditions/,/Volumes/p'

Expected (abridged, line truncated):

Conditions:
  Type                        Status
  PodReadyToStartContainers   True
  Initialized                 True
  Ready                       False
  ContainersReady             False
  PodScheduled                True
kubectl -n demo describe pod <pod> | grep -i readiness
    Readiness:      http-get http://:8080/ delay=0s timeout=1s period=2s #success=1 #failure=3
  Warning  Unhealthy  0s (x4 over 5s)  kubelet            spec.containers{nginx}: Readiness pro
kubectl -n demo patch pdb shop --type=json \
  -p '[{"op":"remove","path":"/spec/minAvailable"},
       {"op":"add","path":"/spec/maxUnavailable","value":1}]'

Save your progress? Sign up for free

Checkpoint

kubectl -n demo get pdb shop

Expected: ALLOWED DISRUPTIONS 1.

kubectl -n demo get pods -l app=shop -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName

Expected: two Pods on different nodes.

kubectl get nodes

Expected: all three Ready, none SchedulingDisabled.

Challenge

During the drain of cp3 in Drill 4, kubectl also reported:

pod/coredns-7d764666f9-hcppb evicted
pod/coredns-7d764666f9-5q99k evicted

Both CoreDNS Pods were running on cp3 and were evicted at the same time. For a few seconds, the whole cluster had no name resolution. Make sure this does not happen again.

Hint: kubeadm does not create a PDB for CoreDNS.

Solution

cat > coredns-pdb.yaml <<'EOF'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: {name: coredns, namespace: kube-system}
spec:
  maxUnavailable: 1
  selector: {matchLabels: {k8s-app: kube-dns}}
EOF
kubectl apply -f coredns-pdb.yaml
kubectl get pdb -A

Expected:

poddisruptionbudget.policy/coredns created
NAMESPACE     NAME      MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
demo          shop      1               N/A               1                     2m38s
kube-system   coredns   N/A             1                 1                     1s

The PDB survives the kubeadm upgrades from Day 6 on: kubeadm replaces the CoreDNS Deployment but does not touch any PDB.

Save your progress? Sign up for free

Cleanup

Nothing. From now on, shop with probe, preStop, spread and PDB is the application you measure all upgrades with. The PDB for CoreDNS stays as well.

Interview Note

  • What is the difference between readiness and liveness? Readiness decides about traffic, liveness about restarts. A missing readiness probe costs requests, a wrong liveness probe costs restarts.
  • Why a preStop hook when there is SIGTERM? Because the removal from the endpoints and the SIGTERM start at the same time. The hook bridges the time the endpoint update takes.
  • When does a PDB block? When ALLOWED DISRUPTIONS is 0, for example because minAvailable equals the number of replicas or Pods are not ready at the moment.

Enterprise Note

  • Many platform teams enforce PDBs and readiness probes via admission policy (Kyverno, OPA Gatekeeper) for every Deployment with two or more replicas.
  • Conversely, before upgrades they automatically check whether ALLOWED DISRUPTIONS 0 shows up anywhere, and clarify it with the teams before the first node is drained.
  • For several data centers or zones, topologyKey is set to topology.kubernetes.io/zone, in addition to the hostname.

Contents

More