Part 12 · Kubernetes · 12.3

8 lab Kubernetes failure và operations

Dùng local hoặc managed cluster phù hợp; mỗi lab phải tạo được failure có kiểm soát, debug theo evidence, phục hồi hệ thống và lưu lại manifests, events, conditions, metrics, timeline cùng recovery evidence.

Safety rule: chạy trong namespace/lab cluster riêng. Trước khi inject lỗi, ghi baseline và rollback path. Không dùng production workload thật cho các bước delete, deny, drain, OOM, bad rollout hoặc snapshot/restore.

Lab 01 · Reconciliation trace

Apply Deployment rồi quan sát chuỗi Deployment → ReplicaSet → Pod → scheduler → kubelet → EndpointSlice bằng get/watch/events/ownerReferences. Scale hoặc delete Pod và giải thích vì sao hệ thống converge về desired state.

Objective

Chứng minh Kubernetes vận hành theo reconciliation thay vì “chạy một lần”, và phân biệt desired state, observed state với controller ownership.

Prerequisites

Steps

  1. Apply Deployment + Service và lưu YAML thực tế bằng kubectl get ... -o yaml.
  2. Watch Deployment, ReplicaSet, Pod và EndpointSlice song song.
  3. Đọc ownerReferences từ Pod lên ReplicaSet rồi Deployment; ghi scheduler/node assignment và readiness.
  4. Scale Deployment từ 2 lên 4 replicas, sau đó delete một Pod đang Ready và quan sát controller tạo replacement.
kubectl get deploy,rs,pod -w
kubectl get events --sort-by=.lastTimestamp
kubectl get pod <pod> -o jsonpath='{.metadata.ownerReferences}'
kubectl get endpointslice -l kubernetes.io/service-name=<service> -w

Failure injection & verification

Delete Pod thủ công. Verify replica count quay lại desired state, Pod mới có owner đúng và EndpointSlice chỉ publish endpoint đủ điều kiện theo implementation/readiness.

Expected evidence: timeline scale/delete/recreate, owner chain, Pod UID cũ/mới, events, Deployment conditions và EndpointSlice trước/sau.

Lab 02 · Pod failure matrix

Tạo bad image, bad command, missing config, permission, liveness loop và CrashLoop. Debug current/previous logs, last state và backoff thay vì chỉ restart Pod.

Objective

Nhận diện failure class bằng status/conditions/events/logs và chọn đúng evidence cho container chưa start, đang crash hoặc bị probe kill.

Prerequisites

Một Deployment mẫu có ConfigMap/Secret test, probes và quyền đọc logs/events.

Steps

  1. Lần lượt inject image tag không tồn tại, command sai, missing ConfigMap/Secret key và filesystem/UID permission không phù hợp.
  2. Tạo container exit non-zero để quan sát CrashLoopBackOff; sau đó cấu hình liveness probe luôn fail.
  3. Với mỗi lỗi, ghi status.containerStatuses, state, lastState, restart count, events, current logs và --previous.
kubectl describe pod <pod>
kubectl logs <pod> -c <container>
kubectl logs <pod> -c <container> --previous
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses}'

Failure injection & verification

Không sửa nhiều biến cùng lúc. Với từng case, sửa đúng root cause rồi verify Pod Ready ổn định và restart count không tiếp tục tăng.

Expected evidence: một matrix symptom → signal → root cause → fix; ảnh/chụp output ImagePullBackOff/CrashLoopBackOff/probe failure và logs trước/sau.

Lab 03 · Resources/OOM/Pending

Thực hành requests/limits/QoS, CPU throttle và memory OOM; tạo Pending bằng affinity/taint/insufficient resource. Không chỉ tăng limit — phải đo heap/native/traffic và xác định capacity bottleneck.

Objective

Liên hệ scheduler admission, runtime enforcement và application behavior với request/limit thay vì nhìn mỗi trạng thái Pod.

Prerequisites

