Kubernetes Hour 2: Workloads and Scheduling
- 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.sleepto 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 availableevents.
1-hour timetable
| # | Time | Module | Core content | Animation / interactive | Lab (kind cluster lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | Check the cluster and shop app, rebuild commands, install metrics-server | 10-item production-readiness self-check | kubectl top works |
| 1 | 00–07 | Resources: requests/limits and QoS | Scheduling 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 simulator | Reproduce OOMKilled (137), observe throttling, resize in place |
| 2 | 07–15 | Probes and graceful termination | Three probe types: semantics and misuse; four probe methods; termination flow; preStop sleep (1.34 GA) | Termination timeline: endpoint removal races SIGTERM | Add probes to api + zero-downtime rolling update |
| 3 | 15–22 | ConfigMap and Secret | Ways to create them, env/envFrom/volume/subPath, hot-update delay, immutable, imagePullSecrets, rollouts triggered by config changes | Whether env and volume changes take effect after an update | Externalized config + checksum rollout |
| 4 | 22–30 | Advanced rollout strategies | maxSurge/maxUnavailable calculation, minReadySeconds, progressDeadlineSeconds, pause/resume, blue-green, canary, PDB | Rolling-update calculator + blue-green switch + canary ratio | Blue-green switch + PDB and drain |
| 5 | 30–37 | StatefulSet | Stable identity, headless Service, volumeClaimTemplates, OrderedReady/Parallel, partition, Recreate (1.37 Alpha), PVC retention policy | Ordered creation and batched updates with partition | Deploy a postgres:17 StatefulSet |
| 6 | 37–42 | DaemonSet | One per node, system DaemonSets, tolerating control-plane taints, update strategy | How DaemonSets react when nodes join or taints change | Deploy a node agent |
| 7 | 42–49 | Job and CronJob | completions/parallelism/backoffLimit, Indexed, podFailurePolicy, successPolicy, backoffLimitPerIndex, timeZone, concurrencyPolicy | Job parallelism and retry simulator | postgres backup CronJob |
| 8 | 49–60 | Scheduling: affinity · taints · topology spread | Scheduling framework, nodeAffinity, pod(Anti)Affinity, taints/tolerations, topologySpread, PriorityClass preemption, cordon/drain, Pending diagnosis | Scheduler Filter + Score simulator + troubleshooting tree | Cross-node distribution + drain drill |
| — | After class | Cheat sheet · Capstone lab | Upgrade shop to “production-ready” and verify a zero-downtime drain | Final quiz (12 questions) | Capstone lab |
Knowledge coverage matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Set container resources and explain QoS | ✓ | · | · | · | · | · | · | ✓ | kubectl top, describe node | OOMKilled / resize |
| Diagnose OOMKilled / CPU throttling | ✓ | · | · | · | · | · | · | · | get pod -o jsonpath, cpu.stat | M1 lab |
| Design probes and implement graceful termination | · | ✓ | · | ✓ | · | · | · | · | describe pod, events | Zero-downtime rolling update |
| Externalize config and secrets, hot-reload config | · | · | ✓ | · | · | · | ✓ | · | create configmap/secret | Checksum rollout |
| Safe releases: rolling, blue-green, canary | · | ✓ | ✓ | ✓ | · | · | · | · | rollout status/pause/undo | Blue-green switch |
| Voluntary disruption protection (PDB / drain) | · | · | · | ✓ | · | ✓ | · | ✓ | drain, get pdb | Drain drill |
| Run stateful applications | · | · | ✓ | · | ✓ | · | ✓ | · | get sts,pvc | postgres:17 |
| Node-level agents | · | · | · | · | · | ✓ | · | ✓ | get ds -A | node-agent |
| Batch jobs and scheduled tasks | · | · | · | · | · | · | ✓ | · | create job --from=cronjob/ | pg_dump backup |
| Scheduling constraints and Pending troubleshooting | ✓ | · | · | · | ✓ | ✓ | · | ✓ | taint, cordon, events | Topology spread |
Out of scope for this hour (and where to learn it)
| Topic | Why it is not covered in this hour | Where to learn it |
|---|---|---|
| Service deep dive, Gateway API weighted routing, NetworkPolicy | Belongs to the networking topic | Hour 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 running | Hour 4 |
| Secret encryption at rest (KMS v2), External Secrets, RBAC, Pod Security | Belongs to the security topic | Hour 5 |
| HPA/VPA/KEDA autoscaling, Argo Rollouts, Helm/Kustomize | Belongs to the operations and delivery topic | Scaling 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 plugins | Aimed at AI and batch platforms, and more than one hour's worth of material | Official Scheduling docs |
How to use this course
Principles · diagrams · animation · commands · lab · production cases · troubleshooting · quiz · voice · video. Start with “Principles” and “Animation,” then do the “Lab.”
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.
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.
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)
- You have completed hour 1: a kind cluster
lab(1 control-plane + 2 worker), the namespaceshop, which contains theapiDeployment (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
shopnamespace 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
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%
--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.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.
Module 1 · Resource requests/limits and QoS
- 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 v2cpu.maxandmemory.max. - Identify a Pod's QoS class (Guaranteed / Burstable / BestEffort), and explain the eviction and OOM priority under node memory pressure.
- Use
kubectl topand the Allocated resources section ofkubectl describe nodefor capacity analysis. Use--subresource resizeto resize resources in place.
--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/Giare powers of 2 (1Mi = 1048576 bytes);M/Gare powers of 10. Watch out:400mmemory 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
| Field | Consumer | Mechanism (cgroup v2) | What happens when exceeded |
|---|---|---|---|
| requests.cpu | kube-scheduler (NodeResourcesFit filter + scoring); kubelet | Converted to cpu.weight (CPU is shared proportionally when busy) | Can use idle CPU beyond the request |
| limits.cpu | kubelet → containerd → runc | cpu.max = "quota period", e.g. 500m → 50000 100000 | Throttling: once the quota for this period is used up, threads are paused until the next period, and nr_throttled in cpu.stat increases |
| requests.memory | kube-scheduler; kubelet eviction ordering; MemoryQoS | When MemoryQoS (1.37 Beta) is enabled, it provides memory.min/memory.low protection | Can go over, but is evicted first under node memory pressure |
| limits.memory | kubelet → runc | memory.max; MemoryQoS also sets memory.high based on the throttling factor | Kernel 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 class | Condition | oom_score_adj | Under node memory pressure |
|---|---|---|---|
| Guaranteed | Every container in the Pod sets CPU and memory requests and limits, and requests = limits | -997 | Evicted last |
| Burstable | Does not meet Guaranteed, but at least one container sets a CPU or memory request or limit | 2–999 (based on the memory request's share of the node) | Containers using more than their requests go first |
| BestEffort | No container has any requests or limits | 1000 | Evicted 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 theresizesubresource, without recreating the Pod. A container'sresizePolicydecides 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 inspec.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.highso that requests protect memory from reclaim.memory.highthrottles reclaim before the limit is reached, which reduces direct OOMs. kubelet settings:memoryReservationPolicy,memoryThrottlingFactor. - Since v1.35, the kubelet's
failCgroupV1defaults 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.weightfrom requests for fairness. Multi-tenant clusters usually enforce limits (using LimitRange/ResourceQuota, hour 5). - Use Guaranteed when you need exclusive CPUs (
staticCPU manager) or the highest eviction protection.
Comparison with similar technologies
| Kubernetes | Docker (single host) | Azure Container Apps / ECS | |
|---|---|---|---|
| Reservation | requests (affects scheduling) | None (--cpu-shares is only a weight) | Billed by vCPU/memory size; the platform schedules it |
| Limit | limits → cpu.max/memory.max | --cpus/--memory, same mechanism | Size is the limit |
| In-place resize | resize subresource (1.35 GA) | docker update | Creates a new revision |
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
Flow chart: what happens after a limit is exceeded
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.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl set resources | Change resources in the Deployment template (triggers a rollout) | -c container --requests=cpu=100m,memory=128Mi --limits=memory=256Mi |
kubectl top pod/node | View live usage (metrics-server) | --containers, --sort-by=memory, -A |
kubectl describe node | Capacity / Allocatable / Allocated resources | Check requests as a percentage of allocatable |
kubectl get pod -o jsonpath | QoS, termination reason, exit code | {.status.qosClass}, {.status.containerStatuses[0].lastState} |
kubectl patch pod --subresource resize | Resize a running Pod in place (1.35 GA) | Requires kubectl ≥ 1.32; only cpu/memory can be changed |
kubectl explain pod.spec.containers.resizePolicy | View the resize restart policy fields | resourceName + 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)
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":"…"}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*".
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.
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).
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.
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 OOMKilledkubectl 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
Official docs
- Resource Management for Pods and Containers
- Resize CPU and Memory Resources assigned to Containers
- Pod Quality of Service Classes
- Node-pressure Eviction
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.
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.
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.
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.
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.
Module 2 · Probes and graceful termination
- 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.sleepto remove 502s during rollouts.
What: the three probe types
| Probe | Question it answers | Result of failure | Typical checks |
|---|---|---|---|
| startupProbe | Has 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 |
| livenessProbe | Is the process still “alive” (no deadlock or hang)? | Fails failureThreshold times in a row → kubelet restarts the container | Checks only the process itself (for example /healthz), not dependencies such as the database |
| readinessProbe | Can 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
initialDelaySecondson 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.
| Parameter | Default | Meaning |
|---|---|---|
initialDelaySeconds | 0 | How long after container start before probing begins (usually not needed when startupProbe is set) |
periodSeconds | 10 | Probe interval |
timeoutSeconds | 1 | Timeout for a single probe (raise it for apps with long GC pauses) |
failureThreshold | 3 | Consecutive failures before the probe counts as failed |
successThreshold | 1 | Consecutive successes before the probe counts as successful (must be 1 for liveness/startup) |
terminationGracePeriodSeconds (probe level) | Inherits from the Pod | Grace 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
- A user or controller deletes the Pod: the apiserver sets
metadata.deletionTimestampanddeletionGracePeriodSeconds(defaultterminationGracePeriodSeconds: 30). - 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. - The kubelet first runs the preStop hook (exec / httpGet / sleep). Time spent in the hook counts toward the grace period.
- After preStop finishes, the container runtime sends SIGTERM to PID 1 (or the image's STOPSIGNAL).
- 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
| Kubernetes | Docker HEALTHCHECK | Azure LB / App Gateway health probes | |
|---|---|---|---|
| Executor | Node kubelet | dockerd | Cloud load balancer |
| Action on failure | liveness restarts / readiness removes from traffic | Only marks it unhealthy (no automatic restart on a single machine) | Removed from the backend pool |
| Startup protection | startupProbe | --start-period | None |
Architecture diagram: how probe results affect traffic
Sequence diagram: two parallel timelines for Pod termination
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.
Core commands and config
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl describe pod | View the probe config and Unhealthy events | In Events: Liveness probe failed / Readiness probe failed |
kubectl get pod -o wide | READY column (ready containers / total) | 0/1 Running = the process is running but not ready |
kubectl get endpointslice -l kubernetes.io/service-name=api | Check whether endpoints are ready | -o yaml to view conditions |
kubectl get events --field-selector reason=Unhealthy | View probe failures in one place | --sort-by=.lastTimestamp |
kubectl delete pod --grace-period=N | Set 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)
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
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.
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 statskubectl 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.
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.
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
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
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
- Configure Liveness, Readiness and Startup Probes
- Pod Lifecycle: Termination of Pods
- Container Lifecycle Hooks
Video storyboard (about 100 s)
This course file cannot generate video or MP3 directly. The storyboard and narration script are provided.
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.
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.
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.
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.
Module 3 · ConfigMap and Secret
- Create ConfigMaps and Secrets with
--from-literal / --from-file / --from-env-fileand 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 restartor a checksum annotation. - Understand the real security boundaries of Secrets (base64, etcd, RBAC). Create tls and docker-registry Secrets and configure imagePullSecrets.
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
| Method | Syntax | Behavior after a ConfigMap update | Best for |
|---|---|---|---|
| env (single key) | env[].valueFrom.configMapKeyRef | Unchanged. Environment variables are set when the container starts, so you must restart it | A few switches and ports |
| envFrom (all keys) | envFrom[].configMapRef, optionally with prefix | Unchanged | 12-Factor style apps |
| volume | volumes[].configMap + volumeMounts | Eventually 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 + subPath | volumeMounts[].subPath | Never 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 undocan 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/Secret | Docker Compose | Azure App Configuration / Key Vault | |
|---|---|---|---|
| Storage | etcd (in-cluster) | .env / secrets files | Managed service, with versioning and auditing |
| Injection | env / files | env / /run/secrets | SDK, CSI driver, or ESO syncs into a Secret |
| Encryption | None by default; requires KMS configuration | None | HSM / managed keys |
Architecture diagram: how configuration flows from the apiserver to containers
Flowchart: reliable configuration release (checksum annotation pattern)
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.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
kubectl create configmap NAME | Create ConfigMap | --from-literal=K=V, --from-file=[key=]path, --from-env-file=.env |
kubectl create secret generic | Opaque Secret | Same as above; values are base64-encoded |
kubectl create secret tls | TLS certificate | --cert=tls.crt --key=tls.key |
kubectl create secret docker-registry | Image pull credentials | --docker-server --docker-username --docker-password |
... --dry-run=client -o yaml | Generate YAML without creating the object (essential for GitOps) | Use with kubectl apply -f - for idempotent updates |
kubectl rollout restart deploy/X | Add a kubectl.kubernetes.io/restartedAt annotation to trigger a rolling update | General 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)
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
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
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.
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
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.
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'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
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.
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.
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.
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.
Module 4 · Advanced Release Strategies
- 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.
What: Deployment rolling update parameters
| Field | Default | Rounding | Meaning |
|---|---|---|---|
strategy.rollingUpdate.maxSurge | 25% | Rounds up | How many Pods can be created above replicas during a rollout |
strategy.rollingUpdate.maxUnavailable | 25% | Rounds down | How many Pods can be unavailable during a rollout (both cannot be 0 at the same time) |
minReadySeconds | 0 | — | 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) |
progressDeadlineSeconds | 600 | — | If there is no progress for longer than this, the condition Progressing=False, reason=ProgressDeadlineExceeded is set. It does not roll back automatically. |
revisionHistoryLimit | 10 | — | 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(labelversion: blue) andapi-green, withversionincluded in the Service selector. Once green is fully ready and verified,kubectl patch svcchanges 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 runresume. You can also pause partway through a rollout as a simple canary. - PodDisruptionBudget (policy/v1):
minAvailableormaxUnavailable. Choose one. Values can be numbers or percentages. It only limits voluntary disruptions initiated through the Eviction API, such askubectl drain, cluster autoscaler scale-down, and AKS node upgrades. It does not protect againstkubectl delete podrun 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
| Strategy | Best for | Not suitable for |
|---|---|---|
| RollingUpdate | Most stateless services, and backward-compatible changes | Old and new versions cannot coexist (incompatible database schema) |
| Recreate | Cannot coexist, single instance, and downtime is acceptable | Needs continuous availability |
| Blue/green | Needs whole-environment rollback within seconds, and full verification before release | Tight resources, or stateful dependencies that are hard to dual-write |
| Canary | High-risk changes that need gradual verification with real traffic | Needs an exact 1% or per-user traffic splits (use Gateway API / Rollouts) |
Comparison with similar technologies
| K8s native | Argo Rollouts | Azure App Service deployment slots / ACA revisions | |
|---|---|---|---|
| Blue/green | Switch the selector manually | BlueGreen strategy + preview Service + automatic switching | slot swap |
| Canary | Replica ratio | Stepwise weights + metric analysis with automatic rollback | Percentage-based traffic split across revisions |
| Automatic rollback | None (CI has to judge rollout status) | Yes (AnalysisTemplate) | Partial support |
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
Flowchart: how the Eviction API and PDB interact during a drain
Interactive 1: rolling update calculator
Interactive 2: blue/green switch and canary ratio
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl rollout status deploy/X | Wait for the rollout to finish; exits non-zero on failure | --timeout=5m; CI gate |
kubectl rollout pause / resume | Pause/resume a rollout, batch template changes | Changes made while paused do not create a new RS |
kubectl rollout undo | Roll back to the previous or a specified revision | --to-revision=N |
kubectl create pdb | Create a PodDisruptionBudget | --selector=app=api --min-available=2 |
kubectl get pdb | Check ALLOWED DISRUPTIONS | When it is 0, drain is blocked |
kubectl patch svc | Blue/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)
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 versioncat <<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)
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"}}}'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"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
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.
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
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:
Official documentation
- Deployments (Rolling Update, Pausing, Progress Deadline)
- Specifying a Disruption Budget for your Application
- Disruptions
Video storyboard script (about 90 seconds)
This lesson cannot generate a video or MP3 directly, so it provides a storyboard and a narration script.
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.
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.
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.
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.
Module 5 · StatefulSet
- 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.
What: what a StatefulSet provides
| Guarantee | Implementation | Example (StatefulSet web, Service web, namespace shop) |
|---|---|---|
| Stable Pod names | Ordinals 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 DNS | The serviceName points to the headless Service (clusterIP: None), which creates A/AAAA records for each Pod | web-0.web.shop.svc.cluster.local |
| Stable storage | volumeClaimTemplates creates a separate PVC for each ordinal. When a Pod is recreated, it rebinds to the same PVC | data-web-0, data-web-1 |
| Ordered | podManagementPolicy: 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 0 | The 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: Kupdates 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 gateStatefulSetRecreateStrategy): 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) andwhenScaled(when scaling down) each takeRetain(default) orDelete. 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
| Deployment | StatefulSet | Operator (such as CloudNativePG) | |
|---|---|---|---|
| Pod name | Random | Fixed ordinal | Decided by the operator |
| Storage | Shared template volume | One PVC per replica | One PVC per instance + backup / WAL archiving |
| Failover | Stateless, replace directly | Only recreates a Pod with the same name in place | Automatically elects a primary, switches over, and rebuilds replicas |
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
Flowchart: OrderedReady creation and partitioned updates
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.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl get sts,pod,pvc -l app=X | View StatefulSet, Pods, and PVCs together | PVC name = template name-StatefulSet name-ordinal |
kubectl scale sts/X --replicas=N | Scale (in order) | Scale-down keeps PVCs by default |
kubectl patch sts X -p | Change partition / strategy | {"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}} |
kubectl rollout status/history/undo sts/X | StatefulSets also support rollout | Based on ControllerRevision |
kubectl get controllerrevision | View the StatefulSet's revision history objects | Similar 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)
kubectl get sc kubectl get secret db-cred
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION standard (default) rancher.io/local-path Delete WaitForFirstConsumer false
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
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;
SQLkubectl 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
mousekubectl 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
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.
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-alpine2. Delete the StatefulSet, but keep its Pods and PVCs.
kubectl delete sts web --cascade=orphan
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
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.
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.
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.
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.
Module 6 · DaemonSet
- 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).
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
| Category | Examples | Why one per node is required |
|---|---|---|
| Networking | kube-proxy, kindnet, Calico/Cilium agents, Azure CNI | Must program nftables/iptables/eBPF and routes on every node |
| Storage | CSI node plugins (such as the Azure Disk/File CSI node) | Mounting volumes must run on the node where the Pod is |
| Logging | Fluent Bit, Azure Monitor Agent (ama-logs) | Read the node's /var/log/pods |
| Monitoring | node-exporter, Datadog agent | Collect node-level metrics |
| Security | Falco, Defender for Containers sensor | Monitor 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
nodeAffinityinto 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, andkubectl drainneeds--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;maxSurgelets a new Pod start before the old one is deleted, and the two cannot both be 0), orOnDelete. 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-criticalis only for truly critical components.
Comparison with similar technologies
| DaemonSet | Static Pod | systemd service / VM extension | |
|---|---|---|---|
| Managed by | API declarative, rolling updates | kubelet reads files from a node directory (mirror Pods are read-only) | Node image or configuration management |
| Typical use | Node agents | kubeadm control-plane components | kubelet, containerd itself |
Architecture diagram: DaemonSet and nodes
Flowchart: when a new node joins
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.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
kubectl get ds -A | View all DaemonSets (DESIRED/CURRENT/READY/UP-TO-DATE) | -o wide shows images and selectors |
kubectl rollout status ds/X | Wait for the rollout to complete | -n kube-system |
kubectl get pod -l app=X -o wide | Confirm that every node has one | NODE column |
kubectl describe node | grep Taints | View node taints | Decide 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)
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.
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
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.
--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
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}}}'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:
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.
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.
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.
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.
Module 7 · Job and CronJob
- 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/.
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.
| Field | Default | Meaning |
|---|---|---|
completions | 1 | How many successful Pods are needed |
parallelism | 1 | Maximum number of Pods running at the same time (0 is equivalent to pausing; you can also use suspend: true) |
backoffLimit | 6 | Maximum number of retries after a failure. Retry intervals use exponential backoff (10s, 20s, 40s, …, capped at 6 minutes) |
activeDeadlineSeconds | None | Maximum total runtime for the Job. After the timeout, all Pods are terminated, with reason: DeadlineExceeded (takes precedence over backoffLimit) |
ttlSecondsAfterFinished | None | After the Job finishes (success or failure), the TTL controller automatically deletes the Job and its Pods after this many seconds |
completionMode | NonIndexed | Indexed: 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.FailJobfails immediately, without wasting retries.Ignoredoes not count toward backoffLimit, for example aDisruptionTargetcondition from being evicted by a node drain.Countis the default and counts the failure.FailIndexis 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.
maxFailedIndexessets 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):
Failedmeans replacement Pods are created only after the old Pods have fully terminated, so two replicas never run at the same time.
CronJob key fields
| Field | Description |
|---|---|
schedule | Standard 5-field cron: minute, hour, day, month, weekday. Macros such as @hourly and @daily are also supported. |
timeZone | IANA 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. |
concurrencyPolicy | Allow (default, runs may overlap), Forbid (skip this run if the previous one has not finished), Replace (cancel the previous run and start this one) |
startingDeadlineSeconds | How 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 / failedJobsHistoryLimit | Number of historical Jobs to keep. Default 3 / 1. |
suspend | Pauses 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/CronJob | Linux cron / systemd timer | Azure Container Apps Jobs / Functions timer triggers | |
|---|---|---|---|
| Failure retries | backoffLimit, podFailurePolicy | Write it yourself | Built-in retries |
| Parallelism | parallelism, Indexed | None | Parallel replicas |
| Where it runs | Any node in the cluster (subject to scheduling constraints) | Single machine | Managed |
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
Flowchart: the order in which the Job controller decides what to do when a Pod fails
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.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
kubectl create job NAME --image=IMG -- CMD | Quickly create a Job | Generate 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/Y | Trigger a CronJob manually, right now | For testing and catch-up runs |
kubectl wait --for=condition=complete job/X | Wait for completion (common in CI) | --timeout=10m; use condition=failed to wait for failure |
kubectl get jobs,cronjobs | Check status (COMPLETIONS, LAST SCHEDULE) | -w |
kubectl patch cronjob X -p '{"spec":{"suspend":true}}' | Pause scheduling | Maintenance 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)
kubectl get pod db-0.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
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
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
kubectl get jobs --sort-by=.metadata.creationTimestamp
kubectl get cronjob db-backup -o jsonpath='{.status.lastScheduleTime} {.status.lastSuccessfulTime}{"\n"}'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).
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'
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
- Jobs
- CronJob
- Handling retriable and non-retriable pod failures with Pod failure policy
- Automatic Cleanup for Finished Jobs
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.
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.
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.
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.
Module 8 · Scheduling: affinity · taints · topology spread
- 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.
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 point | Typical plugins | Purpose |
|---|---|---|
| PreFilter / Filter | NodeResourcesFit, NodeName, NodeUnschedulable, TaintToleration, NodeAffinity, InterPodAffinity, PodTopologySpread, VolumeBinding, VolumeZone, NodePorts | Filter: if any plugin rejects a node, that node is infeasible |
| PostFilter | DefaultPreemption | If no node is feasible, try to preempt lower-priority Pods |
| PreScore / Score | NodeResourcesFit (default LeastAllocated), NodeResourcesBalancedAllocation, ImageLocality, InterPodAffinity, NodeAffinity (preferred), TaintToleration (PreferNoSchedule), PodTopologySpread | Score: pick the best of the feasible nodes |
| Reserve / Permit / PreBind / Bind | VolumeBinding, DefaultBinder | Reserve 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
| Tool | Direction | Hard/soft | Example |
|---|---|---|---|
| nodeSelector | Pod → node labels (attract) | Hard | disktype: ssd |
| nodeAffinity | Pod → node labels, supports In/NotIn/Exists/DoesNotExist/Gt/Lt | requiredDuringSchedulingIgnoredDuringExecution (hard) / preferred… (soft, with weight 1–100) | Only nodes matching topology.kubernetes.io/zone in [a,b] |
| podAffinity | Pod → other Pods (attract) | Hard/soft | api and cache on the same node, to reduce latency |
| podAntiAffinity | Pod → other Pods (repel), where topologyKey defines what "same location" means | Hard/soft | Replicas of the same Deployment are not on the same hostname |
| taints / tolerations | Nodes 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 |
| topologySpreadConstraints | Spread evenly across topology domains | whenUnsatisfiable: DoNotSchedule (hard) / ScheduleAnyway (soft) | Spread evenly across two levels, zone and hostname, with maxSkew: 1 |
| PriorityClass | Sets 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
| Kubernetes | Docker Swarm | AWS ECS | |
|---|---|---|---|
| Node constraints | nodeSelector/nodeAffinity | placement.constraints | placement constraints |
| Spread | topologySpread / antiAffinity | placement.preferences spread | spread placement strategy |
| Repel | taints/tolerations | No direct equivalent | No direct equivalent |
Architecture diagram: scheduling cycle
Illustration: topology spread (maxSkew 1)
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).
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
kubectl label node N k=v | Label a node | k- to remove |
kubectl taint node N k=v:NoSchedule | Add a taint | Add - at the end to remove: k=v:NoSchedule- |
kubectl cordon / uncordon N | Mark unschedulable / restore | Does not affect running Pods |
kubectl drain N | cordon + evict through the Eviction API | --ignore-daemonsets --delete-emptydir-data --timeout=5m --pod-selector |
kubectl get events --field-selector reason=FailedScheduling | Check why scheduling failed | -A --sort-by=.lastTimestamp |
kubectl get pod -o wide | NODE and NOMINATED NODE columns | Shows nominated during preemption |
kubectl get priorityclass | View priority classes | globalDefault |
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.
| Snippet | Meaning | Corresponding plugin / action |
|---|---|---|
0/3 nodes are available | All 3 nodes were rejected by Filter | The counts below add up to the number of nodes (each node lists only its first rejection reason) |
untolerated taint {…} | Untolerated taint | TaintToleration: add a toleration or change nodes |
Insufficient cpu/memory | requests do not fit | NodeResourcesFit: lower requests or add capacity |
didn't match Pod's node affinity/selector | Node labels do not match | NodeAffinity: check label spelling |
didn't match pod anti-affinity rules | Anti-affinity conflict | InterPodAffinity: replicas > nodes? Change to preferred |
didn't match pod topology spread constraints | Would break maxSkew | PodTopologySpread: change to ScheduleAnyway or add domains |
node(s) were unschedulable | Node is cordoned | NodeUnschedulable: uncordon |
volume node affinity conflict | PV is bound to a node or zone elsewhere | VolumeBinding (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)
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
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-worker2cat <<'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
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-demokubectl 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.
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 disktype0/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.
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
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:
Official documentation
- Kubernetes Scheduler
- Scheduling Framework
- Assigning Pods to Nodes
- Taints and Tolerations
- Pod Topology Spread Constraints
- Pod Priority and Preemption
- Safely Drain a Node
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.
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.
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.
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.
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.
Command cheat sheet
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/XRollouts 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.localDaemonSet
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
| Symptom | What to check first | Common causes |
|---|---|---|
| Pending | kubectl describe pod, look for FailedScheduling | requests too large, taints, affinity/topology constraints, unbound PVC, volume node affinity |
| OOMKilled / Exit 137 | lastState.terminated.reason, kubectl top | limits.memory too small, memory leak, heap size not adapted to the container |
| High latency, but average CPU is not high | Check cpu.stat on the node for nr_throttled | CPU limit throttling |
| Running but 0/1 | describe shows Readiness probe failed | Wrong probe path or port, or a dependency is unavailable |
| Repeated restarts (liveness) | Events show Liveness probe failed | Slow startup without a startupProbe, timeout too short, liveness check depends on other services |
| CreateContainerConfigError | describe pod | ConfigMap/Secret or key does not exist |
| Config change not taking effect | Check the injection method | env/subPath are not hot-reloaded, so a rollout is needed |
| Rollout stuck | rollout status, Pod events of the new ReplicaSet | ProgressDeadlineExceeded, image, probes, resources |
| drain stuck | kubectl get pdb -A | PDB does not allow it, replacement Pod Pending |
| Job not completing | describe job, logs of failed Pods | BackoffLimitExceeded, 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
shop namespace of the kind cluster lab, and use a drain drill to prove "zero downtime."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.
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.
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
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.
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.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
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| Kubernetes version | 1.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 notes | MemoryQoS 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 stages | InPlacePodVerticalScaling: 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 policy | podFailurePolicy v1.31 GA (requires restartPolicy Never). Indexed Job v1.24 GA. CronJob timeZone v1.27 GA. | Jobs · CronJob |
| metrics-server | Latest 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 |
| kind | v0.33.0, default kindest/node:v1.37.0. Default StorageClass standard (rancher.io/local-path, WaitForFirstConsumer). | kind releases |
| Resources and QoS | QoS classification rules, eviction ordering, cgroup v2 mapping | Resource Management · Pod QoS · Node-pressure Eviction |
| OOM/CPU lab images | polinux/stress (memory example) and vish/stress (CPU example) come from the official task documentation | Assign Memory Resources · Assign CPU Resources |
| Probes and termination | Default probe parameters, termination flow, preStop sleep | Probes · Pod Lifecycle |
| Scheduling | Scheduling framework extension points, default plugins, default topology spread constraints, preemption | Scheduling 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/zonelabel. - 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.