Kubernetes Hour 2: Workloads and Scheduling

From “Pod runs” to “production-ready”: resources, probes, configuration, rollouts, stateful workloads, batch jobs, and scheduling constraints
Kubernetes v1.37.1kubectl 1.37kind v0.33.0metrics-server v0.9.1Verified against official docs · 2026-11
Overall learning goals
  • Set sensible requests/limits for every container. Explain the difference between CPU throttling (cpu.max) and memory OOMKill (memory.max), the QoS classes and eviction order, and use the v1.35 GA In-place Pod resize to adjust resources on a running Pod.
  • Design liveness / readiness / startup probes correctly. Understand the Pod termination sequence (EndpointSlice updates run in parallel with SIGTERM), and use preStop.sleep to get zero-downtime rolling updates.
  • Externalize config with ConfigMap / Secret. Know how the env, volume, and subPath methods differ when config changes, and trigger rollouts reliably.
  • Master the maxSurge/maxUnavailable calculation, blue-green, canary, and PodDisruptionBudget. Know how they relate to kubectl drain.
  • Choose between StatefulSet / DaemonSet / Job / CronJob based on the scenario. Deploy postgres:17 and add a scheduled backup for it.
  • Read the scheduler's Filter / Score process. Use nodeAffinity, podAntiAffinity, taints/tolerations, topologySpreadConstraints, and PriorityClass with confidence. Quickly find the cause of a Pending Pod from 0/3 nodes are available events.

1-hour timetable

#TimeModuleCore contentAnimation / interactiveLab (kind cluster lab)
0Before classWarm-upCheck the cluster and shop app, rebuild commands, install metrics-server10-item production-readiness self-checkkubectl top works
100–07Resources: requests/limits and QoSScheduling basis, cgroup v2 enforcement, QoS and eviction, allocatable, In-place resize (1.35 GA), Pod-level resources (Beta), MemoryQoS (1.37 Beta)CPU throttling vs memory OOMKilled simulatorReproduce OOMKilled (137), observe throttling, resize in place
207–15Probes and graceful terminationThree probe types: semantics and misuse; four probe methods; termination flow; preStop sleep (1.34 GA)Termination timeline: endpoint removal races SIGTERMAdd probes to api + zero-downtime rolling update
315–22ConfigMap and SecretWays to create them, env/envFrom/volume/subPath, hot-update delay, immutable, imagePullSecrets, rollouts triggered by config changesWhether env and volume changes take effect after an updateExternalized config + checksum rollout
422–30Advanced rollout strategiesmaxSurge/maxUnavailable calculation, minReadySeconds, progressDeadlineSeconds, pause/resume, blue-green, canary, PDBRolling-update calculator + blue-green switch + canary ratioBlue-green switch + PDB and drain
530–37StatefulSetStable identity, headless Service, volumeClaimTemplates, OrderedReady/Parallel, partition, Recreate (1.37 Alpha), PVC retention policyOrdered creation and batched updates with partitionDeploy a postgres:17 StatefulSet
637–42DaemonSetOne per node, system DaemonSets, tolerating control-plane taints, update strategyHow DaemonSets react when nodes join or taints changeDeploy a node agent
742–49Job and CronJobcompletions/parallelism/backoffLimit, Indexed, podFailurePolicy, successPolicy, backoffLimitPerIndex, timeZone, concurrencyPolicyJob parallelism and retry simulatorpostgres backup CronJob
849–60Scheduling: affinity · taints · topology spreadScheduling framework, nodeAffinity, pod(Anti)Affinity, taints/tolerations, topologySpread, PriorityClass preemption, cordon/drain, Pending diagnosisScheduler Filter + Score simulator + troubleshooting treeCross-node distribution + drain drill
—After classCheat sheet · Capstone labUpgrade shop to “production-ready” and verify a zero-downtime drainFinal quiz (12 questions)Capstone lab

Knowledge coverage matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Set container resources and explain QoS✓······✓kubectl top, describe nodeOOMKilled / resize
Diagnose OOMKilled / CPU throttling✓·······get pod -o jsonpath, cpu.statM1 lab
Design probes and implement graceful termination·✓·✓····describe pod, eventsZero-downtime rolling update
Externalize config and secrets, hot-reload config··✓···✓·create configmap/secretChecksum rollout
Safe releases: rolling, blue-green, canary·✓✓✓····rollout status/pause/undoBlue-green switch
Voluntary disruption protection (PDB / drain)···✓·✓·✓drain, get pdbDrain drill
Run stateful applications··✓·✓·✓·get sts,pvcpostgres:17
Node-level agents·····✓·✓get ds -Anode-agent
Batch jobs and scheduled tasks······✓·create job --from=cronjob/pg_dump backup
Scheduling constraints and Pending troubleshooting✓···✓✓·✓taint, cordon, eventsTopology spread

Out of scope for this hour (and where to learn it)

TopicWhy it is not covered in this hourWhere to learn it
Service deep dive, Gateway API weighted routing, NetworkPolicyBelongs to the networking topicHour 3 (the traffic-weighted canary version is implemented there)
PV/PVC/StorageClass, CSI, backup and restore (Velero)This hour only uses kind's default StorageClass to get postgres runningHour 4
Secret encryption at rest (KMS v2), External Secrets, RBAC, Pod SecurityBelongs to the security topicHour 5
HPA/VPA/KEDA autoscaling, Argo Rollouts, Helm/KustomizeBelongs to the operations and delivery topicScaling is covered in hour 6. Helm/Kustomize gets an overview in hour 6; for depth, see the Helm and GitOps and Argo CD courses
DRA / GPU scheduling, Gang scheduling (1.37 Beta), custom scheduler pluginsAimed at AI and batch platforms, and more than one hour's worth of materialOfficial Scheduling docs

How to use this course

10 tabs per module
Principles · diagrams · animation · commands · lab · production cases · troubleshooting · quiz · voice · video. Start with “Principles” and “Animation,” then do the “Lab.”
Learning progress
A module counts toward your progress when you score ≥ 70% on its quiz or click “Mark this module complete.” Progress is saved in this browser. If local storage is blocked, progress is cleared on refresh.
English voice
The “Voice” tab reads the narration script aloud using the browser's built-in Web Speech API (en-US). If no English voice pack is installed, the narration script can still be read or passed to a TTS tool.
Version note This hour uses Kubernetes v1.37 as its baseline. The default node image for kind v0.33.0 is kindest/node:v1.37.0. Feature stages mentioned in this hour were all checked against the official feature gates page in 2026-11: In-place Pod resize is GA in v1.35; Pod-level resources (PodLevelResources) are Beta from v1.34 and enabled by default; preStop.sleep is GA in v1.34; the StatefulSet maxUnavailable field is Beta and was re-enabled by default in v1.37; the StatefulSet Recreate strategy is Alpha in v1.37; MemoryQoS is Beta in v1.37. If you use a 1.35 or 1.36 cluster, follow the docs for that version.

Module 0 · Warm-up (complete before class)

Confirm that the cluster and shop app from hour 1 still work, install metrics-server, then score shop's “production readiness.”
Before class ≈ 8 minkind v0.33.0 · v1.37.0
Prerequisites
  • You have completed hour 1: a kind cluster lab (1 control-plane + 2 worker), the namespace shop, which contains the api Deployment (podinfo 6.17.0) and a ClusterIP Service with the same name.
  • Lab machine: Azure VM Ubuntu 24.04 (Standard_D4s_v5) or local Docker Desktop. kubectl 1.37 and kind v0.33.0 must already be installed.
  • All commands in this hour run in the shop namespace by default. Set the default namespace first (see below).

Step 1: Check the cluster and shop app

kubectl config use-context kind-lab
kubectl config set-context --current --namespace=shop
kubectl get nodes -o wide
kubectl get deploy,rs,pod,svc -n shop -o wide
NAME                STATUS   ROLES           AGE   VERSION
lab-control-plane   Ready    control-plane   2d    v1.37.0
lab-worker          Ready    <none>          2d    v1.37.0
lab-worker2         Ready    <none>          2d    v1.37.0

NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/api   3/3     3            3           2d
...
NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
service/api   ClusterIP   10.96.143.20   <none>        9898/TCP   2d

Step 2 (only if the cluster was deleted): rebuild the lab cluster and shop

If you ran kind delete cluster --name lab at the end of the previous hour, rebuild it in 2–3 minutes with the commands below. All YAML later in this hour uses the label app: api from here. If you used a different label in hour 1, rebuild using this checklist first so the selectors match.

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: lab
nodes:
- role: control-plane
  image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
- role: worker
  image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
- role: worker
  image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
kind create cluster --config kind-lab.yaml
kubectl create namespace shop
kubectl config set-context --current --namespace=shop
kubectl create deployment api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=3 --port=9898 -n shop
kubectl expose deployment api --port=9898 --target-port=9898 -n shop
kubectl rollout status deploy/api -n shop
Note kubectl create deployment api automatically generates the label app: api, and the container name is podinfo (taken from the image name). The patch commands in this hour all use the container name podinfo. To confirm it, run kubectl get deploy api -o jsonpath='{.spec.template.spec.containers[*].name}'.

Step 3: Install metrics-server (kubectl top depends on it)

metrics-server collects CPU and memory from the /metrics/resource endpoint of each node's kubelet, and serves them through the aggregated API metrics.k8s.io for kubectl top and HPA. The latest version verified in 2026-11 is v0.9.1 (2026-10-29). The kubelet on kind nodes uses a self-signed certificate, so the lab needs --kubelet-insecure-tls.

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml

# Lab only: skip kubelet certificate verification
kubectl -n kube-system patch deployment metrics-server --type=json \
  -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
kubectl -n kube-system rollout status deploy/metrics-server
kubectl get apiservices | grep metrics
kubectl top nodes
NAME                  CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
lab-control-plane     180m         4%       780Mi           4%
lab-worker            45m          1%       310Mi           1%
lab-worker2           41m          1%       295Mi           1%
Security note --kubelet-insecure-tls turns off verification of the kubelet serving certificate. Use it only in lab clusters such as kind. AKS, EKS, and GKE already include metrics-server. In production, use kubelet serving certificates signed by the cluster CA (serverTLSBootstrap: true and approve the CSRs). If kubectl top reports Metrics API not available, wait one minute, then check kubectl -n kube-system logs deploy/metrics-server.
Version note In v1.37 the metrics.k8s.io API has reached GA, and v1beta1 still works during the transition. For the API versions metrics-server actually serves, check its release notes. You can list them with kubectl get apiservices | grep metrics.

Warm-up: answer from memory (30 seconds)

How are Deployment, ReplicaSet, and Pod related?

A Deployment manages versions through ReplicaSets (each change to the Pod template creates a new RS). A ReplicaSet keeps the number of Pod replicas for one version. A Pod is the smallest unit that actually runs.

How does a Service find its Pods?

Through a label selector. The EndpointSlice controller writes the IPs of matching Pods that are Ready into EndpointSlices, and kube-proxy (nftables/iptables) builds forwarding rules from them. The word Ready sets up module 2 of this hour.

Production-readiness self-check (10 items)

Check the items your shop app already meets today. Results are saved in this browser. Come back and check again after you finish this hour and the capstone lab.

Environment checklist

Module 1 · Resource requests/limits and QoS

00:00 – 07:00 · requests decide “where the Pod goes,” and limits decide “how much it can use at most.” What happens when a container goes over is very different for CPU and memory.
7 minIn-place resize v1.35 GAPodLevelResources Beta · MemoryQoS 1.37 Beta★★★★★
Learning goals
  • Explain who uses requests and limits. requests are used by kube-scheduler (and by the cgroup cpu.weight). limits are written by kubelet/containerd into the cgroup v2 cpu.max and memory.max.
  • Identify a Pod's QoS class (Guaranteed / Burstable / BestEffort), and explain the eviction and OOM priority under node memory pressure.
  • Use kubectl top and the Allocated resources section of kubectl describe node for capacity analysis. Use --subresource resize to resize resources in place.
Prerequisites: --memory/--cpus from the Docker course, and cgroup v2 files. Importance: ★★★★★ (a top-3 source of production incidents)

What: what requests and limits are

In resources, each container can declare requests (guaranteed or reserved amount) and limits (maximum).Common resources are cpu, memory, and ephemeral-storage, plus extended resources such as nvidia.com/gpu.

  • CPU units: 1 = 1 vCPU/core; 500m = 0.5 core (m = millicore). CPU is a compressible resource: going over only slows things down.
  • Memory units: Mi/Gi are powers of 2 (1Mi = 1048576 bytes); M/G are powers of 10. Watch out: 400m memory means 0.4 bytes, a common typo. Memory is an incompressible resource: going over gets the container killed.

Why: why you must set them

Without requests, the scheduler assumes the Pod uses no resources and may pack too many Pods onto one node. Without limits, one container with a memory leak can push the whole node into memory pressure and make the kubelet evict other innocent Pods. requests are also the baseline HPA uses to calculate utilization, and cluster autoscaling uses them to decide that a Pod “doesn't fit.”

How: who uses these numbers

FieldConsumerMechanism (cgroup v2)What happens when exceeded
requests.cpukube-scheduler (NodeResourcesFit filter + scoring); kubeletConverted to cpu.weight (CPU is shared proportionally when busy)Can use idle CPU beyond the request
limits.cpukubelet → containerd → runccpu.max = "quota period", e.g. 500m → 50000 100000Throttling: once the quota for this period is used up, threads are paused until the next period, and nr_throttled in cpu.stat increases
requests.memorykube-scheduler; kubelet eviction ordering; MemoryQoSWhen MemoryQoS (1.37 Beta) is enabled, it provides memory.min/memory.low protectionCan go over, but is evicted first under node memory pressure
limits.memorykubelet → runcmemory.max; MemoryQoS also sets memory.high based on the throttling factorKernel OOM killer kills the process: container reason: OOMKilled, exit code 137

Node allocatable: the scheduler does not compare the node's total capacity. It compares allocatable = capacity − kube-reserved − system-reserved − eviction threshold. The scheduler only checks whether the sum of requests exceeds allocatable. It does not look at actual usage.

QoS classes (computed automatically by Kubernetes and written to status.qosClass)