Steps

  1. Đặt requests/limits khác nhau, ghi QoS class và node allocatable/requested.
  2. Tạo memory pressure vượt limit để quan sát OOMKilled/lastState; tạo CPU-bound load và so latency/throttle signals nếu runtime/metrics hỗ trợ.
  3. Tạo Pending bằng request lớn hơn capacity hoặc constraint affinity/taint không thỏa; đọc scheduler events.
  4. Phân biệt application leak/working-set tăng, native/off-heap, traffic burst và cấu hình limit quá thấp.

Failure injection & verification

Fix bằng thay đổi có giả thuyết: giảm working set, điều chỉnh concurrency/cache, request/limit hoặc capacity. Verify latency, memory trend, OOM count và Pending reason đã ổn định.

Expected evidence: requests/limits/QoS table, scheduler event cho Pending, OOMKilled lastState, before/after resource/latency graph hoặc metrics snapshot.

Lab 04 · Zero-error rollout

Giữ continuous traffic trong rollout; kiểm tra startup/readiness/TERM, maxSurge/maxUnavailable/minReadySeconds và schema compatible. Đo errors/in-flight/rollout conditions rồi inject bad release và rollback.

Objective

Chứng minh “Deployment Complete” không đồng nghĩa zero-error; phối hợp lifecycle, readiness, termination, capacity và backward-compatible dependency.

Prerequisites

Steps

  1. Baseline request rate/error/latency và số Ready endpoints.
  2. Cấu hình startup/readiness phù hợp, graceful termination và rolling update strategy; rollout good version.
  3. Quan sát Deployment conditions, ReplicaSets, Pod readiness, in-flight requests và error rate.
  4. Inject bad image/config hoặc version làm readiness fail; xác định failure window và blast radius.
  5. Rollback về revision tốt, verify endpoint population và traffic hồi phục.
kubectl rollout status deployment/<name>
kubectl rollout history deployment/<name>
kubectl rollout undo deployment/<name>
kubectl get deploy,rs,pod -w
Expected evidence: traffic/error timeline, rollout conditions, old/new ReplicaSet counts, bad release symptom, rollback command và recovery timestamp.

Lab 05 · Network forensic

Tạo lần lượt Service selector mismatch, wrong targetPort/listen, DNS, no endpoints, default-deny NetworkPolicy và Gateway route/TLS. Debug từng hop thay vì kết luận chung là “network lỗi”.

Objective

Khoanh vùng request path từ client → DNS → route/Gateway → Service → EndpointSlice → Pod listener/policy.

Prerequisites

Steps

  1. Baseline direct Pod IP, Service DNS và Service ClusterIP.
  2. Làm sai selector rồi verify EndpointSlice rỗng/không match; sửa lại.
  3. Làm sai targetPort hoặc app listen port; kiểm tra listener trong Pod.
  4. Áp default-deny NetworkPolicy rồi thêm allow rule tối thiểu.
  5. Nếu có Gateway, inject hostname/path/backend/TLS mismatch và theo dõi status conditions của Gateway/Route.

Failure injection & verification

Mỗi lần chỉ thay một hop. Sau fix, verify từ cùng client, cùng hostname/path và ghi rõ DNS resolution, endpoints, policy và route status.

Expected evidence: hop-by-hop table với symptom, command, expected/actual; EndpointSlice output; DNS answer; NetworkPolicy before/after; Gateway/Route conditions nếu áp dụng.

Lab 06 · Stateful storage

Dùng StatefulSet + headless Service + PVC. Delete/reschedule Pod, mô phỏng zone/attach failure khi môi trường hỗ trợ, thực hiện snapshot/restore và kiểm tra reclaim policy; ghi rõ RPO/RTO limitations.

Objective

Phân biệt Pod identity, volume identity, scheduling topology, data durability và backup/restore.

Prerequisites

Steps

  1. Deploy StatefulSet với headless Service và volumeClaimTemplates; ghi Pod ordinal, PVC/PV binding.
  2. Write dữ liệu marker, delete Pod và verify Pod ordinal trở lại với đúng persistent data.
  3. Nếu có topology constraints, tạo tình huống Pod không attach/mount được và đọc events từ Pod/PVC/PV/VolumeAttachment.
  4. Tạo snapshot/backup theo capability, thay đổi dữ liệu, restore sang volume mới và verify checksum.
  5. Kiểm tra StorageClass/PV reclaim policy trước khi delete PVC/PV.

