Kubernetes Labs · Lab 4 of 9
Probes, Resources and Autoscaling: Keeping Apps Healthy Under Load
Add startup, readiness and liveness probes, watch a failing pod leave its Service, see a container killed for using too much memory, autoscale with metrics-server and an HPA, block a node drain with a PodDisruptionBudget, and push a broken image without any downtime.
- Environment
- Kubernetes
- Level
- Intermediate
- Time
- About 60 min
- Cost
- Free
You will build
An app that only receives traffic when it is ready, scales from 1 to 5 pods under load, survives node maintenance, and can't be taken down by a bad release.
Before you start
Kubernetes keeps pods running, but only you can tell it what "healthy" means and how much CPU and memory a pod needs. This lab wires up the four mechanisms that make apps reliable in production:
- Probes tell the kubelet when a container has started, whether it can take traffic, and whether it is stuck.
- Requests and limits tell the scheduler what to reserve and the kernel what to enforce. Together they decide
the pod's QoS class:
Guaranteed(requests = limits),Burstable(requests set, limits higher or missing) orBestEffort(nothing set, first to be evicted). - The Horizontal Pod Autoscaler (HPA) changes the number of replicas from live metrics.
- PodDisruptionBudgets and the rolling update strategy limit how many pods voluntary operations (node drains, rollouts) may take away at once.
Every output below was captured from a real run on kind 0.33 with Kubernetes 1.37. Pod names, IP addresses, ages and cluster ports are generated, so yours will differ; everything else should match.
Project structure
health-and-scaling/ ├── app.yaml # namespace scale, Deployment web with probes and a safe rollout strategy, Service, PDB ├── oom.yaml # a pod that uses more memory than its limit └── hpa.yaml # CPU-heavy demo app + HorizontalPodAutoscaler
Steps
-
1Install metrics-server
The HPA and
kubectl topread CPU and memory from metrics-server, which collects them from each kubelet. Managed clusters usually include it; on kind you install it and allow the kubelet's self-signed certificates with--kubelet-insecure-tls(never do that in production).Run kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml 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 deployment/metrics-server kubectl top nodesExpected output
serviceaccount/metrics-server created ... apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created deployment.apps/metrics-server patched ... deployment "metrics-server" successfully rolled out NAME CPU(cores) CPU(%) MEMORY(bytes) MEMORY(%) lab-k8s-local-control-plane 178m 1% 1321Mi 7% lab-k8s-local-worker 32m 0% 261Mi 1% lab-k8s-local-worker2 28m 0% 223Mi 1%
Hint
If
kubectl topsays metrics are not available yet, wait a minute: the first scrape takes up to 60 seconds. -
2An app with probes, a safe rollout strategy and a disruption budget
- The startupProbe gives the app up to 30 seconds (15 × 2s) to start before the other probes begin.
- The readinessProbe calls
/health; after two failures the pod is marked not ready and removed from the Service, but not restarted. - The livenessProbe only checks that the port accepts connections; three failures restart the container. Keep liveness simpler than readiness, or a slow dependency makes Kubernetes restart healthy pods.
maxSurge: 1, maxUnavailable: 0means a rollout adds a new pod before removing an old one.- The PodDisruptionBudget keeps at least one pod up during voluntary disruptions such as node drains.
app.yaml apiVersion: v1 kind: Namespace metadata: name: scale --- apiVersion: apps/v1 kind: Deployment metadata: name: web namespace: scale spec: replicas: 2 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 # one extra pod during an update maxUnavailable: 0 # never drop below the desired count selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: whoami image: traefik/whoami:v1.11.0 ports: - name: http containerPort: 80 startupProbe: # gives a slow start time before the other probes begin httpGet: path: /health port: http periodSeconds: 2 failureThreshold: 15 readinessProbe: # failing: removed from the Service, not restarted httpGet: path: /health port: http periodSeconds: 3 failureThreshold: 2 livenessProbe: # failing: the container is restarted tcpSocket: port: http periodSeconds: 10 failureThreshold: 3 resources: requests: cpu: 50m memory: 32Mi limits: memory: 64Mi --- apiVersion: v1 kind: Service metadata: name: web namespace: scale spec: selector: app: web ports: - name: http port: 80 targetPort: http --- apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: web namespace: scale spec: minAvailable: 1 selector: matchLabels: app: web -
3Apply and check QoS and the budget
Run kubectl apply -f app.yaml kubectl -n scale rollout status deployment/web kubectl -n scale get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass kubectl -n scale get pdbExpected output
namespace/scale created deployment.apps/web created service/web created poddisruptionbudget.policy/web created ... deployment "web" successfully rolled out NAME QOS web-86567c7c8-d542v Burstable web-86567c7c8-j7smg Burstable NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE web 1 N/A 1 3s
Check:Burstable: requests are set and the memory limit is higher than the request. -
4Make one pod unhealthy and watch it leave the Service
This demo server lets you set its health status with a POST to
/health. Make one pod return 500: its readiness probe fails, the EndpointSlice marks itready=false, and the Service stops sending it traffic. It is not restarted. Set it back to 200 and it returns.Run POD_IP=$(kubectl -n scale get pod -l app=web -o jsonpath='{.items[0].status.podIP}') kubectl -n scale run sick --rm -i --restart=Never --image=busybox:1.38.0 -- wget -qO- --post-data=500 http://$POD_IP/health # wait about 10 seconds kubectl -n scale get pods kubectl -n scale get endpointslices -l kubernetes.io/service-name=web -o jsonpath='{range .items[0].endpoints[*]}{.addresses[0]} ready={.conditions.ready}{"\n"}{end}' kubectl -n scale get events --field-selector reason=Unhealthy | tail -2Expected output
pod "sick" deleted from scale namespace NAME READY STATUS RESTARTS AGE web-86567c7c8-d542v 0/1 Running 0 22s web-86567c7c8-j7smg 1/1 Running 0 22s 10.244.1.19 ready=true 10.244.2.19 ready=false LAST SEEN TYPE REASON OBJECT MESSAGE 1s Warning Unhealthy pod/web-86567c7c8-d542v Readiness probe failed: HTTP probe failed with statuscode: 500
Check:One pod is
0/1withRESTARTS 0, and its IP isready=false. -
5Make it healthy again
Run kubectl -n scale run heal --rm -i --restart=Never --image=busybox:1.38.0 -- wget -qO- --post-data=200 http://$POD_IP/health # wait about 10 seconds kubectl -n scale get podsExpected output
pod "heal" deleted from scale namespace NAME READY STATUS RESTARTS AGE web-86567c7c8-d542v 1/1 Running 0 32s web-86567c7c8-j7smg 1/1 Running 0 32s
-
6Exceed a memory limit
CPU over the limit is only slowed down (throttled); memory over the limit can't be taken back, so the kernel kills the container: OOMKilled, exit code 137. The kubelet restarts it, it is killed again, and the restarts back off. Size memory limits from real usage plus headroom.
oom.yaml # Tries to use 150 MiB with a 64 MiB limit: the kernel kills it (OOMKilled). apiVersion: v1 kind: Pod metadata: name: memory-hog namespace: scale spec: containers: - name: stress image: polinux/stress:1.0.4 command: ["stress", "--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"] resources: requests: memory: 32Mi limits: memory: 64Mi -
7Watch it get killed
Run kubectl apply -f oom.yaml # wait about 20 seconds kubectl -n scale get pod memory-hog kubectl -n scale get pod memory-hog -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason} exit={.status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}' kubectl -n scale delete pod memory-hogExpected output
pod/memory-hog created NAME READY STATUS RESTARTS AGE memory-hog 0/1 OOMKilled 2 (23s ago) 25s OOMKilled exit=137 pod "memory-hog" deleted from scale namespace
Hint
You may see
CrashLoopBackOffinstead ofOOMKilledin the STATUS column: that's the restart back-off. The jsonpath line shows the real reason. -
8An app to autoscale
Each request to this demo app burns CPU. The HPA keeps average CPU at 50% of the request (200m), adding pods up to 5. Without a CPU request the HPA can't compute a percentage, which is one more reason to set requests everywhere.
The Horizontal Pod Autoscaler control loop hpa.yaml # A CPU-heavy demo app (each request burns CPU) and an autoscaler that keeps average CPU near 50%. apiVersion: apps/v1 kind: Deployment metadata: name: php-apache namespace: scale spec: selector: matchLabels: app: php-apache template: metadata: labels: app: php-apache spec: containers: - name: php-apache image: registry.k8s.io/hpa-example ports: - containerPort: 80 resources: requests: cpu: 200m # HPA percentages are relative to the request limits: cpu: 500m --- apiVersion: v1 kind: Service metadata: name: php-apache namespace: scale spec: selector: app: php-apache ports: - port: 80 --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: php-apache namespace: scale spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: php-apache minReplicas: 1 maxReplicas: 5 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 50 -
9Apply it and check the HPA
Run kubectl apply -f hpa.yaml kubectl -n scale rollout status deployment/php-apache # wait about 40 seconds for the first metrics kubectl -n scale get hpaExpected output
deployment.apps/php-apache created service/php-apache created horizontalpodautoscaler.autoscaling/php-apache created Waiting for deployment "php-apache" rollout to finish: 0 of 1 updated replicas are available... deployment "php-apache" successfully rolled out NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE php-apache Deployment/php-apache cpu: 0%/50% 1 5 1 46s
-
10Generate load and watch it scale out
A busybox pod calls the app in a loop. Within a minute CPU jumps far above the target and the HPA adds pods; as more pods share the load, CPU per pod falls back towards 50%.
Run kubectl -n scale run load --image=busybox:1.38.0 --restart=Never -- /bin/sh -c "while true; do wget -q -O- http://php-apache; done" for i in $(seq 1 9); do sleep 20; kubectl -n scale get hpa php-apache --no-headers; done kubectl -n scale get pods -l app=php-apacheExpected output
pod/load created php-apache Deployment/php-apache cpu: 0%/50% 1 5 1 71s php-apache Deployment/php-apache cpu: 174%/50% 1 5 4 91s php-apache Deployment/php-apache cpu: 115%/50% 1 5 5 111s php-apache Deployment/php-apache cpu: 69%/50% 1 5 5 2m11s php-apache Deployment/php-apache cpu: 71%/50% 1 5 5 2m31s php-apache Deployment/php-apache cpu: 68%/50% 1 5 5 2m51s php-apache Deployment/php-apache cpu: 69%/50% 1 5 5 3m11s php-apache Deployment/php-apache cpu: 67%/50% 1 5 5 3m31s php-apache Deployment/php-apache cpu: 73%/50% 1 5 5 3m51s NAME READY STATUS RESTARTS AGE php-apache-6465bb9b65-cqr4w 1/1 Running 0 3m51s php-apache-6465bb9b65-ctw5r 1/1 Running 0 2m36s php-apache-6465bb9b65-lxn9w 1/1 Running 0 2m21s php-apache-6465bb9b65-qqn89 1/1 Running 0 2m36s php-apache-6465bb9b65-xh57f 1/1 Running 0 2m36s
Check:Replicas go 1 → 4 → 5 and stay at the maximum while CPU is still above 50%.
-
11Stop the load
Scaling down is deliberately slow: the HPA waits for 5 minutes of lower usage (the stabilization window) so a short dip doesn't remove pods you will need again. Check back with
kubectl -n scale get hpalater.Run kubectl -n scale delete pod loadExpected output
pod "load" deleted from scale namespace
-
12Try to drain a node that holds your last replica
kubectl drainevicts everything from a node before maintenance, and evictions respect PodDisruptionBudgets. Scale web down to one pod: the budget now allows zero disruptions, so the drain evicts every other pod but keeps retrying on web, and gives up after the timeout. The lesson: a single replica plus a PDB blocks node upgrades. Run two or more.Run kubectl -n scale scale deployment/web --replicas=1 kubectl -n scale get pods -l app=web -o wide kubectl -n scale get pdb web kubectl drain lab-k8s-local-worker2 --ignore-daemonsets --delete-emptydir-data --timeout=40s # use the node from the line above kubectl uncordon lab-k8s-local-worker2 kubectl -n scale scale deployment/web --replicas=2Expected output
deployment.apps/web scaled NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-86567c7c8-d542v 1/1 Running 0 5m58s 10.244.2.19 lab-k8s-local-worker2 <none> <none> NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE web 1 N/A 0 5m58s node/lab-k8s-local-worker2 cordoned Warning: ignoring DaemonSet-managed Pods: kube-system/kindnet-qcgg9, kube-system/kube-proxy-bvqrp evicting pod scale/web-86567c7c8-d542v evicting pod scale/php-apache-6465bb9b65-cqr4w evicting pod scale/php-apache-6465bb9b65-ctw5r evicting pod scale/php-apache-6465bb9b65-lxn9w error when evicting pods/"web-86567c7c8-d542v" -n "scale" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget. pod/php-apache-6465bb9b65-ctw5r evicted pod/php-apache-6465bb9b65-cqr4w evicted pod/php-apache-6465bb9b65-lxn9w evicted evicting pod scale/web-86567c7c8-d542v error when evicting pods/"web-86567c7c8-d542v" -n "scale" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget. ... error: unable to drain node "lab-k8s-local-worker2" due to error: error when evicting pods/"web-86567c7c8-d542v" -n "scale": global timeout reached: 40s, continuing command... There are pending nodes to be drained: lab-k8s-local-worker2 error when evicting pods/"web-86567c7c8-d542v" -n "scale": global timeout reached: 40s node/lab-k8s-local-worker2 uncordoned deployment.apps/web scaled
Check:Every other pod was evicted; web was refused with
would violate the pod's disruption budget. -
13Release a broken image without downtime
Set an image tag that doesn't exist. Because
maxUnavailableis 0, Kubernetes first starts one new pod; it never becomes ready, so no old pod is removed and the Service keeps both working pods. The rollout just stops.rollout statuswith a timeout is how a pipeline notices and stops.A safe rolling update with a bad image Run kubectl -n scale set image deployment/web whoami=traefik/whoami:v9.9.9 kubectl -n scale rollout status deployment/web --timeout=45s kubectl -n scale get pods -l app=web kubectl -n scale get endpointslices -l kubernetes.io/service-name=web -o jsonpath='{range .items[0].endpoints[*]}{.addresses[0]} ready={.conditions.ready}{"\n"}{end}' kubectl -n scale rollout undo deployment/web kubectl -n scale rollout status deployment/webExpected output
deployment.apps/web image updated Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated... error: timed out waiting for the condition NAME READY STATUS RESTARTS AGE web-85dbd57d5b-9cmfn 0/1 ImagePullBackOff 0 45s web-86567c7c8-d542v 1/1 Running 0 7m33s web-86567c7c8-fqh7w 1/1 Running 0 55s 10.244.2.19 ready=true 10.244.1.28 ready=true 10.244.2.27 ready=false Warning: resource deployments/web was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, which may cause unexpected behavior on future 'kubectl apply' operations. Consider using 'kubectl apply' with your previous configuration file instead. deployment.apps/web rolled back deployment "web" successfully rolled out
Check:Two old pods stay
Runningand ready the whole time; only the new pod fails. -
14Clean up
Keep metrics-server and the cluster for the next labs.
Run kubectl delete namespace scaleExpected output
namespace "scale" deleted
In production
These settings are where most production incidents are prevented or caused. The defaults (no probes, no
requests, maxUnavailable: 25%) are not safe for real traffic.
What changes
| In this lab | In production |
|---|---|
| Probes on a demo endpoint | Readiness checks what the app needs to serve (without calling every dependency); liveness stays simple |
| Requests and limits guessed | Requests set from measured usage (metrics, VPA recommendations), memory limits with headroom, reviewed regularly |
| HPA on CPU only | HPA on CPU plus request rate or queue length (custom/external metrics, KEDA), with sensible min replicas |
| Fixed node count | Cluster Autoscaler or Karpenter adds nodes when pods can't be scheduled |
| A rollout stopped by a timeout in your terminal | The pipeline waits on rollout status and rolls back automatically; progressive delivery (Argo Rollouts, Flagger) for risky changes |
| One replica for the drain demo | At least two replicas, spread across zones, with a PodDisruptionBudget |
Probes: common mistakes
- Liveness checking a database: the database blips, every pod restarts at once, the outage gets worse.
- No startup probe for slow starters: liveness kills the app before it finishes starting.
- Readiness that always returns 200: pods get traffic during startup and shutdown.
Production checklist
- Every container has CPU and memory requests and a memory limit based on real usage
- Readiness and liveness probes on every serving container; startup probes for slow starters
- Deployments use
maxUnavailable: 0(or a small value) and aprogressDeadlineSeconds - User-facing workloads run two or more replicas with a PodDisruptionBudget and topology spread
- HPAs have a sensible
minReplicas, and node autoscaling can supply the capacity they ask for - Alerts on OOMKilled containers, restart loops, pending pods and HPAs at their maximum
- CI waits for
rollout statusand rolls back on failure
Learn the concepts
- Liveness, Readiness and Startup Probes · Kubernetes Tutorial
- Resource Requests and Limits · Kubernetes Tutorial
- Horizontal Pod Autoscaling · Kubernetes Tutorial
- Rolling Updates and Rollbacks · Kubernetes Tutorial
- Troubleshooting Pods · Kubernetes Tutorial
- Kubernetes in Production · Course
Preparing for the CKA or CKS exam? Practice tests and mock exams →