QoS classConditionoom_score_adjUnder node memory pressure
GuaranteedEvery container in the Pod sets CPU and memory requests and limits, and requests = limits-997Evicted last
BurstableDoes not meet Guaranteed, but at least one container sets a CPU or memory request or limit2–999 (based on the memory request's share of the node)Containers using more than their requests go first
BestEffortNo container has any requests or limits1000Evicted first

The actual order for kubelet node-pressure eviction is: ① whether usage exceeds requests; ② Pod Priority; ③ how far usage exceeds requests. QoS is closely related to this order, but it is not the only factor. If you set limits without requests, requests automatically equal limits.

Feature overview (verified stages)

  • In-place Pod resize (InPlacePodVerticalScaling, v1.27 Alpha → v1.33 Beta → v1.35 GA): change the CPU and memory of running containers through the resize subresource, without recreating the Pod. A container's resizePolicy decides whether that container has to restart (NotRequired / RestartContainer). New in v1.37 as Alpha: when node resources are short, the scheduler can preempt lower-priority Pods to make room for a resize (InPlacePodVerticalScalingSchedulerPreemption).
  • Pod-level resources (PodLevelResources, v1.32 Alpha → v1.34 Beta, enabled by default): set one total budget for the whole Pod in spec.resources. Containers can share idle resources with each other.
  • MemoryQoS (v1.22 Alpha → v1.37 Beta, enabled by default, cgroup v2 only): uses memory.min/memory.low/memory.high so that requests protect memory from reclaim. memory.high throttles reclaim before the limit is reached, which reduces direct OOMs. kubelet settings: memoryReservationPolicy, memoryThrottlingFactor.
  • Since v1.35, the kubelet's failCgroupV1 defaults to true, so the kubelet does not start by default on cgroup v1 nodes. Every mechanism in this module assumes cgroup v2.

When: how to set them

  • Memory: set requests = limits (or limits slightly higher), based on the P99 from load tests plus headroom. The cost of exceeding memory is an OOM, which is not worth gambling on.
  • CPU: always set requests. Limits are debated: latency-sensitive services often do not set a CPU limit to avoid throttling, and rely on cpu.weight from requests for fairness. Multi-tenant clusters usually enforce limits (using LimitRange/ResourceQuota, hour 5).
  • Use Guaranteed when you need exclusive CPUs (static CPU manager) or the highest eviction protection.

Comparison with similar technologies

KubernetesDocker (single host)Azure Container Apps / ECS
Reservationrequests (affects scheduling)None (--cpu-shares is only a weight)Billed by vCPU/memory size; the platform schedules it
Limitlimits → cpu.max/memory.max--cpus/--memory, same mechanismSize is the limit
In-place resizeresize subresource (1.35 GA)docker updateCreates a new revision
Common misconceptions ① “Bigger limits are always safer.” Limits far above requests overcommit the node, and under memory pressure many Pods get evicted. ② “A container that reaches its CPU limit gets killed.” It does not. It is throttled, which shows up as higher latency, while kubectl top may show a low average CPU (throttling happens within each 100 ms period). ③ “If kubectl top shows memory above the limit, the container will be killed.” OOM decisions are based on cgroup memory (including how much page cache can be reclaimed). What matters is whether memory.max is breached.

Architecture diagram: how resource numbers travel from YAML to the kernel

Pod spec requests: cpu 250m, mem 128Mi limits: cpu 500m, mem 256Mi → QoS: Burstable kube-scheduler Filter: NodeResourcesFit Σrequests + 250m ≤ allocatable ? Looks only at requests, not actual usage bind kubelet Computes QoS and the Pod cgroup CRI: CreateContainer (LinuxContainerResources) containerd+ runcWrites cgroup files /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/…/cri-containerd-<id>.scope cpu.weight← requests.cpuShares CPU proportionally when busy cpu.max"50000 100000"Over limit → throttling memory.max268435456Over limit → OOM kill Node allocatable capacity − kube-reserved − system-reserved − eviction-hard (memory.available) = the ceiling the scheduler can allocate
Figure 1-1: requests drive scheduling and CPU weight; limits are written to cgroup v2 by runc and enforced by the kernel

Flow chart: what happens after a limit is exceeded

CPU usage > cpu.max CFS bandwidth controlThis 100 ms period's quota is used up Threads are paused until the next periodnr_throttled++ throttled_usec+= Container keeps runningSymptom: P99 latency rises Memory → memory.max Kernel reclaims page cache first(MemoryQoS: memory.high throttling) cgroup OOM killerSIGKILL → exit 137 kubelet restarts the containerreason: OOMKilled → back-off Note: kubelet eviction (Evicted) caused by node-level memory pressure is a different thing from container-level OOMKilled
Figure 1-2: CPU is compressible (throttled); memory is incompressible (process is killed)

Interactive simulator: CPU throttling vs memory OOMKilled

Drag the “Application load” slider, then click “Run 10 periods.” The left side simulates CFS bandwidth quota usage in each 100 ms period. The right side simulates memory growth until it reaches memory.max. The terminal below shows the real file contents and events you would see on the node.

CPU: limits.cpu = 500m (cpu.max = 50000 100000)
CPU the app needs: 900m
nr_periods 0 · nr_throttled 0
Memory: limits.memory = 256Mi (memory.max = 268435456)
Memory growth per period: 35Mi
memory.max 256Mi
64Mi
restartCount 0
Ready. The default load is 900m > limit 500m: CPU is throttled, but the container does not die. Memory grows 35Mi per period, which triggers an OOM around period 6.
$ kubectl apply -f stress-pod.yaml

Core commands and flags

CommandPurposeKey flags / notes
kubectl set resourcesChange resources in the Deployment template (triggers a rollout)-c container --requests=cpu=100m,memory=128Mi --limits=memory=256Mi
kubectl top pod/nodeView live usage (metrics-server)--containers, --sort-by=memory, -A
kubectl describe nodeCapacity / Allocatable / Allocated resourcesCheck requests as a percentage of allocatable
kubectl get pod -o jsonpathQoS, termination reason, exit code{.status.qosClass}, {.status.containerStatuses[0].lastState}
kubectl patch pod --subresource resizeResize a running Pod in place (1.35 GA)Requires kubectl ≥ 1.32; only cpu/memory can be changed
kubectl explain pod.spec.containers.resizePolicyView the resize restart policy fieldsresourceName + restartPolicy
# Set resources on api (container name podinfo)
kubectl set resources deploy/api -c podinfo \
  --requests=cpu=100m,memory=64Mi --limits=cpu=500m,memory=128Mi
kubectl rollout status deploy/api
kubectl get pod -l app=api -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
deployment.apps/api resource requirements updated
deployment "api" successfully rolled out
NAME                   QOS
api-6d9f7c8b5d-4kx2p   Burstable
api-6d9f7c8b5d-9tqzr   Burstable
api-6d9f7c8b5d-wm8hd   Burstable
kubectl describe node lab-worker | sed -n '/Allocatable:/,/Events:/p'
Allocatable:
  cpu:                4
  ephemeral-storage:  …
  memory:             16310Mi
  pods:               110
…
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                300m (7%)   1500m (37%)
  memory             242Mi (1%)  434Mi (2%)

How to verify: when the Requests percentage gets close to 100%, new Pods stay Pending, even if kubectl top shows the node is mostly idle. Common mistake: each kind node can see all of the host's CPU and memory, so allocatable is very large. This is a kind characteristic; on AKS, allocatable is noticeably smaller than the VM size. Production use: for capacity planning, watch Requests%. For cost optimization, compare actual usage from top with the gap to requests.

In-place resize

kubectl patch pod POD --subresource resize --type merge -p \
  '{"spec":{"containers":[{"name":"podinfo","resources":{"requests":{"cpu":"200m"},"limits":{"cpu":"800m"}}}]}}'
kubectl get pod POD -o jsonpath='{.spec.containers[0].resources}{"\n"}{.status.containerStatuses[0].resources}{"\n"}{.status.conditions[?(@.type=="PodResizePending")]}{"\n"}'

spec.containers[].resources is the desired value, and status.containerStatuses[].resources is the value actually in effect. If the request cannot be met right away, the Pod shows a PodResizePending condition (reason Deferred means it may be satisfied later, Infeasible means the node does not have enough total capacity). While it is being applied, the condition is PodResizeInProgress. Resizing a Pod managed by a Deployment affects only that Pod. The template stays the same, so the next rollout restores the values in the template.

Lab 1: Reproduce OOMKilled, observe CPU throttling, resize in place (about 6 min)

Reproduce OOMKilled (the image and flags come from the official “Assign Memory Resources” example):
apiVersion: v1
kind: Pod
metadata:
  name: oom-demo
  namespace: shop
spec:
  containers:
  - name: stress
    image: polinux/stress
    resources:
      requests: { memory: "50Mi" }
      limits:   { memory: "100Mi" }
    command: ["stress"]
    args: ["--vm", "1", "--vm-bytes", "250M", "--vm-hang", "1"]
kubectl apply -f oom-demo.yaml
kubectl get pod oom-demo -w     # watch OOMKilled → CrashLoopBackOff, then press Ctrl+C to exit
kubectl get pod oom-demo -o jsonpath='{.status.containerStatuses[0].lastState.terminated}{"\n"}'
NAME       READY   STATUS             RESTARTS      AGE
oom-demo   0/1     ContainerCreating  0             2s
oom-demo   0/1     OOMKilled          0             5s
oom-demo   0/1     CrashLoopBackOff   1 (3s ago)    8s
{"containerID":"containerd://5c1e…","exitCode":137,"finishedAt":"…","reason":"OOMKilled","startedAt":"…"}
Check the cgroup on the node (a kind node is itself a Docker container):
NODE=$(kubectl get pod oom-demo -o jsonpath='{.spec.nodeName}')
CID=$(kubectl get pod oom-demo -o jsonpath='{.status.containerStatuses[0].containerID}' | sed 's#containerd://##')
docker exec $NODE sh -c "cat /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/*/cri-containerd-$CID.scope/memory.max; \
  grep oom_kill /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/*/cri-containerd-$CID.scope/memory.events"
104857600
oom_kill 3

If the path does not match (the container just restarted and its ID changed), search with docker exec $NODE find /sys/fs/cgroup -name "cri-containerd-$CID*".

Observe CPU throttling (using vish/stress, as in the official “Assign CPU Resources” docs):
kubectl run cpu-demo --image=vish/stress --restart=Never \
  --overrides='{"apiVersion":"v1","spec":{"containers":[{"name":"cpu-demo","image":"vish/stress","args":["-cpus","2"],"resources":{"requests":{"cpu":"250m"},"limits":{"cpu":"500m"}}}]}}'
sleep 60; kubectl top pod cpu-demo
NODE=$(kubectl get pod cpu-demo -o jsonpath='{.spec.nodeName}')
CID=$(kubectl get pod cpu-demo -o jsonpath='{.status.containerStatuses[0].containerID}' | sed 's#containerd://##')
docker exec $NODE sh -c "cat /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/*/cri-containerd-$CID.scope/cpu.max /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/*/cri-containerd-$CID.scope/cpu.stat"
NAME       CPU(cores)   MEMORY(bytes)
cpu-demo   500m         1Mi
50000 100000
usage_usec 30215532
…
nr_periods 612
nr_throttled 609
throttled_usec 29871023

The app wants 2 cores but is held to 500m. nr_throttled/nr_periods approaches 100%. The container stays Running: exceeding the CPU limit does not get it killed.

Resize in place: raise the CPU limit to 1 core without a restart:
kubectl get pod cpu-demo -o jsonpath='{.status.containerStatuses[0].restartCount}{"\n"}'
kubectl patch pod cpu-demo --subresource resize --type merge -p \
  '{"spec":{"containers":[{"name":"cpu-demo","resources":{"requests":{"cpu":"500m"},"limits":{"cpu":"1"}}}]}}'
sleep 30; kubectl top pod cpu-demo
kubectl get pod cpu-demo -o jsonpath='{.status.containerStatuses[0].resources}{"  restarts="}{.status.containerStatuses[0].restartCount}{"\n"}'
0
pod/cpu-demo patched
NAME       CPU(cores)   MEMORY(bytes)
cpu-demo   1000m        1Mi
{"limits":{"cpu":"1"},"requests":{"cpu":"500m"}}  restarts=0

restartCount is still 0, and cpu.max is now 100000 100000. Note that the QoS class cannot change during a resize (for example, a Burstable Pod cannot become Guaranteed through a resize).

Cleanup:
kubectl delete pod oom-demo cpu-demo --now

Case 1: Java service P99 latency spikes periodically

Problem: a Spring Boot service has limits.cpu=1. Average CPU is only 40%, but P99 latency jumps from 80 ms to 600 ms. Approach: on the node, cpu.stat shows nr_throttled at 35%. During JVM startup and GC, multiple threads burst at once and use up the quota in the first 20 ms of each 100 ms period. Configuration: remove the CPU limit and keep only requests.cpu=1 (or raise the limit to 2), and set -XX:ActiveProcessorCount on the JVM to match requests. Limitation: in a multi-tenant cluster that enforces CPU limits, agree with the platform team on a larger limit or a dedicated node pool.

Case 2: Node memory pressure causes mass eviction

Problem: nightly batch jobs (BestEffort) run alongside online services. Node memory.available fell below the threshold, the kubelet evicted a batch of Pods, and some online Pods were hit too. Approach: switch online services to Guaranteed (memory requests=limits), give batch jobs requests and run them on a separate node pool (taint, see module 8), and configure PriorityClass. Configuration: on AKS, create a Spot node pool for batch jobs and add a taint. Limitation: eviction is a node-level protection and is different from container-level OOMKilled. kubectl get pod shows Evicted / reason: Evicted.

Case 3: Enlarge a database proxy's memory without downtime

Problem: the PgBouncer sidecar's memory limit is too small, and restarting it would drop all connections. Approach: on a v1.35+ cluster, resize the running Pod (memory resizePolicy: NotRequired), then update the Deployment template and let the rollout happen in the next maintenance window. Limitation: when you lower a memory limit, the kubelet makes a best-effort check of current usage and applies the new limit only if usage is below it. Applications that need a restart (the JVM heap is fixed at startup) should set restartPolicy: RestartContainer for memory.

Common errors and fixes

Last State: Terminated Reason: OOMKilled Exit Code: 137

Cause: container memory exceeds limits.memory (memory.max), so the kernel's cgroup OOM killer kills the process.

kubectl describe pod POD | grep -A5 "Last State"
kubectl top pod POD --containers
kubectl get pod POD -o jsonpath='{.spec.containers[*].resources}'

Fix: check whether it is a leak or the limit is too small (look at the top trend and the app's heap settings). For JVM or Node.js, set the heap ceiling below the container limit (for example -XX:MaxRAMPercentage=75). As a temporary fix, raise the limit with resize.

0/3 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 2 Insufficient memory.

Cause: the sum of requests exceeds the allocatable of the worker node (not actual usage).

kubectl describe node lab-worker | grep -A8 "Allocated resources"
kubectl get pod -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,MEM:.spec.containers[*].resources.requests.memory --sort-by=.metadata.namespace

Fix: lower oversized requests, add nodes, or clean up Pods that have large requests but do not actually use them. See the Pending diagnosis in module 8.

The Pod "x" is invalid: spec.containers[0].resources.requests: Invalid value: "1Gi": must be less than or equal to memory limit of 512Mi

Cause: requests cannot be greater than limits.

Fix: adjust so that requests ≤ limits. If you set only limits, requests automatically equal limits.

error: unknown flag: --subresource or the server could not find the requested resource (patch pods resize)

Cause: kubectl is older than 1.32, or the cluster is older than 1.33 (before Beta, the feature gate has to be enabled).

kubectl version

Fix: upgrade kubectl to 1.37. On clusters 1.35 and later, the feature is GA.

Pod status Evicted: The node was low on resource: memory. Container x was using 1.2Gi, request is 256Mi

Cause: node-level memory pressure. The kubelet chooses eviction targets by how far their usage exceeds their requests.

kubectl get pod -A --field-selector=status.phase=Failed
kubectl describe node NODE | grep -A5 Conditions

Fix: set requests close to real usage. Use Guaranteed + PriorityClass for critical services. Clean up Evicted Pods: kubectl delete pod -A --field-selector=status.phase=Failed.

Command-line exercises
1. Use one command to list the name and QoS class of every Pod in the shop namespace.
kubectl get pod -n shop -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
2. Find all containers that have restarted because of OOMKilled.
kubectl get pod -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{.status.containerStatuses[*].lastState.terminated.reason}{"\n"}{end}' | grep OOMKilled
Scenario analysis
kubectl top shows the node's CPU is only 20% used, but the new api replica stays Pending with the event Insufficient cpu. Why? How do you fix it?

The scheduler decides based on the sum of requests, not actual usage. This means the existing Pods' requests are far higher than their actual usage (over-reservation). Fix: use describe node to find the biggest requests, then lower them based on top history (or VPA recommendations, hour 6). In the short term, you can add nodes.

Verified teaching videos

▶
Setting Resource Requests and Limits in Kubernetes — Google Cloud Tech
“Kubernetes Best Practices” series · 2018 · English · explains the basics of requests/limits and ResourceQuota (recorded earlier, so for newer features such as In-place resize, follow this hour)
▶
Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours] — TechWorld with Nana
English · complete beginner course; useful as extra review for hours 1–2

Official docs

Video storyboard (about 90 s)

This course file cannot generate video or MP3 directly. The storyboard and narration script are provided, so you can hand them to a video tool.

Shot 1 · 0–15s
Visual: a node box with several Pod blocks inside. A label above reads allocatable.
Narration: The scheduler looks only at requests. It adds up each Pod's reserved amount and compares the total with the node's allocatable amount.
Shot 2 · 15–40s
Visual: the timeline is split into 100 ms cells. In each cell, the CPU quota bar runs out in the first half, and the second half turns gray.
Narration: Going over the CPU limit does not kill the container. It gets throttled. When a period's quota runs out, the container waits for the next period, so latency goes up.
Shot 3 · 40–65s
Visual: the memory bar climbs and hits the red dashed line at memory.max. The container icon flashes red and shows OOMKilled 137.
Narration: Memory cannot be compressed. When the limit is exceeded, the kernel kills the process directly. Kubernetes shows OOMKilled, with exit code one hundred thirty-seven.
Shot 4 · 65–90s
Visual: three Pods are labeled Guaranteed, Burstable, and BestEffort. When the node raises a memory alert, the BestEffort Pod is removed first.
Narration: The QoS class decides who gets evicted first when node memory runs short. For critical services, set memory requests equal to limits.
or score ≥ 70% on the quiz

Module 2 · Probes and graceful termination

07:00 – 15:00 · Tell Kubernetes when a container is “alive,” when it is “ready for traffic,” and how to shut down cleanly
8 minpreStop sleep v1.34 GAgRPC probe GA★★★★★
Learning goals
  • Distinguish the meaning and failure consequences of the liveness, readiness, and startup probes. Avoid cascading restarts caused by a “liveness check that depends on other services.”
  • Choose httpGet / tcpSocket / exec / grpc based on the scenario, and calculate the detection time implied by the probe settings.
  • Draw the Pod termination sequence: deletionTimestamp → EndpointSlice update (in parallel) → preStop → SIGTERM → grace period → SIGKILL. Use preStop.sleep to remove 502s during rollouts.
Prerequisites: PID 1 and signals, and HEALTHCHECK, from the Docker course; module 1. Importance: ★★★★★

What: the three probe types

ProbeQuestion it answersResult of failureTypical checks
startupProbeHas the app finished starting?Still failing after failureThreshold × periodSeconds → kill the container and restart it according to restartPolicy. The other two probes are disabled until it succeeds.Same endpoint as liveness, but with enough time to start
livenessProbeIs the process still “alive” (no deadlock or hang)?Fails failureThreshold times in a row → kubelet restarts the containerChecks only the process itself (for example /healthz), not dependencies such as the database
readinessProbeCan it take traffic now?Failure → Pod Ready=False, and it is marked not ready in the Service's EndpointSlice. No restart.Can check critical dependencies, warm-up, and degraded state (for example /readyz)

Why: what happens without probes

  • Without readiness, a container is treated as Ready as soon as its process starts. The app gets traffic while it is still loading config or warming caches, so rollouts cause 502s or refused connections.
  • Without liveness, a deadlocked process that does not exit goes unnoticed. Kubernetes does not know, and the Pod stays “Running” while doing no work.
  • Without startup, slow-starting apps (JVM, large model loading) force you to set a very high initialDelaySeconds on liveness, which also slows failure detection while the app is running.

How: how the kubelet runs probes

Probes are run by the kubelet on the node (not the control plane). httpGet, tcpSocket, and grpc connect to the Pod IP from the network namespace of the node where the kubelet runs. exec runs a command inside the container through CRI (the most expensive option). Results are written to the Pod's status.conditions and containerStatuses[].ready. The EndpointSlice controller watches for changes and updates the endpoint's ready condition, and then kube-proxy on each node updates the nftables/iptables rules.

ParameterDefaultMeaning
initialDelaySeconds0How long after container start before probing begins (usually not needed when startupProbe is set)
periodSeconds10Probe interval
timeoutSeconds1Timeout for a single probe (raise it for apps with long GC pauses)
failureThreshold3Consecutive failures before the probe counts as failed
successThreshold1Consecutive successes before the probe counts as successful (must be 1 for liveness/startup)
terminationGracePeriodSeconds (probe level)Inherits from the PodGrace period used when killing the container after a liveness/startup failure

Four probe methods: httpGet (2xx/3xx counts as success), tcpSocket (success if a connection can be opened), exec (exit code 0 counts as success), and grpc (the standard gRPC Health Checking Protocol, GA in v1.27).

Full graceful termination flow

  1. A user or controller deletes the Pod: the apiserver sets metadata.deletionTimestamp and deletionGracePeriodSeconds (default terminationGracePeriodSeconds: 30).
  2. Two things happen in parallel: (a) the EndpointSlice controller marks the endpoint as ready: false, terminating: true, and kube-proxy on each node updates forwarding rules asynchronously; (b) the kubelet on the node sees the deletion and starts terminating the container.
  3. The kubelet first runs the preStop hook (exec / httpGet / sleep). Time spent in the hook counts toward the grace period.
  4. After preStop finishes, the container runtime sends SIGTERM to PID 1 (or the image's STOPSIGNAL).
  5. If the process has not exited when the grace period ends → SIGKILL (exit code 137). Then the Pod object is removed from the apiserver.

Race condition: if the app closes its listening port as soon as it gets SIGTERM, but kube-proxy on some nodes has not updated its rules yet (a few hundred milliseconds to several seconds), new requests can still be forwarded to this Pod, which causes connection refused or 502. Fix: lifecycle.preStop.sleep.seconds: 5 (PodLifecycleSleepAction, GA in v1.34, with no sleep binary needed in the image). It waits for endpoint removal to propagate before SIGTERM is sent. After receiving SIGTERM, the app stops accepting new connections, finishes in-flight requests, and then exits.

When: how to choose

  • Every service that receives traffic must have a readiness probe.
  • liveness: configure it only when there is a real risk of “hanging without exiting,” and keep thresholds loose (for example period 10s × 3 failures).
  • Startup takes > 10 seconds or varies a lot: add a startupProbe (for example failureThreshold: 30, periodSeconds: 5 = up to 150 seconds).

Comparison with similar technologies

KubernetesDocker HEALTHCHECKAzure LB / App Gateway health probes
ExecutorNode kubeletdockerdCloud load balancer
Action on failureliveness restarts / readiness removes from trafficOnly marks it unhealthy (no automatic restart on a single machine)Removed from the backend pool
Startup protectionstartupProbe--start-periodNone
Common misconceptions ① Having liveness check the database. A 10-second database blip makes liveness fail on every api Pod at once. All of them restart, and the restart storm plus cold starts amplify the outage (cascading restarts). Dependency checks belong only in readiness. ② Using the same endpoint and thresholds for liveness and readiness. Under overload, a Pod is taken out of traffic and then restarted right away, which removes its chance to recover. ③ Assuming a deleted Pod is removed from traffic before SIGTERM is sent. The two happen in parallel, with no ordering guarantee.

Architecture diagram: how probe results affect traffic

Node lab-worker kubeletprober every periodSeconds Pod api (podinfo)GET /healthz → livenessGET /readyz → readiness:9898 liveness failsCRI StopContainer → restart kube-proxy: nftables rules include only ready endpoints kube-apiserverPod status: Ready=False PATCH pods/status EndpointSlice controllerwatches Pods → updates endpoints EndpointSliceconditions.ready=false watch (kube-proxy on all nodes)
Figure 2-1: liveness takes the “restart” path (on this node only), and readiness takes the “remove from traffic” path (propagated to all nodes through the control plane)

Sequence diagram: two parallel timelines for Pod termination

Time DELETEdeletionTimestamp Control plane lane EndpointSlice: ready=false, terminating=true kube-proxy on each node updates rules (asynchronously) kubelet lane preStop: sleep 5s (counts toward grace period) SIGTERM → finish in-flight requests, then exit SIGKILL at 30s
Figure 2-2: preStop sleep makes SIGTERM arrive after “endpoint removal has finished propagating,” which removes connection errors during rollouts

Termination timeline: endpoint removal vs the SIGTERM race

Choose whether to set preStop.sleep, then play. Each cell is 1 second. The client sends 4 requests per second to the Service, so you can see how many requests land on the Pod that is shutting down and fail.

Ready.
$ kubectl delete pod api-6d9f7c8b5d-4kx2p

Core commands and config

CommandPurposeKey flags / notes
kubectl describe podView the probe config and Unhealthy eventsIn Events: Liveness probe failed / Readiness probe failed
kubectl get pod -o wideREADY column (ready containers / total)0/1 Running = the process is running but not ready
kubectl get endpointslice -l kubernetes.io/service-name=apiCheck whether endpoints are ready-o yaml to view conditions
kubectl get events --field-selector reason=UnhealthyView probe failures in one place--sort-by=.lastTimestamp
kubectl delete pod --grace-period=NSet the grace period for this deletion--grace-period=0 --force, only for stuck Pods on a failed node
spec:
  template:
    spec:
      terminationGracePeriodSeconds: 30
      containers:
      - name: podinfo
        image: ghcr.io/stefanprodan/podinfo:6.17.0
        ports:
        - { name: http, containerPort: 9898 }
        startupProbe:
          httpGet: { path: /healthz, port: http }
          periodSeconds: 2
          failureThreshold: 30        # wait up to 60 s to start
        livenessProbe:
          httpGet: { path: /healthz, port: http }
          periodSeconds: 10
          timeoutSeconds: 2
          failureThreshold: 3         # restart only after about 30 s without a response
        readinessProbe:
          httpGet: { path: /readyz, port: http }
          periodSeconds: 5
          failureThreshold: 2
        lifecycle:
          preStop:
            sleep: { seconds: 5 }     # v1.34 GA, no sleep command needed in the image
kubectl patch deploy api --type strategic --patch-file api-probes.yaml
kubectl rollout status deploy/api
kubectl describe pod -l app=api | grep -E "Liveness|Readiness|Startup"
    Liveness:   http-get http://:http/healthz delay=0s timeout=2s period=10s #success=1 #failure=3
    Readiness:  http-get http://:http/readyz delay=0s timeout=1s period=5s #success=1 #failure=2
    Startup:    http-get http://:http/healthz delay=0s timeout=1s period=2s #success=1 #failure=30

How to verify: the time for the READY column to change from 0/1 to 1/1 ≈ startup time + the first successful readiness check. Common mistakes: a wrong port name (port: http must match ports[].name); timeoutSeconds: 1 is too short for apps with long GC pauses. Production use: readiness works with maxUnavailable so a rollout continues only after the new Pods are truly ready.

gRPC and exec examples

livenessProbe:
  grpc: { port: 9090, service: "" }   # the app must implement grpc.health.v1.Health
readinessProbe:
  exec:
    command: ["pg_isready", "-U", "postgres", "-h", "127.0.0.1"]

Lab 2: Add probes to api, and verify that readiness removes a Pod from traffic and that rollouts have zero downtime (about 7 min)

Apply the probe config: save the snippet from the “Commands” tab as api-probes.yaml (keep only spec: and below), then:
kubectl patch deploy api --type strategic --patch-file api-probes.yaml
kubectl rollout status deploy/api
kubectl get pod -l app=api
Manually make one Pod not ready (podinfo provides POST /readyz/disable):
POD=$(kubectl get pod -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl port-forward pod/$POD 9898:9898 >/dev/null 2>&1 &
sleep 2; curl -s -X POST localhost:9898/readyz/disable; sleep 12
kubectl get pod $POD
kubectl get endpointslice -l kubernetes.io/service-name=api -o jsonpath='{range .items[*].endpoints[*]}{.targetRef.name}{" ready="}{.conditions.ready}{"\n"}{end}'
NAME                   READY   STATUS    RESTARTS   AGE
api-7c9d6f5b8-2lq9x    0/1     Running   0          3m
api-7c9d6f5b8-2lq9x ready=false
api-7c9d6f5b8-8mfkw ready=true
api-7c9d6f5b8-zt5rn ready=true

The Pod is not restarted (RESTARTS stays at 0); it is only removed from load balancing. To recover, run curl -X POST localhost:9898/readyz/enable, then end the port-forward with kill %1.

Start a continuous load client (pinned to lab-worker2, so later operations do not affect it):
kubectl run load --image=curlimages/curl --restart=Never \
  --overrides='{"apiVersion":"v1","spec":{"nodeSelector":{"kubernetes.io/hostname":"lab-worker2"}}}' \
  --command -- sh -c 'while true; do curl -s -o /dev/null -m 2 -w "%{http_code}\n" http://api:9898/version; sleep 0.1; done'
kubectl logs -f load | sort | uniq -c   # run in another terminal, press Ctrl+C to see the stats
Trigger a rollout and count errors:
kubectl rollout restart deploy/api && kubectl rollout status deploy/api
kubectl logs load | sort | uniq -c
   1834 200

Comparison: remove preStop (kubectl patch deploy api --type json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/lifecycle"}]') and roll out again. You may see a few 000 results (connection failures). A kind cluster is small and propagates quickly, so the difference may not show up every time. It is more visible in large clusters and behind cloud load balancers.

Cleanup:
kubectl delete pod load --now

Keep the probe config. The capstone lab uses it.

Case 1: A database blip triggers a site-wide restart storm

Problem: the order service's liveness calls /health, which queries PostgreSQL. A primary/replica failover took 20 seconds. Liveness failed on all Pods at once, so they all restarted. The JVM cold start took 60 seconds, and the outage grew from 20 seconds to 3 minutes. Approach: split the endpoints: /livez checks only the process internals, and /readyz checks the database connection pool. Configuration: liveness failureThreshold: 6, periodSeconds: 10, and add a startupProbe. Limitation: when all readiness checks fail, the Service has no endpoints and clients get connection errors. This needs an application-level degradation strategy.

Case 2: 0.3% 502s during a rolling release

Problem: behind Azure Application Gateway / a cloud LB, every release produces a few 502s. Approach: add preStop.sleep: 10 (cloud LB backend removal is slower than kube-proxy). The app handles SIGTERM by stopping new connections and waiting for in-flight requests to finish. terminationGracePeriodSeconds must be ≥ preStop + the longest request time. Limitation: a long grace period slows node drains and releases.

Case 3: Model service killed by liveness after 4 minutes of startup

Problem: the inference service needs 3–5 minutes to load its model, and liveness initialDelaySeconds: 60 causes endless restarts. Approach: use a startupProbe with periodSeconds: 10, failureThreshold: 40 (up to 400 seconds), and keep liveness responsive. Limitation: readiness does not run until the startupProbe succeeds, so the Pod receives no traffic. This is expected behavior.

Common errors and fixes

Warning Unhealthy Liveness probe failed: Get "http://10.244.1.7:9898/healthz": context deadline exceeded (Client.Timeout exceeded while awaiting headers)

Cause: probe timeout (default 1 second). Common causes are CPU throttling (module 1), GC pauses, or slow work inside the endpoint.

kubectl describe pod POD | grep -A3 Liveness
kubectl top pod POD
kubectl get events --field-selector involvedObject.name=POD,reason=Unhealthy

Fix: raise timeoutSeconds. Confirm the endpoint does not call external dependencies. Check whether the CPU limit is causing throttling.

Readiness probe failed: HTTP probe failed with statuscode: 503 (the Pod stays at 0/1 Running)

Cause: the app considers itself not ready (a dependency is unavailable or warm-up is incomplete), or the probe path or port is wrong (a 404 also counts as a failure).

kubectl exec POD -- wget -qO- -S localhost:9898/readyz 2>&1 | head
kubectl logs POD --tail=50

Fix: correct the path or port. Check the dependencies. If the degradation is intentional, make sure at least some replicas are Ready.

Back-off restarting failed container … Liveness probe failed (repeated restarts during startup)

Cause: startup takes longer than the window that liveness allows. In kubectl describe, Last State often shows exit code 137 (killed by the kubelet) or 143.

Fix: add a startupProbe, and make the window (failureThreshold × periodSeconds) longer than the P99 startup time.

Pod stays in Terminating for a long time after deletion, last Exit Code 137

Cause: the app does not handle SIGTERM (for example, a shell-form CMD where PID 1 is sh), so it waits out the full grace period and is then killed with SIGKILL. It can also be a finalizer or a lost node.

kubectl get pod POD -o jsonpath='{.metadata.deletionTimestamp} {.metadata.finalizers}{"\n"}'
kubectl describe pod POD | grep -A4 "Last State"

Fix: use the exec-form ENTRYPOINT or tini (Docker course hour 2, module 1). If a finalizer is involved, first check the controller that owns it. Do not delete the finalizer carelessly.

spec.containers[0].livenessProbe.successThreshold: Invalid value: 2: must be 1

Cause: successThreshold for liveness and startup probes must be 1. Fix: remove the field or set it to 1.

Command-line exercises
1. Show all current endpoints of the api Service and their ready / terminating status.
kubectl get endpointslice -l kubernetes.io/service-name=api -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{" ready="}{.conditions.ready}{" terminating="}{.conditions.terminating}{"\n"}{end}'
2. List all probe failure events from the last 30 minutes.
kubectl get events -A --field-selector reason=Unhealthy --sort-by=.lastTimestamp
Scenario analysis
A service's liveness and readiness probes both point to /health, with the same thresholds. During peak hours, CPU is maxed out. You see Pods first change to 0/1, then RESTARTS increases, and service capacity drops further. Explain the cause and propose a fix.

Overload makes /health time out. Readiness fails first and removes the Pod from traffic, and then liveness fails too and restarts it. The Pod loses its chance to recover after being removed from traffic, and the restart adds a cold start, which creates a feedback loop. Fixes: split the endpoints; make liveness clearly more lenient than readiness (longer period, higher failureThreshold, longer timeout); set sensible CPU requests/limits and an HPA; and add a PDB and rate limiting.

Verified teaching videos

▶
Kubernetes Health Checks with Readiness and Liveness Probes — Google Cloud Tech
“Kubernetes Best Practices” series · 2018 · English · explains the difference between the two probe types (startupProbe and preStop sleep did not exist when it was recorded)

The companion blog post for the “terminating with grace” episode is verified (Google Cloud blog, 2018-05-18), but its YouTube video ID could not be verified, so no video link is listed.

Official docs

Video storyboard (about 100 s)

This course file cannot generate video or MP3 directly. The storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a small kubelet robot knocks on /healthz and /readyz every few seconds.
Narration: Probes are run by the kubelet on the node. If liveness fails, the container restarts. If readiness fails, the Pod is taken out of traffic.
Shot 2 · 20–45s
Visual: the database flashes red, and all api Pods restart at the same time in an avalanche animation.
Narration: Never check the database in liveness. Otherwise, one database blip restarts every replica at once.
Shot 3 · 45–80s
Visual: two parallel timelines. The top one shows EndpointSlice updates spreading to each node, and the bottom one shows SIGTERM. Without preStop, requests that hit the shut-down Pod turn red.
Narration: When a Pod is deleted, removing it from traffic and sending SIGTERM start at the same time. preStop sleep makes SIGTERM arrive a few seconds later.
Shot 4 · 80–100s
Visual: the config snippet highlights preStop sleep seconds 5 and terminationGracePeriodSeconds 30.
Narration: The grace period must be longer than preStop plus the longest request processing time.
or score ≥ 70% on the quiz

Module 3 · ConfigMap and Secret

15:00 – 22:00 · One image runs across dev, test, and prod: externalized config, the truth about hot updates, and why “Secret is not encryption”
7 mincore/v1 GASecret is base64 only by default★★★★☆
Learning goals
  • Create ConfigMaps and Secrets with --from-literal / --from-file / --from-env-file and YAML, and choose how to inject them: env, envFrom, or volume.
  • Predict accurately what happens after a config update: env stays the same, volumes update with a delay, and subPath does not update. Trigger a rollout with rollout restart or a checksum annotation.
  • Understand the real security boundaries of Secrets (base64, etcd, RBAC). Create tls and docker-registry Secrets and configure imagePullSecrets.
Prerequisites: environment variables and bind mounts from the Docker course, and the 12-Factor configuration principles. Priority: ★★★★☆

What: two configuration objects

ConfigMap stores non-sensitive key-value pairs or files (data holds UTF-8 strings, binaryData holds base64). Each object is limited to 1 MiB, which is the etcd request size limit. Secret has a similar structure. The values in data are base64-encoded. You can also write plain text in stringData, and the apiserver encodes it automatically. Each Secret has a type, such as Opaque, kubernetes.io/tls, kubernetes.io/dockerconfigjson, kubernetes.io/service-account-token, or kubernetes.io/basic-auth.

Why: why externalize configuration

An image should be environment-independent (the "cloud rules" from the Docker course). The same digest differs between dev and prod only through ConfigMaps and Secrets. That is how you get "build once, deploy anywhere," and it keeps passwords out of image layers and Git.

How: four ways to use them

MethodSyntaxBehavior after a ConfigMap updateBest for
env (single key)env[].valueFrom.configMapKeyRefUnchanged. Environment variables are set when the container starts, so you must restart itA few switches and ports
envFrom (all keys)envFrom[].configMapRef, optionally with prefixUnchanged12-Factor style apps
volumevolumes[].configMap + volumeMountsEventually updated: the kubelet syncs periodically (default syncFrequency is 1 minute), plus a cache TTL. Changes usually take effect within 1–2 minutes. Updates are applied by atomically switching the symlink (..data)Config files, for apps that support hot reload
volume + subPathvolumeMounts[].subPathNever updated (the bind mount holds the single file as it was when mounted)You want to overwrite one file in a directory, and you accept a restart to apply the change

immutable: with immutable: true, the data cannot be changed. You can only delete and recreate it. The kubelet stops watching it, which significantly reduces apiserver load in large clusters and prevents accidental edits. It works best with a version or hash in the name, such as api-config-v3 or the hash suffix from a Kustomize generator.

Real Secret security: base64 is only an encoding, so anyone who can get secret can decode it. By default, etcd also stores it in plain text. Kubernetes protects it with RBAC access control, sends it only to nodes whose Pods need it, mounts it as tmpfs on the node, and lets you enable etcd encryption at rest (KMS v2, hour 5). For production, use Azure Key Vault with the Secrets Store CSI Driver, or External Secrets Operator.

When: selection guidelines

  • If configuration changes need auditable, rollback-capable releases, use immutable, versioned names. Changing the config means changing the Deployment template, which triggers a rolling update, and rollout undo can roll back the config.
  • If the app supports hot reload and changes often (such as feature flags), use volume mounts. Do not use subPath.
  • For any password, token, or certificate, use a Secret and restrict access with RBAC. Do not put it in a ConfigMap or an image.

Comparison with similar technologies

ConfigMap/SecretDocker ComposeAzure App Configuration / Key Vault
Storageetcd (in-cluster).env / secrets filesManaged service, with versioning and auditing
Injectionenv / filesenv / /run/secretsSDK, CSI driver, or ESO syncs into a Secret
EncryptionNone by default; requires KMS configurationNoneHSM / managed keys
Common misconceptions ① "If I change a ConfigMap, Pods use the new config." That never happens with env. With volumes, only the files change, and whether the app rereads them depends on the app. ② "Secrets are encrypted." They are not. ③ "A Deployment rolls out automatically when its ConfigMap changes." It does not. A Deployment only rolls out when its Pod template changes.

Architecture diagram: how configuration flows from the apiserver to containers

kube-apiserveretcd: ConfigMap / Secret kubectl apply / editPUT configmaps/api-config kubelet configMapAndSecretChangeDetectionStrategy: Watch (default) At startup: resolve env → CRI Periodic sync: update volume files(syncFrequency defaults to 1m) watch Container A: env / envFromUI_MESSAGE=hello (written to environ when the process starts)After ConfigMap update: unchanged until the container restarts Container B: volume /etc/appconfig.yaml → ..data/config.yaml → ..2026_11_15_…After update: the ..data symlink switches atomically (about 1–2 minutes) Container C: subPath /etc/app/config.yamlBind mount of a single file inode → never updated
Figure 3-1: how the three injection methods behave when configuration is updated

Flowchart: reliable configuration release (checksum annotation pattern)

Edit config.yamlGit commit Compute sha256CI / Helm / Kustomize Write to Pod template annotationchecksum/config: 9f2c… Template changesNew ReplicaSet Rolling updateCan rollout undo
Figure 3-2: the checksum annotation recommended in the Helm docs, which makes a config change equivalent to a Pod template change

After a ConfigMap update, which injection methods take effect?

First, "create the ConfigMap and deploy three Pods." Then "update the ConfigMap." Next, use "time fast-forward" to watch the kubelet sync. Finally, try rollout restart.

Click ①.
$ # ConfigMap api-config: UI_MESSAGE=v1

Core commands

CommandPurposeKey parameters
kubectl create configmap NAMECreate ConfigMap--from-literal=K=V, --from-file=[key=]path, --from-env-file=.env
kubectl create secret genericOpaque SecretSame as above; values are base64-encoded
kubectl create secret tlsTLS certificate--cert=tls.crt --key=tls.key
kubectl create secret docker-registryImage pull credentials--docker-server --docker-username --docker-password
... --dry-run=client -o yamlGenerate YAML without creating the object (essential for GitOps)Use with kubectl apply -f - for idempotent updates
kubectl rollout restart deploy/XAdd a kubectl.kubernetes.io/restartedAt annotation to trigger a rolling updateGeneral approach after configuration changes
kubectl create configmap api-config \
  --from-literal=PODINFO_UI_MESSAGE="Hello from shop v1" \
  --from-literal=PODINFO_UI_COLOR="#34577c"
cat > app.properties <<'EOF'
featureX=true
cacheTTL=60
EOF
kubectl create configmap api-files --from-file=app.properties
kubectl create secret generic db-cred \
  --from-literal=POSTGRES_USER=shop --from-literal=POSTGRES_PASSWORD='S3cure!Pass' --from-literal=POSTGRES_DB=shop
kubectl get secret db-cred -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d; echo
configmap/api-config created
configmap/api-files created
secret/db-cred created
S3cure!Pass

The last row notes that a Secret is only base64: anyone with get secrets permission can read the plain text. Common mistakes: if the password in --from-literal contains $ or !, use single quotes. echo "pw" | base64 also encodes the newline, so use echo -n instead.

Use in a Deployment

spec:
  template:
    metadata:
      annotations:
        checksum/config: "REPLACE_WITH_SHA256"   # config change → template change → rolling update
    spec:
      containers:
      - name: podinfo
        envFrom:
        - configMapRef: { name: api-config }
        env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef: { name: db-cred, key: POSTGRES_PASSWORD }
        volumeMounts:
        - { name: files, mountPath: /etc/shop, readOnly: true }
      volumes:
      - name: files
        configMap: { name: api-files }

Image pull credentials (private registry / ACR)

kubectl create secret docker-registry acr-pull \
  --docker-server=myacr.azurecr.io --docker-username=<token-name> --docker-password=<token-password>
kubectl patch serviceaccount default -p '{"imagePullSecrets":[{"name":"acr-pull"}]}'

Production use: on AKS, it is better to assign AcrPull to the cluster's kubelet managed identity (az aks update --attach-acr). Then you do not need imagePullSecrets at all.

Lab 3: externalized configuration and a comparison of the three injection methods (about 6 minutes)

Create the configuration: run the three create commands on the "Commands" tab (api-config, api-files, db-cred).
Have api use env + volume + subPath:
kubectl patch deploy api --type strategic -p '
spec:
  template:
    spec:
      containers:
      - name: podinfo
        envFrom:
        - configMapRef: { name: api-config }
        volumeMounts:
        - { name: files, mountPath: /etc/shop }
        - { name: files, mountPath: /etc/single/app.properties, subPath: app.properties }
      volumes:
      - name: files
        configMap: { name: api-files }'
kubectl rollout status deploy/api
POD=$(kubectl get pod -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl exec $POD -- sh -c 'echo ENV=$PODINFO_UI_MESSAGE; cat /etc/shop/app.properties; echo ---; cat /etc/single/app.properties; ls -la /etc/shop'
ENV=Hello from shop v1
featureX=true
cacheTTL=60
---
featureX=true
cacheTTL=60
lrwxrwxrwx … app.properties -> ..data/app.properties
lrwxrwxrwx … ..data -> ..2026_11_15_08_30_12.1234567
Update both ConfigMaps, wait about 90 seconds, then observe:
kubectl create configmap api-config --from-literal=PODINFO_UI_MESSAGE="Hello v2" \
  --from-literal=PODINFO_UI_COLOR="#34577c" --dry-run=client -o yaml | kubectl apply -f -
kubectl create configmap api-files --from-literal=app.properties=$'featureX=false\ncacheTTL=120' \
  --dry-run=client -o yaml | kubectl apply -f -
sleep 90
kubectl exec $POD -- sh -c 'echo ENV=$PODINFO_UI_MESSAGE; cat /etc/shop/app.properties; echo ---; cat /etc/single/app.properties'
ENV=Hello from shop v1          ← env: unchanged
featureX=false                  ← volume: updated
cacheTTL=120
---
featureX=true                   ← subPath: unchanged
cacheTTL=60
Trigger a rollout with the checksum annotation so that every method takes effect:
SUM=$(kubectl get cm api-config api-files -o yaml | sha256sum | cut -c1-16)
kubectl patch deploy api -p "{\"spec\":{\"template\":{\"metadata\":{\"annotations\":{\"checksum/config\":\"$SUM\"}}}}}"
kubectl rollout status deploy/api
POD=$(kubectl get pod -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl exec $POD -- sh -c 'echo ENV=$PODINFO_UI_MESSAGE; cat /etc/single/app.properties'
kubectl rollout history deploy/api | tail -3

ENV changes to Hello v2, and the subPath file also gets the new content. In real projects, compute the hash over the config source file (Helm's sha256sum template function, or the hash suffix from Kustomize's configMapGenerator). Here, hashing the object YAML is only for demonstration.

Try immutable:
kubectl create configmap feature-v1 --from-literal=mode=a --dry-run=client -o yaml \
  | sed '/^kind:/i immutable: true' | kubectl apply -f -
kubectl patch cm feature-v1 -p '{"data":{"mode":"b"}}'
configmap/feature-v1 created
The ConfigMap "feature-v1" is invalid: data: Forbidden: field is immutable when `immutable` is set
Cleanup: kubectl delete cm feature-v1. Keep api-config, api-files, and db-cred for later modules. The subPath mount at /etc/single can stay, or you can remove it in the capstone lab.

Case 1: a bad config cannot be rolled back

Problem: the team ran kubectl edit cm to change the connection pool size. After the Pods restarted, they could not connect to the database at all, and nobody knew the old value. Approach: use an immutable ConfigMap with a content-hash name (Kustomize configMapGenerator). The Deployment references the new name, which triggers a rolling update. Rollback = rollout undo, which returns to the ReplicaSet that references the old ConfigMap. Limitation: keep an old ConfigMap until no ReplicaSet references it. Kustomize and Argo CD can be configured with a cleanup policy.

Case 2: Nginx config hot reload does not take effect

Problem: to overwrite only /etc/nginx/conf.d/default.conf, the team used subPath, and config updates never took effect. Approach: mount the whole directory /etc/nginx/conf.d instead (no subPath), and pair it with a sidecar that watches for file changes and runs nginx -s reload, or simply use the checksum rollout. Limitation: mounting the whole directory hides the other files that the image has in that directory.

Case 3: database password leaked into CI logs

Problem: a pipeline ran kubectl get secret -o yaml for debugging, and the base64 values were printed to the logs. Approach: use RBAC to remove the CI identity's permission to read Secrets. Move the password to Azure Key Vault, and mount it through the Secrets Store CSI Driver with Workload Identity (hour 5). Enable etcd KMS encryption. Limitation: anyone who can create Pods can still mount any Secret in the namespace. The namespace is the permission boundary.

Common errors and fixes

Error: configmap "api-config" not found (Pod status CreateContainerConfigError)

Cause: the referenced ConfigMap or Secret, or the key inside it, does not exist. The kubelet cannot assemble the environment variables, so the container is not created.

kubectl describe pod POD | grep -A3 -i "error"
kubectl get cm,secret

Fix: create the object, or correct the name or key. For optional dependencies, set optional: true.

MountVolume.SetUp failed for volume "files" : configmap "api-files" not found (Pod stuck in ContainerCreating)

Cause: the ConfigMap referenced by the volume does not exist.

Fix: same as above. Check events with kubectl get events --field-selector involvedObject.name=POD.

I changed the ConfigMap, but the app behavior did not change

Cause: env requires a restart. subPath never updates. With volumes, the files are updated, but the app does not reread them on its own.

kubectl exec POD -- env | grep KEY
kubectl exec POD -- cat /path/to/file

Fix: kubectl rollout restart deploy/X, or use the checksum annotation pattern.

Failed to pull image "myacr.azurecr.io/api:1.0": … 401 Unauthorized (ErrImagePull)

Cause: there is no imagePullSecrets entry, the Secret is in another namespace (imagePullSecrets can only reference Secrets in the same namespace), or the credentials have expired.

kubectl get pod POD -o jsonpath='{.spec.imagePullSecrets}'
kubectl get secret acr-pull -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d

Fix: create a docker-registry Secret in the same namespace, and attach it to the Pod or ServiceAccount. On AKS, use --attach-acr.

error: failed to create configmap: … Too long: must have at most 1048576 bytes

Cause: the ConfigMap is larger than 1 MiB. Fix: store large files in the image, in object storage, or on a PVC. Do not put large data into a ConfigMap, other than certificate chains.

Command-line exercises
1. Use a .env file to create or update the ConfigMap web-env idempotently.
kubectl create configmap web-env --from-env-file=.env --dry-run=client -o yaml | kubectl apply -f -
2. Find all Pods in the namespace that reference the Secret db-cred.
kubectl get pod -o json | jq -r '.items[] | select(tostring | test("db-cred")) | .metadata.name'
Scenario analysis
The team wants to "change config without restarting Pods," and also wants "every config change to be auditable and rollback-able with one command." Do these two requirements conflict? How would you design it?

There is tension here. Hot updates (volume mount plus the app rereading the file) do not go through Deployment revision history, so rollback only works by reapplying from Git. Versioned releases (immutable ConfigMap, hashed name, and a rolling update) are auditable and rollback-able, but they restart Pods. A common approach is to release business-critical config through versioned rollouts, and to move frequently adjusted feature flags into a dedicated configuration service (Azure App Configuration or a feature-flag platform). The application then fetches values through an SDK, and the service provides its own audit trail.

Verified teaching videos

▶
Kubernetes ConfigMap and Secret as Kubernetes Volumes | Demo — TechWorld with Nana
English · demo that mounts ConfigMap/Secret as volumes (does not cover immutable or the checksum pattern)
▶
Complete Application Deployment using Kubernetes Components | Kubernetes Tutorial 20 — TechWorld with Nana
English · deploying a complete app with a Deployment, Service, ConfigMap, and Secret

Official documentation

Video storyboard script (about 80 seconds)

This lesson cannot generate a video or MP3 directly, so it provides a storyboard and a narration script.

Shot 1 · 0–20s
Visual: the same image box gets a dev config card and a prod config card.
Narration: the image is environment-independent. All the differences live in the ConfigMap and Secret.
Shot 2 · 20–50s
Visual: the ConfigMap changes from v1 to v2. There are three containers: the env container stays at v1, the volume container changes to v2 after about a minute, and the subPath container stays at v1.
Narration: environment variables are fixed at startup. Volume mounts update within a minute or two. subPath never updates.
Shot 3 · 50–80s
Visual: a single command decodes the Secret's base64 string into plain text, and a "RBAC + KMS" shield lights up beside it.
Narration: a Secret is encoded, not encrypted. Real protection comes from access control, etcd encryption, and an external key store.
Or score ≥ 70% on the quiz

Module 4 · Advanced Release Strategies

22:00 – 30:00 · Work out the rolling update parameters, then use native objects to implement blue/green, canary, and PodDisruptionBudgets
8 minapps/v1 · policy/v1 GAweighted traffic: see hour 3★★★★★
Learning objectives
  • Calculate by hand how maxSurge and maxUnavailable round for a given replica count, and the upper and lower bounds on the Pod count during a rollout.
  • Use minReadySeconds, progressDeadlineSeconds, and pause/resume, and recognize ProgressDeadlineExceeded.
  • Implement blue/green with a Service selector, implement canary with replica ratios, and protect voluntary disruptions (drain, upgrades) with a PodDisruptionBudget.
Prerequisites: Module 7 of hour 1 (Deployments, rollout undo), and Module 2 of this hour (readiness). Priority: ★★★★★

What: Deployment rolling update parameters

FieldDefaultRoundingMeaning
strategy.rollingUpdate.maxSurge25%Rounds upHow many Pods can be created above replicas during a rollout
strategy.rollingUpdate.maxUnavailable25%Rounds downHow many Pods can be unavailable during a rollout (both cannot be 0 at the same time)
minReadySeconds0—How many seconds a new Pod must stay Ready before it counts as Available (prevents a Pod that becomes ready and then crashes right away)
progressDeadlineSeconds600—If there is no progress for longer than this, the condition Progressing=False, reason=ProgressDeadlineExceeded is set. It does not roll back automatically.
revisionHistoryLimit10—How many old ReplicaSets to keep for rollback

Example calculation: replicas=10, maxSurge=25% → ⌈2.5⌉=3, maxUnavailable=25% → ⌊2.5⌋=2. During the rollout, the total Pod count is ≤ 13 and the available Pod count is ≥ 8. With replicas=3: surge ⌈0.75⌉=1, unavailable ⌊0.75⌋=0. So one new Pod starts, and once it is ready, one old Pod is deleted. At least 3 Pods are always available.

Why: why you need more strategies

The problem with rolling updates is that old and new versions run at the same time, and traffic is distributed by Pod count. You cannot send "5% of users to try it first," and you cannot "switch everything back instantly." Blue/green and canary solve those two problems. PDBs solve a different one: non-release causes (node drains, cluster upgrades, scale-down) evicting too many replicas at once.

How: implement with native objects

  • Blue/green: two Deployments, api-blue (label version: blue) and api-green, with version included in the Service selector. Once green is fully ready and verified, kubectl patch svc changes the selector to green. The EndpointSlice controller then recalculates the endpoints, and each node's kube-proxy updates its rules, so everything switches within seconds. Rollback = change the selector back to blue. The cost is double the resources during the release.
  • Canary (replica ratio): the stable and canary Deployments share the label that the Service selects (app: api), and replica counts control the ratio. For example, 9 stable + 1 canary ≈ 10% of traffic. Limitations: the granularity of the ratio is limited by the replica count (1% requires 100 replicas), you cannot route by header or by user, and each connection lands randomly (long-lived connections are unevenly distributed). Precise weights and header-based routing require Gateway API HTTPRoute weights (hour 3) or Argo Rollouts (hour 6).
  • pause/resume: after kubectl rollout pause, multiple template changes (image, resources, environment variables) do not each trigger a rollout. They take effect together when you run resume. You can also pause partway through a rollout as a simple canary.
  • PodDisruptionBudget (policy/v1): minAvailable or maxUnavailable. Choose one. Values can be numbers or percentages. It only limits voluntary disruptions initiated through the Eviction API, such as kubectl drain, cluster autoscaler scale-down, and AKS node upgrades. It does not protect against kubectl delete pod run directly, Deployment rolling updates (those are controlled by maxUnavailable), node failures, or other involuntary disruptions. unhealthyPodEvictionPolicy: AlwaysAllow (GA in v1.31) allows evicting Pods that are already unhealthy, so they do not block a drain.

When: selection guidelines

StrategyBest forNot suitable for
RollingUpdateMost stateless services, and backward-compatible changesOld and new versions cannot coexist (incompatible database schema)
RecreateCannot coexist, single instance, and downtime is acceptableNeeds continuous availability
Blue/greenNeeds whole-environment rollback within seconds, and full verification before releaseTight resources, or stateful dependencies that are hard to dual-write
CanaryHigh-risk changes that need gradual verification with real trafficNeeds an exact 1% or per-user traffic splits (use Gateway API / Rollouts)

Comparison with similar technologies

K8s nativeArgo RolloutsAzure App Service deployment slots / ACA revisions
Blue/greenSwitch the selector manuallyBlueGreen strategy + preview Service + automatic switchingslot swap
CanaryReplica ratioStepwise weights + metric analysis with automatic rollbackPercentage-based traffic split across revisions
Automatic rollbackNone (CI has to judge rollout status)Yes (AnalysisTemplate)Partial support
Common misconceptions ① "ProgressDeadlineExceeded rolls back automatically." It does not. It only sets a condition. kubectl rollout status returns a non-zero exit code, and CI or a person has to run rollout undo. ② "With a PDB, a rolling update will never go below minAvailable." Rolling updates do not use the Eviction API. They are controlled by maxUnavailable. ③ "Setting the PDB's minAvailable equal to the replica count is the safest option." That makes drains impossible to complete, and node upgrades get stuck.

Architecture diagram: object relationships for blue/green and canary

Blue/green: switch the Service selector Service apiselector: app=api, version=green Deployment api-blueversion=blue · 6.16.03 Pods (kept for rollback) Deployment api-greenversion=green · 6.17.03 Pods (receiving traffic) Before switchAfter switch Canary: shared label + replica ratio Service apiselector: app=api api-stableapp=api, track=stable9 Pods ≈ 90% api-canaryapp=api, track=canary1 Pod ≈ 10%
Figure 4-1: blue/green switches the selector, while canary is controlled by the ratio of endpoints (kube-proxy picks each ready endpoint with equal probability)

Flowchart: how the Eviction API and PDB interact during a drain

kubectl drainCordon the node first POST pods/evictionPod by pod apiserver checks the PDBstatus.disruptionsAllowed >0: 201, the Pod is deleted (normal termination flow)The Deployment creates a replacement replica on another node =0: 429 Too Many RequestsThe drain retries every 5 seconds until the new replica is Ready
Figure 4-2: a PDB only applies to the Eviction API. disruptionsAllowed is continuously calculated by the disruption controller from the current number of healthy replicas

Interactive 1: rolling update calculator

replicas maxSurge maxUnavailable
Change the parameters, then click "Simulate batch by batch."

Interactive 2: blue/green switch and canary ratio

Blue/green
Canary: stable 9 / canary 1
canary replica count (total fixed at 10)
$ kubectl get svc api -o jsonpath='{.spec.selector}' {"app":"api","version":"blue"}

Core commands

CommandPurposeKey parameters / notes
kubectl rollout status deploy/XWait for the rollout to finish; exits non-zero on failure--timeout=5m; CI gate
kubectl rollout pause / resumePause/resume a rollout, batch template changesChanges made while paused do not create a new RS
kubectl rollout undoRoll back to the previous or a specified revision--to-revision=N
kubectl create pdbCreate a PodDisruptionBudget--selector=app=api --min-available=2
kubectl get pdbCheck ALLOWED DISRUPTIONSWhen it is 0, drain is blocked
kubectl patch svcBlue/green switch-p '{"spec":{"selector":{...}}}'
kubectl patch deploy api -p '{"spec":{"minReadySeconds":5,"progressDeadlineSeconds":120,"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'
# Batch change: pause → change image + env var → resume (only one rollout is triggered)
kubectl rollout pause deploy/api
kubectl set image deploy/api podinfo=ghcr.io/stefanprodan/podinfo:6.17.0
kubectl set env deploy/api PODINFO_UI_MESSAGE="batched change"
kubectl rollout resume deploy/api
kubectl rollout status deploy/api --timeout=3m
# Create a stuck rollout: the image does not exist
kubectl set image deploy/api podinfo=ghcr.io/stefanprodan/podinfo:0.0.0-nope
kubectl rollout status deploy/api --timeout=150s; echo "exit=$?"
kubectl get deploy api -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}{"\n"}{end}'
kubectl rollout undo deploy/api
Waiting for deployment "api" rollout to finish: 1 out of 3 new replicas have been updated...
error: deployment "api" exceeded its progress deadline
exit=1
Available=True MinimumReplicasAvailable
Progressing=False ProgressDeadlineExceeded
deployment.apps/api rolled back

Because maxUnavailable: 0, the 3 old Pods stay online the whole time, so service is not affected. This is the value of "add first, then remove."

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api
  namespace: shop
spec:
  minAvailable: 2
  selector:
    matchLabels: { app: api }
  unhealthyPodEvictionPolicy: AlwaysAllow
kubectl apply -f pdb-api.yaml
kubectl get pdb api
NAME   MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
api    2               N/A               1                     5s

Lab 4: blue/green switch + canary + PDB blocking a drain (about 8 minutes)

Create the blue and green versions (use the UI message to tell the versions apart):
for c in blue green; do
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-$c
  namespace: shop
  labels: { tier: bg-demo }
spec:
  replicas: 2
  selector:
    matchLabels: { app: api-bg, version: $c }
  template:
    metadata:
      labels: { app: api-bg, version: $c }
    spec:
      containers:
      - name: podinfo
        image: ghcr.io/stefanprodan/podinfo:6.17.0
        env: [ { name: PODINFO_UI_MESSAGE, value: "$c" } ]
        ports: [ { containerPort: 9898 } ]
        readinessProbe: { httpGet: { path: /readyz, port: 9898 } }
EOF
done
kubectl get pod -l app=api-bg -L version
Create a Service pointing to blue, and verify it:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata: { name: api-bg, namespace: shop }
spec:
  selector: { app: api-bg, version: blue }
  ports: [ { port: 9898, targetPort: 9898 } ]
EOF
kubectl run t --rm -i --restart=Never --image=curlimages/curl -- sh -c \
 'for i in $(seq 6); do curl -s api-bg:9898 | grep -o "\"message\": \"[a-z]*\""; done'
"message": "blue"   (all 6 responses are blue)
Switch to green with one command, then switch back:
kubectl patch svc api-bg -p '{"spec":{"selector":{"app":"api-bg","version":"green"}}}'
kubectl get endpointslice -l kubernetes.io/service-name=api-bg -o wide
# Roll back:
kubectl patch svc api-bg -p '{"spec":{"selector":{"app":"api-bg","version":"blue"}}}'
Canary: remove version from the selector, and split traffic by replica ratio:
kubectl patch svc api-bg --type json -p '[{"op":"remove","path":"/spec/selector/version"}]'
kubectl scale deploy/api-blue --replicas=4; kubectl scale deploy/api-green --replicas=1
kubectl rollout status deploy/api-blue
kubectl run t --rm -i --restart=Never --image=curlimages/curl -- sh -c \
 'for i in $(seq 100); do curl -s api-bg:9898 | grep -o "\"message\": \"[a-z]*\""; done | sort | uniq -c'
     79 "message": "blue"
     21 "message": "green"
PDB blocks a drain: create a PDB with minAvailable=3 for the shop api (3 replicas), and observe the drain being rejected:
kubectl create pdb api-strict --selector=app=api --min-available=3
NODE=$(kubectl get pod -l app=api -o jsonpath='{.items[0].spec.nodeName}')
kubectl drain $NODE --ignore-daemonsets --delete-emptydir-data --timeout=30s
node/lab-worker cordoned
evicting pod shop/api-7c9d6f5b8-2lq9x
error when evicting pods/"api-7c9d6f5b8-2lq9x" -n "shop" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
…
error: unable to drain node "lab-worker" due to error: … global timeout reached: 30s
kubectl uncordon $NODE
kubectl delete pdb api-strict
kubectl apply -f pdb-api.yaml        # a valid PDB: minAvailable 2
Cleanup:
kubectl delete deploy -l tier=bg-demo; kubectl delete svc api-bg

Case 1: AKS node pool upgrade stuck for 1 hour

Problem: a single-replica service has a PDB with minAvailable: 1. ALLOWED DISRUPTIONS stays at 0, and the node drain keeps retrying. Approach: run critical services with at least 2 replicas plus anti-affinity (Module 8). Use maxUnavailable: 1 in the PDB to express "at most one disruption at a time." For unhealthy Pods, use unhealthyPodEvictionPolicy: AlwaysAllow. Limitation: AKS upgrades have drain timeouts and settings such as undrainableNodeBehavior. Follow the current Microsoft Learn documentation.

Case 2: blue/green plus smoke test for a payment service

Problem: the payment API must be able to roll back the whole release within 10 seconds. Approach: the pipeline deploys green, runs smoke tests through the internal Service api-preview (its selector points to green), switches the main Service selector, and keeps blue for 30 minutes before scaling it to 0. Limitation: database migrations must be backward-compatible (expand/contract pattern). Otherwise, switching back to blue will not help.

Case 3: insufficient capacity during a rolling release

Problem: the cluster is nearly full. The default maxSurge of 25% leaves the new Pods Pending, and the release stalls until ProgressDeadlineExceeded. Approach: on a full cluster, use maxSurge: 0, maxUnavailable: 1 (remove first, then add), or rely on cluster autoscaling. In CI, run rollout undo automatically when rollout status --timeout fails. Limitation: remove-first briefly reduces capacity, so you need HPA headroom.

Common errors and fixes

error: deployment "api" exceeded its progress deadline

Cause: the new Pods did not become Available within progressDeadlineSeconds. Possible causes: image pull failure, probe failure, Pending due to insufficient resources, or missing configuration.

kubectl rollout status deploy/api
kubectl get rs -l app=api
kubectl describe pod -l app=api | grep -A8 Events
kubectl rollout undo deploy/api
Cannot evict pod as it would violate the pod's disruption budget.

Cause: the PDB's disruptionsAllowed is 0 (not enough replicas, minAvailable is too high, or some Pods are already unhealthy).

kubectl get pdb -A
kubectl describe pdb api

Fix: first scale up the replicas or repair the unhealthy Pods, then adjust the PDB. Only in an emergency, and only after you accept the risk, use kubectl drain --disable-eviction (it bypasses the PDB and deletes Pods directly).

Some requests still reach the old version after the Service switch

Cause: existing long-lived connections (HTTP keep-alive, gRPC) are not closed when endpoints change, and clients or gateways keep connection pools.

Fix: have the old version shut down gracefully after the switch (close idle connections). Set MaxConnectionAge on gRPC clients, or switch at L7 through a Gateway (hour 3).

The Deployment "api" is invalid: spec.strategy.rollingUpdate.maxUnavailable: Invalid value: intstr.IntOrString{…}: may not be 0 when `maxSurge` is 0

Cause: when both are 0, the rollout cannot make progress. Fix: make sure at least one of them is greater than 0.

Command-line exercises
1. Create a PDB for api that allows at most 1 replica to be disrupted at a time.
kubectl create pdb api --selector=app=api --max-unavailable=1
2. In one rollout, change both the image and the resources, and have CI roll back automatically if it fails.
kubectl rollout pause deploy/api
kubectl set image deploy/api podinfo=ghcr.io/stefanprodan/podinfo:6.17.0
kubectl set resources deploy/api -c podinfo --limits=memory=256Mi
kubectl rollout resume deploy/api
kubectl rollout status deploy/api --timeout=5m || kubectl rollout undo deploy/api
Scenario analysis
replicas=4, maxSurge=0, maxUnavailable=50%, plus a PDB with minAvailable=3. Will the release be blocked by the PDB? What about a node drain?

The release is not blocked by the PDB. A rolling update is performed by the Deployment controller, which deletes old Pods directly without going through the Eviction API. It can take down 2 at once, so availability drops to 2, which conflicts with the PDB's intent. Set maxUnavailable to 1, or add surge. The drain is constrained by the PDB: only 1 replica can be evicted at a time.

Verified teaching videos

No verified video was found that specifically covers maxSurge calculation, native blue/green and canary implementation, and PDBs. You can refer to the Deployment sections of these verified comprehensive courses:

▶
Kubernetes Crash Course for Absolute Beginners [NEW] — TechWorld with Nana
English · quick review of the basic Deployment / Service relationship

Official documentation

Video storyboard script (about 90 seconds)

This lesson cannot generate a video or MP3 directly, so it provides a storyboard and a narration script.

Shot 1 · 0–25s
Visual: 10 Pod squares. 3 new blue Pods appear, and 2 gray old Pods disappear. A counter above reads "total ≤13, available ≥8."
Narration: maxSurge rounds up, and maxUnavailable rounds down. Ten replicas at 25% each means at most thirteen in total and at least eight available.
Shot 2 · 25–50s
Visual: the Service selector label flips from blue to green, and all the arrows turn at once.
Narration: a blue/green release only changes the Service selector, so both switching and rolling back take seconds.
Shot 3 · 50–70s
Visual: nine stable replicas plus one canary, with request balls flowing in by ratio.
Narration: native canary splits traffic by replica ratio. When you need precise weights, use the Gateway API from hour 3.
Shot 4 · 70–90s
Visual: the drain sends eviction requests, and the PDB shield returns 429.
Narration: a PodDisruptionBudget only blocks eviction requests. It protects the minimum number of available replicas during node maintenance.
Or score ≥ 70% on the quiz

Module 5 · StatefulSet

30:00 – 37:00 · Give each Pod an "ID card": a fixed name, fixed DNS, fixed disks, and ordered execution
7 minapps/v1 GA · PVC retention policy v1.32 GAmaxUnavailable Beta · Recreate 1.37 Alpha★★★★☆
Learning objectives
  • Explain the three StatefulSet guarantees (stable network identity, stable storage, and ordered deployment and updates), and compare them with Deployments.
  • Configure a headless Service, volumeClaimTemplates, podManagementPolicy, updateStrategy (partition / OnDelete), and persistentVolumeClaimRetentionPolicy.
  • Deploy a single-instance postgres:17 StatefulSet on kind, and verify that the data and DNS name stay the same after a Pod is recreated.
Prerequisites: named volumes and Postgres persistence from the Docker course; Module 3 of this hour (Secret). Priority: ★★★★☆

What: what a StatefulSet provides

GuaranteeImplementationExample (StatefulSet web, Service web, namespace shop)
Stable Pod namesOrdinals 0..N-1 (you can change the starting ordinal with .spec.ordinals.start, GA in v1.31)web-0, web-1, web-2; names stay the same after recreation
Stable DNSThe serviceName points to the headless Service (clusterIP: None), which creates A/AAAA records for each Podweb-0.web.shop.svc.cluster.local
Stable storagevolumeClaimTemplates creates a separate PVC for each ordinal. When a Pod is recreated, it rebinds to the same PVCdata-web-0, data-web-1
OrderedpodManagementPolicy: OrderedReady (default): Pods are created one at a time, from 0 to N-1, and the next one is created only after the previous one is Running and Ready. Scale-down happens in reverse, from N-1 to 0The primary web-0 starts first, and the replicas start after it

Why: why a Deployment is not enough

Deployment Pod names are random (api-7c9d6f5b8-2lq9x), and all replicas share the same volume reference from the template. If that references a RWO PVC, multiple replicas compete for the same disk. When a Pod is recreated, its IP and name both change, so cluster members (such as etcd, Kafka, or PostgreSQL primary/replica setups) cannot find each other through a stable identity.

How: key fields

  • podManagementPolicy: OrderedReady | Parallel (create or delete at the same time; this affects scaling only, not update order).
  • updateStrategy:
    • RollingUpdate (default): updates in reverse order, starting from the highest ordinal, one at a time. Each one must be Ready before the next one is updated. partition: K updates only the Pods with ordinal ≥ K, which gives you a natural batch or canary pattern. maxUnavailable (MaxUnavailableStatefulSet, Beta; disabled by default in v1.35.4–v1.36 due to a defect, and re-enabled by default in v1.37) allows several Pods to update at the same time.
    • OnDelete: the controller does not update Pods on its own. A Pod is recreated with the new template only when you delete it manually. Database operators often use this to control the order completely.
    • Recreate (Alpha in v1.37, feature gate StatefulSetRecreateStrategy): deletes all Pods first, then creates them from the new template. Use it when old and new versions cannot coexist. kind does not enable the Alpha gate by default, so this hour only introduces it.
  • persistentVolumeClaimRetentionPolicy (GA in v1.32): whenDeleted (when the StatefulSet is deleted) and whenScaled (when scaling down) each take Retain (default) or Delete. PVCs are kept by default to prevent accidental data loss.
  • minReadySeconds: same as for Deployments. How long a Pod must stay Ready before it counts as available.

When: when to use it

  • Good for: cluster software that needs a fixed identity and fixed disks (databases, message queues, ZooKeeper/etcd, Elasticsearch).
  • Production recommendation: for PostgreSQL and similar databases, prefer a managed service (Azure Database for PostgreSQL Flexible Server) or a mature operator (such as CloudNativePG). A StatefulSet only solves identity and disks. It does not handle failover, backups, or upgrades. This hour uses a single instance to demonstrate the principles. Hour 4 covers storage in depth.

Comparison with similar technologies

DeploymentStatefulSetOperator (such as CloudNativePG)
Pod nameRandomFixed ordinalDecided by the operator
StorageShared template volumeOne PVC per replicaOne PVC per instance + backup / WAL archiving
FailoverStateless, replace directlyOnly recreates a Pod with the same name in placeAutomatically elects a primary, switches over, and rebuilds replicas
Common misconceptions ① "Deleting a StatefulSet deletes the data." By default it uses whenDeleted: Retain, so the PVCs are kept. ② "A StatefulSet is a highly available database." It only guarantees identity. It does not do replication or leader election. ③ "When a node goes down, the StatefulSet immediately recreates web-0 somewhere else." It does not. To guarantee that one identity has at most one running instance, the old Pod stays in Terminating/Unknown while the node is unreachable. The controller will not create a new Pod with the same name until the node recovers or someone confirms it is down, for example by applying the out-of-service taint.

Architecture diagram: StatefulSet, headless Service, and PVCs

StatefulSet webreplicas 3 · serviceName web Service webclusterIP: None (headless)CoreDNS: one record per Pod web-0web-0.web.shop.svc… web-1web-1.web.shop.svc… web-2web-2.web.shop.svc… PVC data-web-0RWO 1Gi PVC data-web-1RWO 1Gi PVC data-web-2RWO 1Gi PV (dynamically provisioned)StorageClass standardrancher local-pathWaitForFirstConsumerNode-local directory→ PV bound to the node→ Pod can only return to that node
Figure 5-1: each ordinal gets a fixed name, a fixed DNS record, and a dedicated PVC. The kind local-path PV binds the Pod to a node

Flowchart: OrderedReady creation and partitioned updates

Create (OrderedReady) web-0 Ready web-1 Ready web-2 Ready Update (RollingUpdate partition=1, reverse order) web-2 → v2 web-1 → v2 web-0 stays on v1 (ordinal < 1) After verification: partition: 0→ web-0 updates, and the release is complete
Figure 5-2: partition lets you update the high-ordinal replicas first (usually the replicas), verify them, and then update web-0 (usually the primary)

Ordered creation, scaling, and partitioned updates

Choose a podManagementPolicy, then create, scale, or update. Each square is a Pod, and its PVC is shown below it. Watch the requests that the StatefulSet controller (the statefulset controller in kube-controller-manager) sends to the apiserver at each step.

podManagementPolicy: · partition
$ kubectl apply -f web-sts.yaml

Core commands

CommandPurposeKey parameters / notes
kubectl get sts,pod,pvc -l app=XView StatefulSet, Pods, and PVCs togetherPVC name = template name-StatefulSet name-ordinal
kubectl scale sts/X --replicas=NScale (in order)Scale-down keeps PVCs by default
kubectl patch sts X -pChange partition / strategy{"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}}
kubectl rollout status/history/undo sts/XStatefulSets also support rolloutBased on ControllerRevision
kubectl get controllerrevisionView the StatefulSet's revision history objectsSimilar to a Deployment's old RS
apiVersion: v1
kind: Service
metadata: { name: web, namespace: shop }
spec:
  clusterIP: None
  selector: { app: web }
  ports: [ { name: http, port: 80 } ]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: web, namespace: shop }
spec:
  serviceName: web
  replicas: 3
  podManagementPolicy: OrderedReady
  updateStrategy:
    type: RollingUpdate
    rollingUpdate: { partition: 0 }
  persistentVolumeClaimRetentionPolicy: { whenDeleted: Retain, whenScaled: Retain }
  selector: { matchLabels: { app: web } }
  template:
    metadata: { labels: { app: web } }
    spec:
      containers:
      - name: nginx
        image: nginx:alpine
        ports: [ { name: http, containerPort: 80 } ]
        volumeMounts: [ { name: data, mountPath: /usr/share/nginx/html } ]
  volumeClaimTemplates:
  - metadata: { name: data }
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: standard
      resources: { requests: { storage: 1Gi } }
kubectl apply -f web-sts.yaml
kubectl get pod -l app=web -w      # watch web-0 → web-1 → web-2 being created in order
kubectl get pvc -l app=web
kubectl run dns --rm -i --restart=Never --image=busybox:1.37 -- nslookup web-0.web.shop.svc.cluster.local
NAME    READY   STATUS              RESTARTS   AGE
web-0   0/1     ContainerCreating   0          2s
web-0   1/1     Running             0          6s
web-1   0/1     Pending             0          0s
web-1   1/1     Running             0          5s
web-2   …
NAME         STATUS   VOLUME          CAPACITY   ACCESS MODES   STORAGECLASS
data-web-0   Bound    pvc-3f0c…       1Gi        RWO            standard
…
Name:      web-0.web.shop.svc.cluster.local
Address:   10.244.2.14

Common mistakes: forgetting to create the headless Service, or misspelling serviceName. The Pods start, but they have no per-Pod DNS records. Production use: partitioned upgrades for database replicas, and OnDelete, so the DBA controls when each instance restarts.

Lab 5: deploy a postgres:17 StatefulSet and verify data persistence (about 7 minutes)

Confirm the StorageClass and Secret (db-cred comes from Module 3; if it does not exist, run the create secret command from Module 3 first):
kubectl get sc
kubectl get secret db-cred
NAME                 PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION
standard (default)   rancher.io/local-path   Delete          WaitForFirstConsumer   false
Deploy db:
apiVersion: v1
kind: Service
metadata: { name: db, namespace: shop, labels: { app: db } }
spec:
  clusterIP: None
  selector: { app: db }
  ports: [ { name: pg, port: 5432 } ]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: db, namespace: shop }
spec:
  serviceName: db
  replicas: 1
  selector: { matchLabels: { app: db } }
  template:
    metadata: { labels: { app: db } }
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: postgres
        image: postgres:17
        envFrom: [ { secretRef: { name: db-cred } } ]
        env: [ { name: PGDATA, value: /var/lib/postgresql/data/pgdata } ]
        ports: [ { name: pg, containerPort: 5432 } ]
        resources:
          requests: { cpu: 100m, memory: 256Mi }
          limits:   { memory: 512Mi }
        readinessProbe:
          exec: { command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""] }
          periodSeconds: 5
        livenessProbe:
          tcpSocket: { port: pg }
          periodSeconds: 10
          failureThreshold: 6
        volumeMounts: [ { name: data, mountPath: /var/lib/postgresql/data } ]
  volumeClaimTemplates:
  - metadata: { name: data }
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: standard
      resources: { requests: { storage: 2Gi } }
kubectl apply -f db.yaml
kubectl rollout status sts/db
kubectl get pod db-0 -o wide; kubectl get pvc data-db-0
Write data:
kubectl exec -i db-0 -- psql -U shop -d shop <<'SQL'
CREATE TABLE orders(id serial PRIMARY KEY, item text, created timestamptz DEFAULT now());
INSERT INTO orders(item) VALUES ('keyboard'),('mouse');
SELECT * FROM orders;
SQL
Delete the Pod, then verify that the name, DNS, and data are unchanged:
kubectl delete pod db-0
kubectl wait --for=condition=Ready pod/db-0 --timeout=120s
kubectl exec db-0 -- psql -U shop -d shop -c "SELECT count(*) FROM orders;"
kubectl run pgc --rm -i --restart=Never --image=postgres:17 --env=PGPASSWORD='S3cure!Pass' -- \
  psql -h db-0.db.shop.svc.cluster.local -U shop -d shop -c "SELECT item FROM orders;"
 count
-------
     2
   item
----------
 keyboard
 mouse
Try partition (using the web StatefulSet from earlier):
kubectl apply -f web-sts.yaml
kubectl patch sts web -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}}'
kubectl set image sts/web nginx=nginx:1.29-alpine
sleep 20; kubectl get pod -l app=web -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image
kubectl patch sts web -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":0}}}}'
kubectl rollout status sts/web
NAME    IMAGE
web-0   nginx:alpine
web-1   nginx:alpine
web-2   nginx:1.29-alpine
Cleanup: keep db, since Module 7 and the capstone lab use it. Delete web and its PVCs (Retain does not delete them automatically):
kubectl delete sts web; kubectl delete svc web; kubectl delete pvc -l app=web

Case 1: after scaling down and back up, old data comes back to life

Problem: Kafka was scaled from 5 to 3, then a few weeks later scaled back to 5. broker-3 and broker-4 mounted the old PVCs and rejoined the cluster with stale partition data. Approach: set the policy explicitly: whenScaled: Delete (scaling down deletes the data), or manually clean up the PVCs before scaling back up. Limitation: Delete is irreversible, so always pair it with backups.

Case 2: upgrade replicas first when upgrading a database minor version

Problem: a 3-instance PostgreSQL cluster (self-managed, not run by an operator) needs an image upgrade. Approach: partition: 1 updates db-2 and db-1 (the replicas) first. Watch the replication lag and errors, then perform a primary/replica switchover, and finally set partition: 0. Alternatively, use OnDelete and delete the Pods one by one by hand. Limitation: a major version upgrade (17→18) involves changes to the data directory format, so you cannot simply swap the image.

Case 3: node lost contact, leaving db-0 stuck in Terminating

Problem: a node lost power. db-0 is stuck in Terminating, and the StatefulSet does not create a new db-0. Approach: after you confirm the node is really powered off, add the node.kubernetes.io/out-of-service=nodeshutdown:NoExecute taint to the node (non-graceful node shutdown handling, GA in v1.28). This detaches the volumes and force-deletes the Pod, so it is recreated on another node. Limitation: if the node is actually still alive, this causes dual writes and can corrupt data. The cloud disk must be mountable on other nodes (kind local-path does not allow this).

Common errors and fixes

pod has unbound immediate PersistentVolumeClaims / 0/3 nodes are available: pod has unbound immediate PersistentVolumeClaims.

Cause: the PVC cannot bind. The StorageClass name is wrong, there is no default StorageClass, or the provisioner is failing.

kubectl get pvc; kubectl describe pvc data-db-0
kubectl get sc
kubectl -n local-path-storage logs deploy/local-path-provisioner --tail=30
0/3 nodes are available: 1 node(s) had volume node affinity conflict, …

Cause: the local-path PV (or a single-zone cloud disk) is bound to a particular node or zone, but the Pod is scheduled elsewhere. That node may be cordoned, resources may be insufficient, or affinity may conflict.

kubectl get pv $(kubectl get pvc data-db-0 -o jsonpath='{.spec.volumeName}') -o jsonpath='{.spec.nodeAffinity}'

Fix: uncordon the node or free up resources. In production, use cloud disks that can be mounted across nodes, and combine them with topology awareness (hour 4).

web-1 stays Pending and is never created; web-0 is in CrashLoopBackOff

Cause: under OrderedReady, if the previous ordinal is not Ready, the later ordinals are not created.

Fix: first repair web-0 (kubectl logs web-0 --previous). If the app does not depend on ordering, switch to podManagementPolicy: Parallel. This field cannot be changed after creation, so you must delete and recreate the StatefulSet. You can use --cascade=orphan to keep the Pods.

Forbidden: updates to statefulset spec for fields other than 'replicas', 'ordinals', 'template', 'updateStrategy', 'revisionHistoryLimit', 'persistentVolumeClaimRetentionPolicy' and 'minReadySeconds' are forbidden

Cause: volumeClaimTemplates, serviceName, podManagementPolicy, selector, and similar fields cannot be changed after creation.

Fix: kubectl delete sts db --cascade=orphan keeps the Pods and PVCs. Then recreate the StatefulSet with the new definition so it adopts them.

initdb: error: directory "/var/lib/postgresql/data" exists but is not empty (contains lost+found)

Cause: after formatting, a block storage volume has lost+found in its root directory. Fix: set PGDATA to a subdirectory under the mount point. This lab sets it to .../data/pgdata.

Command-line exercises
1. Update only the Pods with ordinal ≥3 in the StatefulSet web to the new image.
kubectl patch sts web -p '{"spec":{"updateStrategy":{"type":"RollingUpdate","rollingUpdate":{"partition":3}}}}'
kubectl set image sts/web nginx=nginx:1.29-alpine
2. Delete the StatefulSet, but keep its Pods and PVCs.
kubectl delete sts web --cascade=orphan
Scenario analysis
On kind, you drain the node where db-0 runs, and db-0 stays Pending. Explain why, and describe what would be different on AKS.

The kind local-path PV is a node-local directory, and the PV carries a nodeAffinity that points to the original node. After that node is cordoned, the Pod cannot return there, and the other nodes do not satisfy the volume affinity, so the Pod stays Pending (volume node affinity conflict). On AKS, use Azure Disk CSI (ZRS, or LRS within the same zone). The disk can be detached and attached to another node in the same zone (ZRS can span zones), so the Pod can be recreated elsewhere. You still need to consider the zone topology, and a single-instance database is unavailable during the move. Production databases should use replication or a managed service.

Verified teaching videos

▶
Kubernetes StatefulSet simply explained | Deployment vs StatefulSet — TechWorld with Nana
2020 · English · the difference between Deployments and StatefulSets, and why databases need a fixed identity (does not cover partition, the PVC retention policy, or other newer fields)

Official documentation

Video storyboard script (about 80 seconds)

This lesson cannot generate a video or MP3 directly, so it provides a storyboard and a narration script.

Shot 1 · 0–20s
Visual: Deployment Pod names are random strings, while StatefulSet Pods wear number tags 0, 1, and 2 on their chests.
Narration: a StatefulSet gives each Pod a fixed ordinal. Its name stays the same after it is recreated.
Shot 2 · 20–45s
Visual: each Pod is connected to its own disk, data-web-0 and data-web-1. After web-1 is deleted, the new web-1 reattaches the original disk.
Narration: volumeClaimTemplates creates a separate PVC for each ordinal. When a Pod is recreated, it mounts the same disk again.
Shot 3 · 45–80s
Visual: 0, 1, and 2 light up in order. During an update, 2 changes color first, then 1, while 0 waits. The partition slider is dragged from 1 to 0.
Narration: by default, Pods are created in order and updated in reverse order. The partition lets you update the high-ordinal replicas first, then update the primary after verification.
Or score ≥ 70% on the quiz

Module 6 · DaemonSet

37:00 – 42:00 · "Exactly one per node": the workloads behind logging, monitoring, networking, and storage plugins
5 minapps/v1 GA · maxSurge GA★★★☆☆
Learning objectives
  • Explain how DaemonSets are scheduled. The controller creates a Pod for each eligible node, and binding is handed to the default scheduler through nodeAffinity.
  • Use nodeSelector / tolerations to control which nodes it runs on (including control-plane nodes), and configure maxUnavailable / maxSurge for RollingUpdate.
  • Recognize the system DaemonSets in a cluster (kube-proxy, kindnet, CSI node plugins, and so on).
Prerequisites: Module 1 (resources), and the taint concept from Module 8 (you can read about the principle first). Priority: ★★★☆☆ (★★★★★ for platform engineers)

What: what a DaemonSet is

A DaemonSet ensures that all (or selected) nodes each run one Pod replica. When a node joins the cluster, the Pod is added automatically. When a node is removed, its Pod is reclaimed. It has no replicas field. The replica count equals the number of eligible nodes.

Why: typical uses

CategoryExamplesWhy one per node is required
Networkingkube-proxy, kindnet, Calico/Cilium agents, Azure CNIMust program nftables/iptables/eBPF and routes on every node
StorageCSI node plugins (such as the Azure Disk/File CSI node)Mounting volumes must run on the node where the Pod is
LoggingFluent Bit, Azure Monitor Agent (ama-logs)Read the node's /var/log/pods
Monitoringnode-exporter, Datadog agentCollect node-level metrics
SecurityFalco, Defender for Containers sensorMonitor kernel events on the node

How: scheduling mechanism

  • The DaemonSet controller (in kube-controller-manager) creates one Pod for each target node, and injects a nodeAffinity into the Pod (matchFields: metadata.name In [node name]). Then the default scheduler completes the binding. That means resource requests, taints, and other scheduling rules are respected, and preemption works too.
  • The controller automatically adds a set of tolerations to DaemonSet Pods: node.kubernetes.io/not-ready, unreachable (NoExecute, with no tolerationSeconds), disk-pressure, memory-pressure, pid-pressure, unschedulable (NoSchedule), and, when hostNetwork is used, network-unavailable. So cordon does not stop DaemonSet Pods, and kubectl drain needs --ignore-daemonsets.
  • It does not automatically tolerate the control-plane taint node-role.kubernetes.io/control-plane:NoSchedule. To run on control-plane nodes (for example, a log agent), you must add the toleration explicitly.
  • updateStrategy: RollingUpdate (default, maxUnavailable: 1; maxSurge lets a new Pod start before the old one is deleted, and the two cannot both be 0), or OnDelete. A DaemonSet that uses hostPort cannot use maxSurge, because of port conflicts.

When: when to use it and when not to

  • Use it for: agents that genuinely need node-local access (files, devices, the network stack).
  • Do not use it for: ordinary apps that just need to be "spread across every node." Use a Deployment with topologySpreadConstraints (Module 8) instead, so the replica count is decoupled from the node count.
  • DaemonSet Pods often need hostPath, hostNetwork, or privileges, so they are a key focus for security audits (hour 5, Pod Security). Always set requests and a PriorityClass. system-node-critical is only for truly critical components.

Comparison with similar technologies

DaemonSetStatic Podsystemd service / VM extension
Managed byAPI declarative, rolling updateskubelet reads files from a node directory (mirror Pods are read-only)Node image or configuration management
Typical useNode agentskubeadm control-plane componentskubelet, containerd itself
Common misconceptions ① "A DaemonSet always runs on every node." Nodes with taints, such as control-plane nodes, do not get one by default. ② "Once a node is cordoned, its DaemonSet Pods stop coming." They keep coming, because they automatically tolerate unschedulable. ③ "DaemonSets are not affected by resource limits." When a node runs short of resources, DaemonSet Pods also stay Pending. They can preempt ordinary Pods through priority.

Architecture diagram: DaemonSet and nodes

DaemonSet node-agenttolerations: control-plane lab-control-planetaint control-plane:NoSchedule node-agent-xxxxx(appears only with a matching toleration) lab-worker node-agent-yyyyy lab-worker2 node-agent-zzzzz
Figure 6-1: one Pod per node. Control-plane nodes need an explicit toleration for their taint

Flowchart: when a new node joins

kubelet registers the nodePOST /api/v1/nodes DS controller watches NodeMatches nodeSelector/taints Create PodInject nodeAffinity with the node name Scheduler bindsOnly one candidate node kubelet startsAgent ready
Figure 6-2: DaemonSet Pods are still bound by the default scheduler (since v1.12), so resource and taint rules are respected

Interactive: how the DaemonSet controller reacts when nodes change

Change tolerations, add nodes, taint a node, or cordon one. Then observe which Pods the controller creates or deletes, and the corresponding API calls.

$ kubectl apply -f node-agent.yaml

Core commands

CommandPurposeKey parameters
kubectl get ds -AView all DaemonSets (DESIRED/CURRENT/READY/UP-TO-DATE)-o wide shows images and selectors
kubectl rollout status ds/XWait for the rollout to complete-n kube-system
kubectl get pod -l app=X -o wideConfirm that every node has oneNODE column
kubectl describe node | grep TaintsView node taintsDecide whether a toleration is needed
kubectl get ds -A
NAMESPACE     NAME         DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR            AGE
kube-system   kindnet      3         3         3       3            3           <none>                   2d
kube-system   kube-proxy   3         3         3       3            3           kubernetes.io/os=linux   2d
kubectl -n kube-system get ds kube-proxy -o jsonpath='{.spec.template.spec.tolerations}{"\n"}{.spec.updateStrategy}{"\n"}'
[{"key":"CriticalAddonsOnly","operator":"Exists"},{"operator":"Exists"}]
{"rollingUpdate":{"maxSurge":0,"maxUnavailable":1},"type":"RollingUpdate"}

kube-proxy uses operator: Exists (with no key) to tolerate all taints, because it must run on every node. Common mistake: business DaemonSets copy this pattern and end up running on dedicated nodes (GPU or system pools). Production use: for log agents, tolerate only specific taints.

apiVersion: apps/v1
kind: DaemonSet
metadata: { name: node-agent, namespace: shop }
spec:
  selector: { matchLabels: { app: node-agent } }
  updateStrategy:
    type: RollingUpdate
    rollingUpdate: { maxUnavailable: 0, maxSurge: 1 }
  template:
    metadata: { labels: { app: node-agent } }
    spec:
      tolerations:
      - key: node-role.kubernetes.io/control-plane
        operator: Exists
        effect: NoSchedule
      containers:
      - name: agent
        image: busybox:1.37
        command: ["sh", "-c", "while true; do echo \"$(date -Iseconds) node=$NODE_NAME pods=$(ls /host/log/pods | wc -l)\"; sleep 30; done"]
        env:
        - name: NODE_NAME
          valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
        resources:
          requests: { cpu: 10m, memory: 16Mi }
          limits:   { memory: 32Mi }
        volumeMounts: [ { name: varlog, mountPath: /host/log, readOnly: true } ]
      volumes:
      - name: varlog
        hostPath: { path: /var/log, type: Directory }

Lab 6: deploy a node agent and let it cover the control plane (about 4 minutes)

First, without tolerations: remove the tolerations section from the YAML above, save it as node-agent.yaml, and apply it:
kubectl apply -f node-agent.yaml
kubectl get ds node-agent; kubectl get pod -l app=node-agent -o wide
NAME         DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
node-agent   2         2         2       2            2           <none>          10s

DESIRED=2: the control plane is excluded because of its taint.

Add the toleration (full YAML), then apply again:
kubectl apply -f node-agent.yaml   # tolerations section restored
kubectl rollout status ds/node-agent
kubectl get pod -l app=node-agent -o wide
kubectl logs -l app=node-agent --prefix --tail=1
node-agent   3   3   3   3   3 …
[pod/node-agent-8xk2p/agent] 2026-11-15T09:12:30+00:00 node=lab-control-plane pods=12
[pod/node-agent-q7rtd/agent] 2026-11-15T09:12:31+00:00 node=lab-worker pods=9
[pod/node-agent-z2mfn/agent] 2026-11-15T09:12:31+00:00 node=lab-worker2 pods=8
Verify that cordon does not affect the DaemonSet:
kubectl cordon lab-worker
kubectl delete pod -l app=node-agent --field-selector spec.nodeName=lab-worker
sleep 5; kubectl get pod -l app=node-agent -o wide --field-selector spec.nodeName=lab-worker
kubectl uncordon lab-worker

The deleted Pod is recreated immediately on the cordoned lab-worker, because the controller automatically adds an node.kubernetes.io/unschedulable toleration.

Cleanup: keep node-agent. The drain exercise in the capstone lab uses it, to verify --ignore-daemonsets.

Case 1: a log agent OOM causes node log loss

Problem: the Fluent Bit DaemonSet has a 64Mi memory limit. During peak log volume it was OOMKilled, and logs were lost in the meantime. Approach: set memory based on load tests of Pod density per node, enable filesystem buffering, and give the DaemonSet a higher PriorityClass so it is not evicted first under node pressure. Limitation: DaemonSet resources multiply by the number of nodes, so the cost is significant in large clusters.

Case 2: a dedicated agent on a GPU node pool

Problem: the NVIDIA device plugin only needs to run on GPU nodes. Approach: use nodeSelector: {accelerator: nvidia}, plus a toleration for the sku=gpu:NoSchedule taint on the GPU node pool. Limitation: AKS can configure this automatically through node pool labels and taints. Follow the AKS documentation for the details.

Case 3: a CNI upgrade causes cluster-wide network jitter

Problem: someone manually changed the CNI DaemonSet image and set maxUnavailable to 100%, so the CNI agent restarted on all nodes at once. Approach: keep maxUnavailable: 1 (or a small percentage), validate on one node pool first, and on managed clusters let the platform (AKS managed CNI) handle the upgrade. Limitation: DaemonSet rollouts have no PDB protection, so you must control the speed through the strategy parameters.

Common errors and fixes

DESIRED is lower than the node count (some nodes have no DaemonSet Pod)

Cause: the node has taints that the Pod does not tolerate, or it does not match the nodeSelector/nodeAffinity.

kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints
kubectl get ds X -o jsonpath='{.spec.template.spec.nodeSelector} {.spec.template.spec.tolerations}'
error: unable to drain node "lab-worker" due to error: cannot delete DaemonSet-managed Pods (use --ignore-daemonsets to ignore)

Cause: DaemonSet Pods are recreated immediately even when deleted, and drain refuses them by default. Fix: add --ignore-daemonsets. They keep running on the node.

DaemonSet Pod Pending: 0/3 nodes are available: 1 Insufficient cpu …

Cause: the target node's resources are full. A DaemonSet Pod can only go to its designated node, so it has no alternative.

Fix: give the DaemonSet a higher PriorityClass so it can preempt ordinary Pods, lower its requests, or reserve resources on the node.

UP-TO-DATE stays below DESIRED for a long time (the update is stuck)

Cause: new Pods are not Ready (image, probes, or hostPort conflicts), so RollingUpdate stops in place according to maxUnavailable.

kubectl rollout status ds/X
kubectl get pod -l app=X -o wide | grep -v Running
Command-line exercises
1. Find the nodes that have no node-agent Pod.
comm -23 <(kubectl get nodes -o name | sed 's#node/##' | sort) \
  <(kubectl get pod -l app=node-agent -o jsonpath='{range .items[*]}{.spec.nodeName}{"\n"}{end}' | sort)
2. Change the node-agent update strategy to OnDelete.
kubectl patch ds node-agent --type merge -p '{"spec":{"updateStrategy":{"type":"OnDelete","rollingUpdate":null}}}'
Scenario analysis
The team wants the web service to run "one replica per node for the best distribution," and plans to use a DaemonSet. What is your assessment?

Not recommended. A DaemonSet ties the replica count to the node count. Adding nodes adds replicas, and removing nodes removes them. You cannot scale them independently, you cannot use an HPA, and rolling updates have no PDB protection. Use a Deployment with topologySpreadConstraints (maxSkew 1, by hostname or zone) or podAntiAffinity instead, so the workload determines the replica count.

Verified teaching videos

No verified video that specifically covers DaemonSets (with a matching title, author, and video ID) was found. You can refer to these verified comprehensive courses:

▶
Kubernetes Explained in 100 Seconds — Fireship
English · an overview review of about 2 minutes on the concept

Official documentation

Video storyboard script (about 60 seconds)

This lesson cannot generate a video or MP3 directly, so it provides a storyboard and a narration script.

Shot 1 · 0–20s
Visual: three nodes, and an identical agent icon drops onto each one.
Narration: a DaemonSet guarantees exactly one Pod per node. Typical examples are kube-proxy, the CNI, and log agents.
Shot 2 · 20–40s
Visual: a new node slides in, and the agent icon drops onto it automatically. A control-plane node has a lock on it, and the icon drops only after a toleration key is applied.
Narration: a new node gets the Pod automatically. Nodes with taints need an explicit toleration.
Shot 3 · 40–60s
Visual: a node gets a cordon seal, but the agent Pod still lands on it.
Narration: a DaemonSet automatically tolerates the unschedulable mark, so drain needs the ignore-daemonsets flag.
Or score ≥ 70% on the quiz

Module 7 · Job and CronJob

42:00 – 49:00 · Tasks that run to completion and exit: parallelism, retries, failure policies, and scheduled triggers
7 minbatch/v1 GApodFailurePolicy 1.31 · successPolicy / backoffLimitPerIndex 1.33 GA★★★★☆
Learning objectives
  • Configure completions, parallelism, backoffLimit, activeDeadlineSeconds, and ttlSecondsAfterFinished, and predict when a Job will succeed or fail.
  • Understand what Indexed Jobs, podFailurePolicy, successPolicy, and backoffLimitPerIndex are for, and the GA version of each.
  • Write a CronJob with timeZone, concurrencyPolicy, and startingDeadlineSeconds, and implement a Postgres backup. Trigger it manually with kubectl create job --from=cronjob/.
Prerequisites: Module 5 (the db StatefulSet) and Module 3 (Secret). Priority: ★★★★☆

What: Job and CronJob

A Job creates one or more Pods and retries them until the specified number of Pods finish successfully (exit code 0). A Pod's restartPolicy can only be OnFailure (restart the container inside the same Pod) or Never (on failure, create a new Pod and keep the failed one for debugging). A CronJob creates Jobs on a schedule defined by a cron expression.

FieldDefaultMeaning
completions1How many successful Pods are needed
parallelism1Maximum number of Pods running at the same time (0 is equivalent to pausing; you can also use suspend: true)
backoffLimit6Maximum number of retries after a failure. Retry intervals use exponential backoff (10s, 20s, 40s, …, capped at 6 minutes)
activeDeadlineSecondsNoneMaximum total runtime for the Job. After the timeout, all Pods are terminated, with reason: DeadlineExceeded (takes precedence over backoffLimit)
ttlSecondsAfterFinishedNoneAfter the Job finishes (success or failure), the TTL controller automatically deletes the Job and its Pods after this many seconds
completionModeNonIndexedIndexed: each Pod gets an index 0..completions-1 (annotation and environment variable JOB_COMPLETION_INDEX, hostname $(job-name)-$(index)), GA in v1.24

Advanced failure/success policies (all GA)

  • podFailurePolicy (GA in v1.31, requires restartPolicy: Never): decides the action by exit code or Pod condition. FailJob fails immediately, without wasting retries. Ignore does not count toward backoffLimit, for example a DisruptionTarget condition from being evicted by a node drain. Count is the default and counts the failure. FailIndex is used with backoffLimitPerIndex.
  • backoffLimitPerIndex (v1.33 GA, Indexed Job): each index counts its retries on its own, so one failed index does not stop the others. maxFailedIndexes sets how many indexes are allowed to fail.
  • successPolicy (v1.33 GA, Indexed Job): once the condition is met, the whole Job is marked successful (for example, when leader index 0 succeeds, or when any N indexes succeed), and the remaining Pods are terminated. This suits distributed training and "first answer wins" tasks.
  • podReplacementPolicy (v1.34 GA): Failed means replacement Pods are created only after the old Pods have fully terminated, so two replicas never run at the same time.

CronJob key fields

FieldDescription
scheduleStandard 5-field cron: minute, hour, day, month, weekday. Macros such as @hourly and @daily are also supported.
timeZoneIANA time zone name, such as America/Toronto or Asia/Shanghai (v1.27 GA). If not set, the local time zone of kube-controller-manager is used (usually UTC). CRON_TZ= and TZ= are not officially supported in the schedule.
concurrencyPolicyAllow (default, runs may overlap), Forbid (skip this run if the previous one has not finished), Replace (cancel the previous run and start this one)
startingDeadlineSecondsHow many seconds after a missed schedule time a run can still start late. After that, it counts as missed. If more than 100 schedules are missed while the controller is down, it reports an error and stops catching up.
successfulJobsHistoryLimit / failedJobsHistoryLimitNumber of historical Jobs to keep. Default 3 / 1.
suspendPauses future schedules (Jobs that are already running are not affected)

Why / When

  • Job: database migrations, batch data processing, report generation, one-off repair scripts. Indexed Job: splits a large task into shards that run in parallel (for example, 100 shards with parallelism 10).
  • CronJob: backups, cleanup, scheduled sync, certificate checks. Note that CronJob guarantees at-least-once scheduling, so tasks must be idempotent (in rare cases, a Job may be created twice or a run may be missed).
  • Not suitable for: long-running services (use a Deployment) or workflows with complex DAG dependencies (use Argo Workflows, Azure Data Factory, and similar tools).

Comparison with similar technologies

K8s Job/CronJobLinux cron / systemd timerAzure Container Apps Jobs / Functions timer triggers
Failure retriesbackoffLimit, podFailurePolicyWrite it yourselfBuilt-in retries
Parallelismparallelism, IndexedNoneParallel replicas
Where it runsAny node in the cluster (subject to scheduling constraints)Single machineManaged
Common misconceptions ① "With restartPolicy: OnFailure, failed Pods are kept for debugging." No. The container restarts inside the same Pod, so only the logs from the last run remain (--previous). To keep the failed state for debugging, use Never. ② "Jobs are cleaned up automatically after they finish." Not by default. You must set ttlSecondsAfterFinished (CronJobs rely on the history limit). ③ "CronJobs use Beijing time or local time by default." The default is the controller's time zone, usually UTC.

Architecture diagram: CronJob → Job → Pod

CronJob db-backupschedule: "0 2 * * *"timeZone: America/Toronto cronjob controllerChecks every 10 secondsDecides based on concurrencyPolicy Job db-backup-29384520completions 1 · backoffLimit 2activeDeadlineSeconds 600 create job controllerCreates Pods according to parallelismCounts succeeded / failed Pod #1 Failed (exit 1)restartPolicy Never → keep the failed state Pod #2 Succeeded (exit 0)Recreated after a 10s backoff Job Complete → TTL controllerDeleted after ttlSecondsAfterFinished
Figure 7-1: CronJob only creates Jobs on schedule. Retries and completion are handled by the Job controller.

Flowchart: the order in which the Job controller decides what to do when a Pod fails

Pod Failedexit 42 podFailurePolicy rulesMatched in order, first match wins FailJob → Job Failed (PodFailurePolicy) Ignore → not counted, Pod recreated Count, or no match → failed++ failed > backoffLimit ?Yes: BackoffLimitExceeded. No: recreate after backoff.
Figure 7-2: podFailurePolicy fails non-retriable errors immediately, and lets infrastructure-caused interruptions skip the retry count.

Job parallelism and retry simulator

Set the parameters, then click "Run." Each Pod has a chance of failing (simulating exit 1). Watch how the job controller creates Pods to match parallelism, and how it decides on failure based on backoffLimit.

completions parallelism backoffLimit Failure probability %
$ kubectl apply -f job.yaml

Core commands

CommandPurposeKey parameters
kubectl create job NAME --image=IMG -- CMDQuickly create a JobGenerate a template with --dry-run=client -o yaml
kubectl create cronjob NAME --schedule="*/5 * * * *"Quickly create a CronJob--image, -- CMD
kubectl create job X --from=cronjob/YTrigger a CronJob manually, right nowFor testing and catch-up runs
kubectl wait --for=condition=complete job/XWait for completion (common in CI)--timeout=10m; use condition=failed to wait for failure
kubectl get jobs,cronjobsCheck status (COMPLETIONS, LAST SCHEDULE)-w
kubectl patch cronjob X -p '{"spec":{"suspend":true}}'Pause schedulingMaintenance window
apiVersion: batch/v1
kind: Job
metadata: { name: shard, namespace: shop }
spec:
  completionMode: Indexed
  completions: 5
  parallelism: 2
  backoffLimitPerIndex: 1
  maxFailedIndexes: 1
  ttlSecondsAfterFinished: 600
  podFailurePolicy:
    rules:
    - action: FailJob
      onExitCodes: { containerName: worker, operator: In, values: [42] }
    - action: Ignore
      onPodConditions: [ { type: DisruptionTarget } ]
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: worker
        image: busybox:1.37
        command: ["sh", "-c", "echo processing shard $JOB_COMPLETION_INDEX; sleep 3"]
kubectl apply -f indexed-job.yaml
kubectl wait --for=condition=complete job/shard --timeout=2m
kubectl get pod -l job-name=shard -o custom-columns=NAME:.metadata.name,INDEX:.metadata.annotations.batch\\.kubernetes\\.io/job-completion-index,STATUS:.status.phase
kubectl logs -l job-name=shard --prefix
job.batch/shard condition met
NAME            INDEX   STATUS
shard-0-x7k2p   0       Succeeded
shard-1-9fq4m   1       Succeeded
…
[pod/shard-3-…/worker] processing shard 3

How to verify: kubectl get job shard -o jsonpath='{.status.completedIndexes}' shows 0-4. Common error: using podFailurePolicy with restartPolicy: OnFailure is rejected by the API. Production use: parallel data export by shard, batch image processing.

Lab 7: postgres backup CronJob (about 6 minutes)

Confirm db-0 is running (Module 5): kubectl get pod db-0.
Create the CronJob: backups are written to an emptyDir (demo only; the files disappear when the Pod ends; in hour 4 this changes to a PVC or object storage).
apiVersion: batch/v1
kind: CronJob
metadata: { name: db-backup, namespace: shop }
spec:
  schedule: "*/5 * * * *"
  timeZone: "America/Toronto"
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 120
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 2
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 600
      ttlSecondsAfterFinished: 3600
      template:
        spec:
          restartPolicy: Never
          containers:
          - name: pg-dump
            image: postgres:17
            env:
            - { name: PGHOST, value: db-0.db.shop.svc.cluster.local }
            - name: PGUSER
              valueFrom: { secretKeyRef: { name: db-cred, key: POSTGRES_USER } }
            - name: PGPASSWORD
              valueFrom: { secretKeyRef: { name: db-cred, key: POSTGRES_PASSWORD } }
            - name: PGDATABASE
              valueFrom: { secretKeyRef: { name: db-cred, key: POSTGRES_DB } }
            command: ["bash", "-c"]
            args:
            - |
              set -euo pipefail
              F=/backup/shop-$(date +%Y%m%d-%H%M%S).sql.gz
              pg_dump --no-owner | gzip > "$F"
              ls -lh /backup
              gunzip -c "$F" | grep -c "INSERT\|COPY" || true
              echo "backup ok: $F"
            resources:
              requests: { cpu: 50m, memory: 64Mi }
              limits:   { memory: 256Mi }
            volumeMounts: [ { name: backup, mountPath: /backup } ]
          volumes:
          - name: backup
            emptyDir: { sizeLimit: 1Gi }
kubectl apply -f db-backup.yaml
kubectl get cronjob db-backup
NAME        SCHEDULE      TIMEZONE          SUSPEND   ACTIVE   LAST SCHEDULE   AGE
db-backup   */5 * * * *   America/Toronto   False     0        <none>          5s
Don't wait 5 minutes. Trigger one run manually now:
kubectl create job db-backup-manual --from=cronjob/db-backup
kubectl wait --for=condition=complete job/db-backup-manual --timeout=2m
kubectl logs job/db-backup-manual
total 4K
-rw-r--r--    1 root     root         812 Nov 15 09:40 shop-20261115-094012.sql.gz
1
backup ok: /backup/shop-20261115-094012.sql.gz
Cause a failure, and watch the retries and backoffLimit:
kubectl create job bad-backup --image=postgres:17 -- sh -c 'pg_dump -h no-such-host -U x x'
kubectl get pod -l job-name=bad-backup -w      # default backoffLimit is 6, so you will see several failed Pods; press Ctrl+C
kubectl describe job bad-backup | grep -A3 Conditions
kubectl delete job bad-backup
Wait for automatic scheduling and review the history (optional, about 5 minutes):
kubectl get jobs --sort-by=.metadata.creationTimestamp
kubectl get cronjob db-backup -o jsonpath='{.status.lastScheduleTime} {.status.lastSuccessfulTime}{"\n"}'
Cleanup: kubectl delete job db-backup-manual. Keep the CronJob for the capstone lab (if you don't need it, run kubectl patch cronjob db-backup -p '{"spec":{"suspend":true}}').

Case 1: database migration Job as a release gate

Problem: the app runs migrations at startup, and when several replicas migrate at once, they conflict on locks. Approach: in CI, run the migration Job first (backoffLimit: 0, activeDeadlineSeconds: 600), and update the Deployment only after kubectl wait --for=condition=complete succeeds. Helm can use a pre-upgrade hook (hour 6). Limitation: migrations must be backward compatible, so the old version keeps working if the release fails.

Case 2: node upgrade wastes a batch job's retries

Problem: during a nightly ETL Job, an AKS node upgrade evicts its Pod 3 times, and the Job fails because of backoffLimit. Approach: in podFailurePolicy, use Ignore for the DisruptionTarget condition, and FailJob for exit code 42 (invalid input data), so the Job stops retrying pointlessly. Limitation: requires restartPolicy: Never.

Case 3: overlapping backups overwhelm the database

Problem: as the data grows, backups take over 1 hour, and @hourly with the default Allow causes several pg_dump processes to run at the same time. Approach: concurrencyPolicy: Forbid, activeDeadlineSeconds, and run backups on a replica; alert on lastSuccessfulTime. Limitation: Forbid skips the current schedule, so you need an alert to catch consecutive skips.

Common errors and fixes

Job has reached the specified backoff limit (reason: BackoffLimitExceeded)

Cause: the number of failures exceeded backoffLimit.

kubectl describe job X
kubectl get pod -l job-name=X
kubectl logs -l job-name=X --prefix --tail=20

Fix: fix the command or dependencies based on the failed Pods' logs. For non-retriable errors, use podFailurePolicy with FailJob.

Job was active longer than specified deadline (reason: DeadlineExceeded)

Cause: activeDeadlineSeconds was exceeded, so all running Pods were terminated. Fix: optimize the task, increase parallelism, or extend the deadline.

Cannot determine if job needs to be started: too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew.

Cause: the CronJob controller was down, or the CronJob was paused for a long time and then resumed, so more than 100 schedules were missed.

Fix: set startingDeadlineSeconds (for example, 200). The controller then counts only the missed schedules within that window.

CronJob did not run at the expected time (off by several hours)

Cause: timeZone was not set, so the schedule is interpreted in the controller's time zone (usually UTC).

kubectl get cronjob X -o jsonpath='{.spec.schedule} {.spec.timeZone}{"\n"}'

Fix: set an IANA name, such as timeZone: "America/Toronto".

spec.template.spec.restartPolicy: Unsupported value: "Always"

Cause: Job only allows Never or OnFailure. Fix: change restartPolicy (it must be Never when you use podFailurePolicy).

Command-line exercises
1. Trigger the CronJob db-backup manually now, and wait for it to finish.
J=db-backup-manual-$(date +%s)
kubectl create job $J --from=cronjob/db-backup
kubectl wait --for=condition=complete job/$J --timeout=5m
2. Generate a CronJob YAML template that runs every day at 2 a.m. (Toronto time).
kubectl create cronjob nightly --image=busybox:1.37 --schedule="0 2 * * *" --dry-run=client -o yaml -- date \
 | sed '/^  schedule:/a\  timeZone: America/Toronto'
Scenario analysis
A Job processes 1,000 files. Each file is independent. A few files are malformed (the program exits with code 42). You want bad files not to affect the others, but the whole Job should fail if more than 10 files are bad. How would you design it?

Use an Indexed Job (completions 1000, each index processes its matching file, parallelism set according to resources), with backoffLimitPerIndex: 1 (each file is retried at most once) and maxFailedIndexes: 10. In podFailurePolicy, use FailIndex for exit code 42 (marks that index as failed immediately, with no retry) and Ignore for DisruptionTarget. Use restartPolicy: Never, ttlSecondsAfterFinished for automatic cleanup, and status.failedIndexes to record the indexes of the bad files.

Verified video lessons

No verified video was found that specifically covers the new Job/CronJob failure policies. To review the basics of these objects, see the verified TechWorld with Nana 4-hour full course.

Official documentation

Video storyboard script (about 80 seconds)

This lesson file cannot generate a video or MP3 directly, so a storyboard and an English voice narration script are provided.

Shot 1 · 0–20s
Visual: the clock strikes two, a CronJob outputs a Job card, and the Job creates a Pod.
Narration: The CronJob creates the Job on schedule, and the Job runs the Pod until it succeeds.
Shot 2 · 20–50s
Visual: six task cells fill in two at a time in parallel. One turns red, then turns green after a short delay when it retries.
Narration: completions is the number of successes needed, parallelism is how many run at once, and failures are retried with exponential backoff until backoffLimit is reached.
Shot 3 · 50–80s
Visual: a Pod with exit code 42 turns the Job red immediately. An evicted Pod shows "Ignored."
Narration: podFailurePolicy separates retriable and non-retriable errors. Interruptions caused by node maintenance no longer use up retries.
Or score ≥ 70% in the quiz

Module 8 · Scheduling: affinity · taints · topology spread

49:00 – 60:00 · Learn how kube-scheduler's Filter and Score work, place replicas where you want them, and read why a Pod is Pending within 10 seconds.
11 mintopologySpreadConstraints GA · PriorityClass GAGang scheduling 1.37 Beta (not covered in detail)★★★★★
Learning objectives
  • Describe the scheduling framework's extension points (PreFilter → Filter → PostFilter (preemption) → PreScore → Score → Reserve → Permit → PreBind → Bind).
  • Be fluent with nodeSelector, nodeAffinity (required/preferred), podAffinity/podAntiAffinity, taints/tolerations, topologySpreadConstraints, and PriorityClass.
  • Maintain nodes with cordon/uncordon/drain, and interpret each part of a 0/3 nodes are available: … event.
Prerequisites: Module 1 (requests), Module 4 (PDB), Module 6 (taints and DaemonSets). Importance: ★★★★★

What: what the scheduler does

kube-scheduler watches Pods whose spec.nodeName is empty and puts them in the scheduling queue. For each Pod it runs a scheduling cycle (serially): first Filter removes infeasible nodes, then Score ranks the feasible nodes (each plugin's score is normalized to 0–100, then weighted and summed), and the highest-scoring node is chosen. Then the binding cycle (which can run in parallel) writes spec.nodeName through POST pods/binding, and the kubelet on that node sees it and starts the Pod.

Extension pointTypical pluginsPurpose
PreFilter / FilterNodeResourcesFit, NodeName, NodeUnschedulable, TaintToleration, NodeAffinity, InterPodAffinity, PodTopologySpread, VolumeBinding, VolumeZone, NodePortsFilter: if any plugin rejects a node, that node is infeasible
PostFilterDefaultPreemptionIf no node is feasible, try to preempt lower-priority Pods
PreScore / ScoreNodeResourcesFit (default LeastAllocated), NodeResourcesBalancedAllocation, ImageLocality, InterPodAffinity, NodeAffinity (preferred), TaintToleration (PreferNoSchedule), PodTopologySpreadScore: pick the best of the feasible nodes
Reserve / Permit / PreBind / BindVolumeBinding, DefaultBinderReserve resources, bind volumes, write the binding

Why: why constrain scheduling

Default scheduling only ensures that a Pod fits, not that replicas are spread out. Three replicas can all land on the same node or in the same availability zone, and one node failure or zone failure would take them all down. Specialized hardware (GPUs, high memory), compliance isolation, and cost (Spot nodes) also need explicit constraints.

How: the constraint toolbox

ToolDirectionHard/softExample
nodeSelectorPod → node labels (attract)Harddisktype: ssd
nodeAffinityPod → node labels, supports In/NotIn/Exists/DoesNotExist/Gt/LtrequiredDuringSchedulingIgnoredDuringExecution (hard) / preferred… (soft, with weight 1–100)Only nodes matching topology.kubernetes.io/zone in [a,b]
podAffinityPod → other Pods (attract)Hard/softapi and cache on the same node, to reduce latency
podAntiAffinityPod → other Pods (repel), where topologyKey defines what "same location" meansHard/softReplicas of the same Deployment are not on the same hostname
taints / tolerationsNodes repel Pods. Pods can enter only if they tolerate the taint.NoSchedule (hard), PreferNoSchedule (soft), NoExecute (also evicts running Pods that don't tolerate it; tolerationSeconds can be set)GPU nodes, system node pools
topologySpreadConstraintsSpread evenly across topology domainswhenUnsatisfiable: DoNotSchedule (hard) / ScheduleAnyway (soft)Spread evenly across two levels, zone and hostname, with maxSkew: 1
PriorityClassSets the scheduling queue order and preemption—Critical services 1000000, batch -10

Built-in taints: the node controller automatically adds node.kubernetes.io/not-ready and node.kubernetes.io/unreachable (NoExecute). The kubelet adds memory-pressure, disk-pressure, or pid-pressure when it reports pressure, and cordon adds node.kubernetes.io/unschedulable. The DefaultTolerationSeconds admission plugin automatically adds tolerationSeconds: 300 for not-ready and unreachable to regular Pods. This is why Pods are evicted and recreated only about 5 minutes after a node is lost. Kind control-plane nodes carry node-role.kubernetes.io/control-plane:NoSchedule.

Topology spread essentials: skew = matching Pods in a topology domain − the global minimum. labelSelector decides which Pods are counted. matchLabelKeys: [pod-template-hash] makes a rolling update count only the same version. minDomains sets the minimum number of domains. The cluster default constraints (used when none are set explicitly) are hostname maxSkew 3 and zone maxSkew 5, both ScheduleAnyway.

PriorityClass and preemption: when a high-priority Pod has nowhere to go, DefaultPreemption looks for a node where evicting some lower-priority Pods would make room. Preempted Pods go through graceful termination. PDBs are respected on a best-effort basis, not guaranteed. Built-in classes include system-cluster-critical and system-node-critical. preemptionPolicy: Never means the Pod only moves up the queue and does not preempt.

When: common combinations

  • Stateless multi-replica services: topologySpreadConstraints (zone DoNotSchedule + hostname ScheduleAnyway) + PDB.
  • Small clusters where replicas ≤ nodes and must be separated: podAntiAffinity required (note that if replicas > nodes, the extra replicas stay Pending).
  • Dedicated node pool: taint the nodes (to repel other workloads), and add a toleration plus nodeAffinity to the Pods (so they go only there). You need both.

Comparison with similar technologies

KubernetesDocker SwarmAWS ECS
Node constraintsnodeSelector/nodeAffinityplacement.constraintsplacement constraints
SpreadtopologySpread / antiAffinityplacement.preferences spreadspread placement strategy
Repeltaints/tolerationsNo direct equivalentNo direct equivalent
Common misconceptions ① "A toleration attracts a Pod to a tainted node." No. It only permits the Pod. To attract it, use nodeAffinity or nodeSelector. ② "IgnoredDuringExecution means the constraint has no effect." It means that a change in node labels while running does not evict existing Pods. The constraint still applies at scheduling time. ③ "cordon evicts Pods." cordon only stops new Pods from being scheduled. drain = cordon + evicting Pods one by one. ④ "podAntiAffinity is cheap." It is costly to compute in large clusters. The official guidance is to use required rules sparingly in clusters with hundreds of nodes or more, and to prefer topologySpread.

Architecture diagram: scheduling cycle

kube-apiserverPod nodeName="" watch Scheduling queueSorted by priority Filter4 nodes → 2 feasible ScoreWeighted sum, take the highest Bindpods/binding 0 feasible PostFilter: preemptionFind lower-priority Pods that can be evictedSet nominatedNodeName Failure → PendingEvent FailedScheduling:0/3 nodes are available: … Filter plugins: NodeUnschedulable · NodeResourcesFit · NodeAffinity · TaintToleration · VolumeBinding · InterPodAffinity · PodTopologySpread · NodePorts Score plugins: NodeResourcesFit(LeastAllocated) · BalancedAllocation · ImageLocality · InterPodAffinity · NodeAffinity · TaintToleration · PodTopologySpread
Figure 8-1 Scheduling cycle: Filter finds the feasible set, Score picks the best one. If both fail, the cycle moves to PostFilter (preemption).

Illustration: topology spread (maxSkew 1)

zone=canadacentral-1 node-a api-1 node-b api-2 zone=canadacentral-2 node-c api-3 node-d api-4 → here Zone level: zone1=2, zone2=1 → the new Pod can only go to zone2 (otherwise skew=2 > 1). Hostname level: node-d=0 is the lowest → choose node-d.
Figure 8-2 Two-level topologySpreadConstraints: zone balance first, then hostname balance within each zone

Scheduler simulator: Filter + Score

Check the Pod's constraints, then click "Schedule." The simulator filters the 4 nodes in the real plugin order and shows why each node was filtered out. It then scores the feasible nodes and produces either a Binding or a FailedScheduling event (the wording matches real events).

Constraints for Pod api-new
$ kubectl apply -f api-new.yaml

Core commands

CommandPurposeKey parameters
kubectl label node N k=vLabel a nodek- to remove
kubectl taint node N k=v:NoScheduleAdd a taintAdd - at the end to remove: k=v:NoSchedule-
kubectl cordon / uncordon NMark unschedulable / restoreDoes not affect running Pods
kubectl drain Ncordon + evict through the Eviction API--ignore-daemonsets --delete-emptydir-data --timeout=5m --pod-selector
kubectl get events --field-selector reason=FailedSchedulingCheck why scheduling failed-A --sort-by=.lastTimestamp
kubectl get pod -o wideNODE and NOMINATED NODE columnsShows nominated during preemption
kubectl get priorityclassView priority classesglobalDefault
spec:
  template:
    spec:
      priorityClassName: shop-critical
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: kubernetes.io/hostname
        whenUnsatisfiable: ScheduleAnyway
        labelSelector: { matchLabels: { app: api } }
        matchLabelKeys: [ pod-template-hash ]
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector: { matchLabels: { app: api } }
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - { key: kubernetes.io/os, operator: In, values: [linux] }
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata: { name: shop-critical }
value: 100000
globalDefault: false
description: "shop online service"
kubectl get nodes -L topology.kubernetes.io/zone,disktype
kubectl describe node lab-control-plane | grep Taints
kubectl get events -A --field-selector reason=FailedScheduling --sort-by=.lastTimestamp | tail
NAME                STATUS   ROLES           AGE   VERSION   ZONE   DISKTYPE
lab-control-plane   Ready    control-plane   2d    v1.37.0
lab-worker          Ready    <none>          2d    v1.37.0
lab-worker2         Ready    <none>          2d    v1.37.0
Taints:             node-role.kubernetes.io/control-plane:NoSchedule

Interpreting FailedScheduling events

Warning  FailedScheduling  default-scheduler  0/3 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 2 node(s) didn't match pod anti-affinity rules. preemption: 0/3 nodes are available: 1 Preemption is not helpful for scheduling, 2 No preemption victims found for incoming pod.
SnippetMeaningCorresponding plugin / action
0/3 nodes are availableAll 3 nodes were rejected by FilterThe counts below add up to the number of nodes (each node lists only its first rejection reason)
untolerated taint {…}Untolerated taintTaintToleration: add a toleration or change nodes
Insufficient cpu/memoryrequests do not fitNodeResourcesFit: lower requests or add capacity
didn't match Pod's node affinity/selectorNode labels do not matchNodeAffinity: check label spelling
didn't match pod anti-affinity rulesAnti-affinity conflictInterPodAffinity: replicas > nodes? Change to preferred
didn't match pod topology spread constraintsWould break maxSkewPodTopologySpread: change to ScheduleAnyway or add domains
node(s) were unschedulableNode is cordonedNodeUnschedulable: uncordon
volume node affinity conflictPV is bound to a node or zone elsewhereVolumeBinding (see Module 5)
preemption: …Preemption evaluation result"not helpful" = evicting other Pods would not fix it either (for example, a taint problem)

Lab 8: spreading across nodes, taint isolation, and a drain drill (about 9 minutes)

Label the nodes with simulated availability zones (kind nodes have no zone label by default):
kubectl label node lab-worker  topology.kubernetes.io/zone=zone-a --overwrite
kubectl label node lab-worker2 topology.kubernetes.io/zone=zone-b --overwrite
kubectl get nodes -L topology.kubernetes.io/zone
Observe the default distribution, then add topology spread constraints:
kubectl scale deploy/api --replicas=4
kubectl get pod -l app=api -o wide --sort-by=.spec.nodeName | awk '{print $1, $7}'
kubectl patch deploy api --type strategic -p '
spec:
  template:
    spec:
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector: { matchLabels: { app: api } }
        matchLabelKeys: [ pod-template-hash ]'
kubectl rollout status deploy/api
kubectl get pod -l app=api -o wide | awk 'NR>1{print $7}' | sort | uniq -c
      2 lab-worker
      2 lab-worker2
Create a Pending Pod and interpret it: required anti-affinity + 4 replicas, with only 2 schedulable nodes:
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata: { name: anti-demo, namespace: shop }
spec:
  replicas: 4
  selector: { matchLabels: { app: anti-demo } }
  template:
    metadata: { labels: { app: anti-demo } }
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - topologyKey: kubernetes.io/hostname
            labelSelector: { matchLabels: { app: anti-demo } }
      containers:
      - { name: pause, image: registry.k8s.io/pause:3.10 }
EOF
sleep 10; kubectl get pod -l app=anti-demo -o wide
kubectl get events --field-selector reason=FailedScheduling | tail -2
anti-demo-5b7d…   1/1   Running   lab-worker
anti-demo-5b7d…   1/1   Running   lab-worker2
anti-demo-5b7d…   0/1   Pending   <none>
anti-demo-5b7d…   0/1   Pending   <none>
… 0/3 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 2 node(s) didn't match pod anti-affinity rules. preemption: …
kubectl delete deploy anti-demo
Isolate a dedicated node with a taint:
kubectl taint node lab-worker2 dedicated=batch:NoSchedule
kubectl create deployment taint-demo --image=registry.k8s.io/pause:3.10 --replicas=3
sleep 5; kubectl get pod -l app=taint-demo -o wide | awk 'NR>1{print $7}' | sort | uniq -c   # all on lab-worker
kubectl taint node lab-worker2 dedicated=batch:NoSchedule-
kubectl delete deploy taint-demo
Drain drill (PDB from Module 4: minAvailable 2; api currently has 4 replicas):
kubectl get pdb api
kubectl drain lab-worker --ignore-daemonsets --delete-emptydir-data --timeout=3m
kubectl get pod -l app=api -o wide
kubectl uncordon lab-worker
node/lab-worker cordoned
Warning: ignoring DaemonSet-managed Pods: kube-system/kindnet-…, kube-system/kube-proxy-…, shop/node-agent-…
evicting pod shop/api-…
evicting pod shop/api-…
pod/api-… evicted
pod/api-… evicted
node/lab-worker drained

What to watch for: after the drain, the 2 replacement Pods evicted from lab-worker stay Pending with the event didn't match pod topology spread constraints. zone-a has only one node left, and it is cordoned (topology calculation ignores taints by default, so zone-a still counts as one domain). Placing the Pods in zone-b would make the skew 2–3. The PDB minAvailable 2 keeps 2 replicas serving traffic, but capacity is halved. This is the tension between hard topology constraints and maintenance operations. In production, each zone should have several nodes, or the zone constraint should use ScheduleAnyway (the capstone lab takes this approach). kubectl uncordon lab-worker lets the Pending Pods schedule right away. Also, if db-0 is on the node being drained, it stays Pending because the local-path PV cannot move (Module 5 scenario question). The capstone lab checks which node db is on first.

Cleanup: kubectl uncordon lab-worker; kubectl scale deploy/api --replicas=3. Keep the zone labels for the capstone lab.

Case 1: all 3 replicas go down during an availability zone outage

Problem: an AKS cluster spans 3 availability zones, but because api's 3 replicas use the default ScheduleAnyway constraint, all of them land in zone 1, so service is interrupted when zone 1 fails. Approach: set explicit topologySpreadConstraints: zone DoNotSchedule with maxSkew 1, plus hostname ScheduleAnyway; span the node pool across zones; PDB maxUnavailable 1. Limitation: stateful services that use zone-bound disks are limited by volume topology and cannot be freely spread across zones (hour 4).

Case 2: system node pool crowded out by workloads

Problem: the system nodes that run CoreDNS and metrics-server are filled by application Pods, and DNS latency rises. Approach: add the CriticalAddonsOnly=true:NoSchedule taint to the system node pool (the AKS recommended approach), run application workloads on the user node pool, and don't add that toleration to application Pods. Limitation: a DaemonSet that uses operator: Exists tolerates all taints, so it needs review.

Case 3: batch work pushes out online services

Problem: after a large batch of Jobs is created, they fill the resources, and online services stay Pending when they try to scale up. Approach: give the online service PriorityClass 100000 and the batch PriorityClass -10 with preemptionPolicy: Never. When an online Pod has nowhere to go, it preempts batch Pods. Batch Jobs use podFailurePolicy Ignore DisruptionTarget (Module 7). Limitation: preemption loses the work of the preempted Pods. ResourceQuota can cap total resources per priority class (hour 5).

Common errors and fixes

0/3 nodes are available: 3 node(s) didn't match Pod's node affinity/selector.

Cause: the label referenced by nodeSelector/nodeAffinity does not exist on the node (wrong spelling, case, or value).

kubectl get pod POD -o jsonpath='{.spec.nodeSelector}{"\n"}{.spec.affinity.nodeAffinity}{"\n"}'
kubectl get nodes --show-labels | tr ',' '\n' | grep -i disktype
0/3 nodes are available: 3 node(s) didn't match pod topology spread constraints.

Cause: with DoNotSchedule, every node choice would push the skew above maxSkew, or the node is missing the topologyKey label (nodes without that label are not counted as domains for this constraint).

kubectl get nodes -L topology.kubernetes.io/zone
kubectl get pod -l app=api -o wide

Fix: confirm the node labels, change to ScheduleAnyway, and use matchLabelKeys: [pod-template-hash] so old and new Pods are not counted together during a rollout.

drain stuck: Cannot evict pod as it would violate the pod's disruption budget (retrying continuously)

Cause: the PDB does not allow it, or a replacement replica of the evicted Pod cannot become Ready because of scheduling constraints.

kubectl get pdb -A
kubectl get pod -A --field-selector=status.phase=Pending

Fix: first resolve the Pending state of the replacement replica. If needed, temporarily relax the PDB or the scheduling constraints.

Pods are recreated only 5 minutes after a node becomes NotReady

Cause: the default tolerationSeconds: 300 (not-ready/unreachable).

Fix: for stateless services that need fast failover, explicitly set a shorter tolerationSeconds (for example, 30), but guard against frequent migrations caused by network blips.

Interactive troubleshooting decision tree: common workload problems

Covers six symptoms: Pending, CrashLoopBackOff, OOMKilled, probe failures, Jobs that won't complete, and stuck rollouts. Choose the symptom you see and work through the steps to find the cause.

Command-line exercises
1. Make lab-worker2 run only Pods that tolerate team=data, and make the data team's Pods go only to this node.
kubectl taint node lab-worker2 team=data:NoSchedule
kubectl label node lab-worker2 team=data
# Pod spec:
#   tolerations: [{key: team, operator: Equal, value: data, effect: NoSchedule}]
#   nodeSelector: {team: data}
2. Maintain lab-worker safely: evict all Pods (keep DaemonSets), wait up to 5 minutes, and restore the node when done.
kubectl drain lab-worker --ignore-daemonsets --delete-emptydir-data --timeout=5m
# …maintenance…
kubectl uncordon lab-worker
Scenario analysis
A 5-node cluster across 3 availability zones (zone-a has 2 nodes, zone-b has 2 nodes, zone-c has 1 node). A Deployment with 6 replicas has a zone-level maxSkew 1 DoNotSchedule constraint. What happens if the zone-c node fails? How would you improve it?

Before the failure, the distribution is 2/2/2. After the zone-c node fails, if the node is still in the cluster (NotReady with a taint), zone-c has no feasible node but is still counted as a domain. Rebuilding the 2 missing replicas on a or b would give 3/3/0 or 3/2/0, so skew > 1 and the Pods stay Pending. The service stays at 4 replicas. Improvements: use ScheduleAnyway for the zone constraint or accept reduced capacity; be clear about what minDomains means before you set it; keep at least 2 nodes in each zone; combine with HPA and PDB; keep spare capacity for critical services (N+1 zones).

Verified video lessons

No verified video was found that specifically covers the scheduler's Filter/Score or topology spread with matching title, author, and ID. You can refer to this verified comprehensive course:

▶
Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours] — TechWorld with Nana
English · review the scheduler's role in cluster architecture

Official documentation

Video storyboard script (about 110 seconds)

This lesson file cannot generate a video or MP3 directly, so a storyboard and an English voice narration script are provided.

Shot 1 · 0–25s
Visual: Pod cards drop into a funnel. Four nodes are filtered one by one through a sieve, and each filtered node shows a reason label (taint, insufficient memory, anti-affinity).
Narration: The scheduler filters first. If any one plugin says no, that node is excluded.
Shot 2 · 25–50s
Visual: score bars appear above the two remaining nodes. Resource headroom, image locality, and preferred affinity add up one by one. The highest score wins, and an arrow writes the nodeName.
Narration: Next it scores the nodes and picks the highest-scoring one. Finally, it binds the Pod through the binding subresource.
Shot 3 · 50–80s
Visual: a GPU node behind a lock. Only a Pod holding the key (toleration) can enter. On the other side, a magnet (nodeAffinity) pulls Pods in.
Narration: Taints repel, and tolerations only permit. To attract Pods, use node affinity. A dedicated node pool needs both.
Shot 4 · 80–110s
Visual: a bar chart of two availability zones, with 2 replicas in one and 1 in the other. The new Pod can only land on the smaller side. At the end, the FailedScheduling event text appears, highlighted segment by segment.
Narration: Topology spread constraints keep replicas evenly distributed. When a Pod is stuck in Pending, read the 0/3 nodes are available line in the event. Each part corresponds to a filter plugin.
Or score ≥ 70% in the quiz

Command cheat sheet

Kubernetes v1.37 · Workloads and scheduling · every code block has a one-click copy button
After-class reference

Resources and QoS

kubectl set resources deploy/X -c C --requests=cpu=100m,memory=128Mi --limits=memory=256Mi
kubectl top pod -A --sort-by=memory --containers
kubectl top node
kubectl describe node N | sed -n '/Allocated resources/,/Events/p'
kubectl get pod -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
kubectl get pod P -o jsonpath='{.status.containerStatuses[*].lastState.terminated.reason}'
kubectl patch pod P --subresource resize --type merge -p \
  '{"spec":{"containers":[{"name":"C","resources":{"limits":{"cpu":"1"}}}]}}'

Probes and termination

kubectl describe pod P | grep -E "Liveness|Readiness|Startup"
kubectl get events --field-selector reason=Unhealthy --sort-by=.lastTimestamp
kubectl get endpointslice -l kubernetes.io/service-name=S -o yaml
kubectl delete pod P --grace-period=60
kubectl get pod P -o jsonpath='{.metadata.deletionTimestamp}'
# lifecycle: { preStop: { sleep: { seconds: 5 } } }   (v1.34 GA)

ConfigMap / Secret

kubectl create cm C --from-literal=K=V --from-file=app.conf --from-env-file=.env
kubectl create secret generic S --from-literal=PASSWORD='p@ss'
kubectl create secret tls T --cert=tls.crt --key=tls.key
kubectl create secret docker-registry R --docker-server=… --docker-username=… --docker-password=…
kubectl create cm C --from-file=app.conf --dry-run=client -o yaml | kubectl apply -f -
kubectl get secret S -o jsonpath='{.data.PASSWORD}' | base64 -d
kubectl rollout restart deploy/X

Rollouts and PDB

kubectl rollout status deploy/X --timeout=5m || kubectl rollout undo deploy/X
kubectl rollout pause deploy/X; kubectl set image …; kubectl rollout resume deploy/X
kubectl rollout history deploy/X; kubectl rollout undo deploy/X --to-revision=N
kubectl get deploy X -o jsonpath='{.status.conditions}'
kubectl create pdb X --selector=app=X --max-unavailable=1
kubectl get pdb -A
kubectl patch svc S -p '{"spec":{"selector":{"app":"X","version":"green"}}}'

StatefulSet

kubectl get sts,pod,pvc -l app=X
kubectl scale sts/X --replicas=N
kubectl patch sts X -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}}'
kubectl rollout status sts/X; kubectl rollout undo sts/X
kubectl delete sts X --cascade=orphan      # keep Pods and PVCs
kubectl get controllerrevision -l app=X
nslookup X-0.X.NS.svc.cluster.local

DaemonSet

kubectl get ds -A
kubectl rollout status ds/X -n NS
kubectl get pod -l app=X -o wide
kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints
# tolerations: [{key: node-role.kubernetes.io/control-plane, operator: Exists, effect: NoSchedule}]

Job / CronJob

kubectl create job J --image=busybox:1.37 -- sh -c 'echo hi'
kubectl create cronjob C --image=IMG --schedule="0 2 * * *" -- CMD
kubectl create job manual-1 --from=cronjob/C
kubectl wait --for=condition=complete job/J --timeout=10m
kubectl logs job/J
kubectl get job J -o jsonpath='{.status.completedIndexes} {.status.failedIndexes}'
kubectl patch cronjob C -p '{"spec":{"suspend":true}}'

Scheduling and node maintenance

kubectl label node N topology.kubernetes.io/zone=zone-a
kubectl taint node N dedicated=batch:NoSchedule      # add - at the end to remove
kubectl cordon N; kubectl uncordon N
kubectl drain N --ignore-daemonsets --delete-emptydir-data --timeout=5m
kubectl get events -A --field-selector reason=FailedScheduling --sort-by=.lastTimestamp
kubectl get pod -o wide --field-selector spec.nodeName=N
kubectl get priorityclass

Quick troubleshooting table

SymptomWhat to check firstCommon causes
Pendingkubectl describe pod, look for FailedSchedulingrequests too large, taints, affinity/topology constraints, unbound PVC, volume node affinity
OOMKilled / Exit 137lastState.terminated.reason, kubectl toplimits.memory too small, memory leak, heap size not adapted to the container
High latency, but average CPU is not highCheck cpu.stat on the node for nr_throttledCPU limit throttling
Running but 0/1describe shows Readiness probe failedWrong probe path or port, or a dependency is unavailable
Repeated restarts (liveness)Events show Liveness probe failedSlow startup without a startupProbe, timeout too short, liveness check depends on other services
CreateContainerConfigErrordescribe podConfigMap/Secret or key does not exist
Config change not taking effectCheck the injection methodenv/subPath are not hot-reloaded, so a rollout is needed
Rollout stuckrollout status, Pod events of the new ReplicaSetProgressDeadlineExceeded, image, probes, resources
drain stuckkubectl get pdb -APDB does not allow it, replacement Pod Pending
Job not completingdescribe job, logs of failed PodsBackoffLimitExceeded, DeadlineExceeded, Pod Pending

For the full interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.

Recommended config snippet: production-ready stateless service

spec:
  replicas: 3
  revisionHistoryLimit: 5
  minReadySeconds: 5
  progressDeadlineSeconds: 300
  strategy: { type: RollingUpdate, rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } }
  template:
    spec:
      priorityClassName: shop-critical
      terminationGracePeriodSeconds: 30
      topologySpreadConstraints:
      - { maxSkew: 1, topologyKey: topology.kubernetes.io/zone, whenUnsatisfiable: ScheduleAnyway,
          labelSelector: { matchLabels: { app: api } }, matchLabelKeys: [pod-template-hash] }
      - { maxSkew: 1, topologyKey: kubernetes.io/hostname, whenUnsatisfiable: ScheduleAnyway,
          labelSelector: { matchLabels: { app: api } }, matchLabelKeys: [pod-template-hash] }
      containers:
      - name: app
        resources:
          requests: { cpu: 100m, memory: 128Mi }
          limits:   { memory: 128Mi }          # memory requests = limits; set a CPU limit only if the workload needs one
        startupProbe:   { httpGet: { path: /healthz, port: http }, periodSeconds: 2, failureThreshold: 30 }
        livenessProbe:  { httpGet: { path: /healthz, port: http }, periodSeconds: 10, timeoutSeconds: 2, failureThreshold: 3 }
        readinessProbe: { httpGet: { path: /readyz,  port: http }, periodSeconds: 5, failureThreshold: 2 }
        lifecycle: { preStop: { sleep: { seconds: 5 } } }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