Failure injection & verification

Không coi snapshot là backup hoàn chỉnh nếu chưa test restore. Ghi recovery point thực tế, recovery time và dependency ngoài volume như Secret/config/schema.

Expected evidence: identity mapping Pod↔PVC↔PV, data checksum trước/sau reschedule, attach/mount events, snapshot/restore proof, RPO/RTO và reclaim behavior.

Lab 07 · Security baseline

Áp dụng dedicated ServiceAccount/RBAC, non-root/read-only/drop capabilities/seccomp, Secret external injection, quotas và admission policy theo hướng audit → enforce. Phải chứng minh các action không được phép thực sự bị deny.

Objective

Xây baseline least-privilege có thể kiểm chứng cho workload và giảm blast radius khi container bị compromise.

Prerequisites

Steps

  1. Tạo ServiceAccount riêng, Role chỉ có verbs/resources cần thiết và RoleBinding.
  2. Verify bằng kubectl auth can-i --as=system:serviceaccount:... cho allowed và denied actions.
  3. Cấu hình non-root, read-only root filesystem khi app hỗ trợ, drop capabilities và seccomp profile phù hợp.
  4. Inject Secret qua cơ chế cluster/external secret phù hợp môi trường; không in Secret vào logs/evidence.
  5. Thêm ResourceQuota/LimitRange nếu phù hợp; thử Pod vi phạm policy ở audit/warn rồi chuyển enforce sau khi remediation.

Failure injection & verification

Thử đọc Secret ngoài scope, tạo privileged Pod hoặc action RBAC không được grant. Verify deny xảy ra ở đúng control plane layer và workload hợp lệ vẫn chạy.

Expected evidence: RBAC matrix, denied can-i/API request, Pod security context, admission warning/deny và checklist không leak credential.

Lab 08 · Scaling/disruption game day

Chạy HPA theo CPU hoặc custom queue metric, đưa vào node provisioning delay, DB saturation, PDB/drain/node loss. Tune stabilization/max replicas và load shedding; cuối cùng viết incident runbook.

Objective

Chứng minh autoscaling chỉ hữu ích khi dependency và cluster capacity theo kịp; luyện phản ứng disruption mà không khuếch đại overload.

Prerequisites

Steps

  1. Baseline replicas, utilization, request rate, latency/error, queue age và DB saturation signal.
  2. Tăng load để HPA scale; ghi delay từ metric → desired replicas → scheduled/Ready capacity.
  3. Tạo node provisioning/scheduling delay hoặc cordon/drain node test; quan sát Pending và available replicas.
  4. Tạo downstream DB saturation để chứng minh tăng replicas có thể làm overload nặng hơn.
  5. Thử PDB với drain/node loss; tune stabilization window/max replicas và thêm load shedding/backpressure.
  6. Viết runbook: detection, immediate containment, capacity action, rollback/recovery và post-incident evidence.

Failure injection & verification

Không drain production node. Verify hệ thống có bounded recovery, không scale vô hạn và SLO phục hồi sau khi bỏ fault/load.

Expected evidence: HPA desired/current replica timeline, Pending/provisioning delay, PDB/drain result, dependency saturation graph/snapshot, load-shedding effect và incident runbook.

Rubric

MứcTiêu chíEvidence tối thiểu
1Workload chạy happy path.Manifest + baseline output chứng minh workload/Service hoạt động.
2Có probes/resources/security và systematic debug.Failure được inject có kiểm soát, root cause dựa trên events/logs/status/metrics, có fix + verification.
3 · SeniorChứng minh reconciliation, failure, rollout, scaling và recovery.Có timeline, failure window/blast radius, capacity/security signal, rollback/recovery evidence và trade-off/RPO/RTO khi phù hợp.
Completion rule: một lab chưa hoàn tất nếu chỉ “fix được”. Phải chỉ ra evidence nào chứng minh root cause, evidence nào chứng minh recovery, và điều gì sẽ được monitor/alert nếu tình huống tương tự xảy ra ở production.
Tài liệu tham chiếu: Deployments · Debug Running Pods · Services, Load Balancing, and Networking · Pod Security Standards · Security Checklist