spec: { maxUnavailable: 1, unhealthyPodEvictionPolicy: AlwaysAllow, selector: { matchLabels: { app: api } } }

Capstone lab + final quiz

Upgrade shop to "production-ready": resources, probes, externalized config, PDB, spread, a postgres StatefulSet, and a backup CronJob. Finally, verify zero downtime with a drain drill.
After class ≈ 35 minutesCovers all modules
Scenario shop is about to go live. The SRE review requires: every container has requests/limits; api has all three probes and graceful termination; config and passwords are not in the image; no failed requests reach api during any node maintenance; replicas are spread across nodes; the database has a stable identity and persistent volumes and is backed up every 5 minutes (a demo frequency). Complete this in the shop namespace of the kind cluster lab, and use a drain drill to prove "zero downtime."
Pre-checks (Modules 0, 3, 5, 7)
kubectl config set-context --current --namespace=shop
kubectl get nodes -L topology.kubernetes.io/zone
kubectl get cm api-config api-files; kubectl get secret db-cred
kubectl get sts db; kubectl get cronjob db-backup; kubectl get ds node-agent
kubectl top nodes

If an object is missing, go back to the "Lab" tab of the matching module and create it. If the zone labels are missing, run Step 1 of the Module 8 lab.

PriorityClass + production api Deployment (Modules 1, 2, 3, 4, 8)
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata: { name: shop-critical }
value: 100000
description: "shop online service"
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: api, namespace: shop, labels: { app: api } }
spec:
  replicas: 3
  revisionHistoryLimit: 5
  minReadySeconds: 5
  progressDeadlineSeconds: 300
  strategy: { type: RollingUpdate, rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } }
  selector: { matchLabels: { app: api } }
  template:
    metadata:
      labels: { app: api }
      annotations: { checksum/config: "v1" }
    spec:
      priorityClassName: shop-critical
      terminationGracePeriodSeconds: 30
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: ScheduleAnyway
        labelSelector: { matchLabels: { app: api } }
        matchLabelKeys: [ pod-template-hash ]
      - maxSkew: 1
        topologyKey: kubernetes.io/hostname
        whenUnsatisfiable: ScheduleAnyway
        labelSelector: { matchLabels: { app: api } }
        matchLabelKeys: [ pod-template-hash ]
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector: { matchLabels: { app: api } }
      containers:
      - name: podinfo
        image: ghcr.io/stefanprodan/podinfo:6.17.0
        ports: [ { name: http, containerPort: 9898 } ]
        envFrom: [ { configMapRef: { name: api-config } } ]
        env:
        - name: DB_PASSWORD
          valueFrom: { secretKeyRef: { name: db-cred, key: POSTGRES_PASSWORD } }
        volumeMounts: [ { name: files, mountPath: /etc/shop, readOnly: true } ]
        resources:
          requests: { cpu: 50m, memory: 64Mi }
          limits:   { cpu: 500m, memory: 128Mi }
        startupProbe:   { httpGet: { path: /healthz, port: http }, periodSeconds: 2, failureThreshold: 30 }
        livenessProbe:  { httpGet: { path: /healthz, port: http }, periodSeconds: 10, timeoutSeconds: 2, failureThreshold: 3 }
        readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, failureThreshold: 2 }
        lifecycle: { preStop: { sleep: { seconds: 5 } } }
      volumes:
      - name: files
        configMap: { name: api-files }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: api, namespace: shop }
spec:
  maxUnavailable: 1
  unhealthyPodEvictionPolicy: AlwaysAllow
  selector: { matchLabels: { app: api } }
kubectl delete pdb api --ignore-not-found     # replaces the minAvailable version from Module 4
kubectl apply -f shop-api-prod.yaml
kubectl rollout status deploy/api
kubectl get pod -l app=api -o wide
kubectl get pdb api

If kubectl apply reports a field conflict with an earlier kubectl patch, you can first run kubectl apply --server-side --force-conflicts -f shop-api-prod.yaml. Note: apply removes only fields that were in the previous apply and are not in this manifest. Fields added earlier with kubectl create or patch (such as the subPath mount from Module 3) are not removed automatically. List fields such as topologySpreadConstraints are merged by key, so the zone DoNotSchedule constraint added in Module 8 would coexist with the new ScheduleAnyway constraint and cause Pending Pods in the drain drill. So if you applied patches in earlier modules, first run kubectl delete deploy api and then apply (there is a brief interruption, which is acceptable before go-live). After that, manage it with apply only.

Verify each production property
kubectl get pod -l app=api -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,QOS:.status.qosClass,PRIO:.spec.priority
POD=$(kubectl get pod -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl describe pod $POD | grep -E "Liveness|Readiness|Startup|PreStop|Limits|Requests" -A0
kubectl exec $POD -- sh -c 'echo $PODINFO_UI_MESSAGE; test -n "$DB_PASSWORD" && echo "secret injected"'
kubectl get pod db-0 -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,QOS:.status.qosClass
kubectl create job verify-backup --from=cronjob/db-backup && kubectl wait --for=condition=complete job/verify-backup --timeout=2m && kubectl logs job/verify-backup | tail -1
NAME                   NODE          QOS         PRIO
api-5f8c9d7b6c-8kq2w   lab-worker    Burstable   100000
api-5f8c9d7b6c-m4zts   lab-worker2   Burstable   100000
api-5f8c9d7b6c-x9prl   lab-worker    Burstable   100000
…
Hello v2
secret injected
backup ok: /backup/shop-20261115-101503.sql.gz
Drain drill: prove zero downtime (Modules 2, 4, 6, 8)
DBNODE=$(kubectl get pod db-0 -o jsonpath='{.spec.nodeName}')
TARGET=$(kubectl get nodes -l '!node-role.kubernetes.io/control-plane' -o name | sed 's#node/##' | grep -v "^$DBNODE$" | head -1)
echo "db is on $DBNODE, rehearsing drain of $TARGET"
# pin the load-test client to a node that will not be drained
kubectl run load --image=curlimages/curl --restart=Never \
  --overrides="{\"apiVersion\":\"v1\",\"spec\":{\"nodeSelector\":{\"kubernetes.io/hostname\":\"$DBNODE\"}}}" \
  --command -- sh -c 'while true; do curl -s -o /dev/null -m 2 -w "%{http_code}\n" http://api:9898/version; sleep 0.1; done'
kubectl wait --for=condition=Ready pod/load --timeout=60s
kubectl drain $TARGET --ignore-daemonsets --delete-emptydir-data --timeout=5m
kubectl get pod -l app=api -o wide
sleep 10; kubectl uncordon $TARGET
kubectl logs load | sort | uniq -c
kubectl delete pod load --now
db is on lab-worker2, rehearsing drain of lab-worker
…
node/lab-worker drained
   2140 200

Only 200 means pass. If 000 or 5xx appears, check whether readiness is configured, whether the preStop sleep is working, whether the PDB allowed too many evictions, and whether replacement Pods are Pending (kubectl get events --field-selector reason=FailedScheduling). After the drain, the 3 api replicas are temporarily all on the same node. After uncordon they will not redistribute automatically, because scheduling only happens at creation time. You can run kubectl rollout restart deploy/api to rebalance, or learn about the descheduler in hour 6.

Return to Module 0 and redo the production-readiness self-assessment and compare the scores. Clean up the demo object with kubectl delete job verify-backup. Keep the cluster for hour 3 (networking). To free resources, run kind delete cluster --name lab (the start of the next hour has the rebuild command). When you're not using the Azure VM, stop it or run az group delete -n rg-k8s-lab --yes --no-wait.
Acceptance checklist

Open-ended self-check (answer on your own first, then expand the reference answers)

1. Which component uses requests, and which uses limits? What do they become in the kernel?

kube-scheduler uses requests for NodeResourcesFit filtering and scoring, and CPU requests are also converted to the cgroup cpu.weight. The kubelet passes limits to runc through CRI, which writes cpu.max (throttling) and memory.max (OOM kill).

2. Why is a preStop sleep needed when a Pod is deleted?

Endpoint removal (EndpointSlice → kube-proxy on each node) and the kubelet sending SIGTERM happen in parallel, with no ordering guarantee. The sleep makes SIGTERM arrive after the rules have been updated, so new requests don't reach a Pod that has already stopped listening.

3. After a ConfigMap is updated, what happens to env, volume, and subPath?

env/envFrom do not change (a restart is needed). Volume files are updated atomically after the kubelet's next sync (usually 1–2 minutes), and whether the app rereads them depends on the app. subPath is never updated.

4. Which operations can a PDB protect, and which can't it?

It protects voluntary disruptions that go through the Eviction API: kubectl drain, cluster autoscaler scale-down, and managed-cluster node upgrades. It does not protect against direct Pod deletion, Deployment rolling updates, node failures, or OOM.

5. What are the three core differences between a StatefulSet and a Deployment?

Stable ordinal names and per-Pod DNS (headless Service); an independent PVC per replica (volumeClaimTemplates); ordered creation, reverse-order scale-down, and reverse-order rolling updates (partition can be used to roll out in batches).

6. You see 0/3 nodes are available: 1 node(s) had untolerated taint …, 2 Insufficient memory. How would you handle it?

It is normal for the control plane to have a taint, and you should not place workloads there. The real issue is that the 2 workers' allocatable resources are not enough for the Pod's memory requests. Check the Allocated resources in describe node, lower overly large requests, or add nodes. For a high-priority service, consider PriorityClass preemption of lower-priority Pods.

Final quiz (12 questions, covering all modules)

Sources and versions

Evidence for all technical facts in this lesson. Verified on 2026-11-15.
TopicVerification resultSources (accessed 2026-11-15)
Kubernetes version1.37 latest patch is 1.37.1 (2026-09-15). Supported: 1.37, 1.36, 1.35. 1.34 reached EOL on 2026-10-27.kubernetes.io/releases
v1.37 release notesMemoryQoS Beta enabled by default (memory.min/low/high, memoryReservationPolicy, memoryThrottlingFactor). StatefulSet Recreate Alpha (gate StatefulSetRecreateStrategy, deletes all Pods before creating new ones). StatefulSet maxUnavailable is enabled by default again in v1.37 (a defect was found in v1.36, kubernetes#137409). In-place resize scheduling preemption Alpha (InPlacePodVerticalScalingSchedulerPreemption). Gang scheduling Beta. Node lifecycle conditions Alpha (DrainInProgress, etc.).Kubernetes v1.37 “Garhwal” release blog (2026-08-26)
Feature gate stagesInPlacePodVerticalScaling: 1.27 Alpha / 1.33 Beta / 1.35 GA. PodLevelResources: 1.32 Alpha / 1.34 Beta (on by default). PodLifecycleSleepAction: 1.29 Alpha / 1.30 Beta / 1.34 GA. PodLifecycleSleepActionAllowZero: 1.34 GA. MaxUnavailableStatefulSet: 1.24 Alpha / 1.35 Beta (off by default in 1.35.4–1.36) / on by default in 1.37. StatefulSetAutoDeletePVC: 1.32 GA. StatefulSetStartOrdinal: 1.31 GA. JobBackoffLimitPerIndex, JobSuccessPolicy: 1.33 GA. JobPodReplacementPolicy: 1.34 GA. JobManagedBy: 1.35 GA. MemoryQoS: 1.37 Beta. SidecarContainers: 1.33 GA.Feature Gates
Job failure policypodFailurePolicy v1.31 GA (requires restartPolicy Never). Indexed Job v1.24 GA. CronJob timeZone v1.27 GA.Jobs · CronJob
metrics-serverLatest v0.9.1 (2026-10-29). Install manifest releases/download/v0.9.1/components.yaml. kind needs --kubelet-insecure-tls (lab use only).metrics-server releases
kindv0.33.0, default kindest/node:v1.37.0. Default StorageClass standard (rancher.io/local-path, WaitForFirstConsumer).kind releases
Resources and QoSQoS classification rules, eviction ordering, cgroup v2 mappingResource Management · Pod QoS · Node-pressure Eviction
OOM/CPU lab imagespolinux/stress (memory example) and vish/stress (CPU example) come from the official task documentationAssign Memory Resources · Assign CPU Resources
Probes and terminationDefault probe parameters, termination flow, preStop sleepProbes · Pod Lifecycle
SchedulingScheduling framework extension points, default plugins, default topology spread constraints, preemptionScheduling Framework · Topology Spread · Priority & Preemption

Video verification notes

The following videos were verified through the YouTube oEmbed API (2026-11-15). Titles, channels, and video IDs match: TechWorld with Nana, "Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]" (X48VuDVv0do), "Kubernetes Crash Course for Absolute Beginners [NEW]" (s_o8dwzRlu4), "Kubernetes StatefulSet simply explained | Deployment vs StatefulSet" (pPQKAR1pA9U), "Kubernetes ConfigMap and Secret as Kubernetes Volumes | Demo" (FAnQTgr04mU), and "Complete Application Deployment using Kubernetes Components | Kubernetes Tutorial 20" (EQNO_kM96Mo). Fireship, "Kubernetes Explained in 100 Seconds" (PziYflu8cB8). Google Cloud Tech, "Setting Resource Requests and Limits in Kubernetes" (xjpHggHKm78) and "Kubernetes Health Checks with Readiness and Liveness Probes" (mxEvAPQRwhw). oEmbed does not return durations or publish dates, so the cards list no specific durations. The Google Cloud Tech series is inferred to be from 2018 based on the accompanying blog posts. No verified dedicated video was found for DaemonSet, Job/CronJob, the scheduler, or rollout strategies/PDB, so storyboard scripts are provided instead. All videos are in English and were recorded before v1.37, so for new features, refer to this lesson and the official documentation.

English voice narration notes

The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration aloud in real time, with English terms pronounced in en-US. The result depends on the voices installed on your operating system, such as the English voices on Windows or macOS. This course build cannot call a TTS service, so no MP3 is embedded. If you need offline audio, give the narration script to a TTS service such as Azure AI Speech to generate it.

Known limitations

  • The Pod name suffixes, IPs, UIDs, hashes, times and counts in the “Expected output” are sample values. Your environment will show different values.
  • A kind node can see all CPU and memory on the host, so allocatable, eviction and throttling behavior differs from cloud nodes. kind has no real availability zones, so this hour simulates them with the topology.kubernetes.io/zone label.
  • kind's local-path storage binds a PV to a node, so cross-node StatefulSet migration is demonstrated in hour 4 with a cloud disk (Azure Disk CSI).
  • The cgroup file paths assume kind v0.33's default systemd cgroup driver with cgroup v2. If a path does not match, find it with find /sys/fs/cgroup -name "cri-containerd-<id>*".
  • The times, probabilities and scores in the animation are illustrative values. They explain the mechanism and are not exact scheduler scores.
  • The alpha features (StatefulSet Recreate, resize preemption, node lifecycle conditions) are not enabled in kind's default configuration. This hour only introduces them. For field details, see the official docs.