Kubernetes Hour 6: Production Operations: Scaling, Upgrades and Troubleshooting

Treat the shop app from the first 5 hours as a production service: pick the right delivery tools, use HPA and node scaling to handle load, use metrics, logs and events to locate problems, understand kubelet eviction and node shutdown, upgrade with zero downtime, back up etcd and renew certificates, compare the three managed platforms, and troubleshoot with one master decision tree
Kubernetes v1.37.1Helm 4.3.2Argo CD v3.6 · Flux v2.10AKS 1.37 GA · EKS 1.37 · GKEVerified against official docs · 2026-11
Overall learning goals
  • Explain which link in the delivery chain Helm, Kustomize and GitOps each solve. Write a minimal overlay, use helm upgrade --install, and know where to go deeper: the Helm and Argo CD courses.
  • Work out the HPA desired replica count by hand. Configure behavior (stabilization window, tolerance), and understand the 1.37 scale-to-zero Beta. Tell apart HPA / VPA / KEDA / Cluster Autoscaler / Karpenter / AKS NAP.
  • Build three troubleshooting threads (metrics, logs and events), and use the three kubectl debug modes and profiles with confidence.
  • Explain the signals, thresholds and ordering of kubelet node-pressure eviction, configure graceful node shutdown, and tell apart the six termination paths: delete / Eviction API / preemption / node pressure / taint-based eviction / OOM.
  • Plan cluster upgrades within the version skew policy, check for deprecated APIs, and complete a zero-downtime upgrade of the control plane and node pools (surge + PDB) on AKS.
  • For self-managed clusters, take an etcd snapshot, verify it and rehearse a restore; check and renew kubeadm certificates; and know what the managed platforms do for you.
  • Compare AKS / EKS / GKE on responsibility boundaries, networking, identity, upgrades and scaling, and use one master decision tree to troubleshoot all the common failures you hit in the 6 hours.

1-hour timetable

#TimeModuleCore contentAnimation / interactiveLab
0Before classWarm-up (Helm · AKS setup)Reuse the kind lab cluster and shop; metrics-server; Helm 4; create the AKS aks-lab (1.36, for the upgrade lab), ACR, kubelogin—az aks create / get-credentials
100–06Production delivery toolchain overviewThe roles of Helm vs Kustomize vs GitOps and how they combine, a minimal overlay, a minimal helm install, pull-based reconciliation, where to go deeperPath comparison of the three delivery methodsDeploy the same api once with apply -k and once with Helm
206–14AutoscalingHPA v2 algorithm and behavior, tolerance (1.37 GA), scale-to-zero (1.37 Beta), VPA, KEDA, CA / Karpenter / NAPHPA control loop calculator (adjustable load)podinfo load test + kubectl get hpa -w
314–22Observability and kubectl debugMetrics / logs / events, kube-prometheus-stack, SLIs and PromQL, the three kubectl debug modes and profilesAnimation of the troubleshooting path for “one alert”Ephemeral containers + Pod copies + node debugging
422–29Reliability: node-pressure eviction and node shutdownEviction signals and thresholds, soft/hard eviction, ordering rules, graceful/non-graceful shutdown, the six termination paths and DisruptionTargetNode memory pressure → eviction ordering simulatoremptyDir over-limit eviction + Eviction API 429 vs delete
529–37Cluster upgrades and maintenanceVersion skew, deprecated APIs, the kubeadm process, drain + PDB, AKS upgrade channels and maintenance windowsNode pool surge rolling upgradeAKS 1.36 → 1.37 zero-downtime upgrade
637–43Control plane operations overviewetcd roles and quorum, etcdctl snapshot save / etcdutl verification and restore, kubeadm certificate validity and renewal, AKS rotate-certsBackup → accidental deletion → restore / certificate expirykind snapshot + temporary cluster restore rehearsal
743–51Managed clusters compared: AKS / EKS / GKEResponsibility boundaries, fully managed modes, support windows and upgrades, Pod IP sources, identity, node scaling, managed observabilityThree-platform comparison, switchable by dimensionRead-only health check of aks-lab + selection exercise
851–60Production troubleshooting: master decision treeSummary of 6 hours of troubleshooting by symptom, nodes NotReady, eviction, certificates, runbooks and postmortemsLarge interactive troubleshooting tree (40+ nodes)Fault injection drills (A–F)
—After classFull cheat sheet · 6-hour capstone labDeliver shop: ACR → Kustomize/Helm → GitOps → Gateway+TLS → security → backup → HPA → eviction protection → upgrade → failures → cleanup12-question final quiz12-item acceptance checklist

Knowledge Coverage Matrix

Target skillModuleKey commandsLabProduction case
Delivery tool selection (Helm / Kustomize / GitOps)M1kubectl apply -k, helm upgrade --install, argocd app sync✓✓
Workload autoscalingM2kubectl autoscale, kubectl get hpa -w, kubectl top✓✓
Node autoscaling (CA / NAP / Karpenter)M2 · M7az aks update --enable-cluster-autoscaler, --node-provisioning-mode AutoReading✓
Metrics / logs / events troubleshootingM3 · M8kubectl logs --previous, kubectl events --for, PromQL✓✓
Live debuggingM3kubectl debug --target / --copy-to / node/✓✓
Node-pressure eviction and node shutdownM4kubectl get --raw …/proxy/configz, kubectl create --raw …/eviction✓✓
Cluster upgrades and deprecated APIsM5az aks get-upgrades, az aks nodepool upgrade --max-surge, kubeadm upgrade plan✓✓
etcd backup and restore, and certificatesM6etcdctl snapshot save, etcdutl snapshot restore, kubeadm certs check-expiration✓✓
Managed platform selection and differencesM7az aks show, aws eks describe-cluster, gcloud container clusters describe✓✓
Systematic troubleshootingM8kubectl describe, kubectl get events, crictl, journalctl -u kubelet✓✓
Integration of 6 hours of knowledgeCapstone labAll✓✓

Topics excluded from this hour (and where to learn them)

TopicReasonWhere to learn
Helm chart development, template functions, hooks, OCI publishing, Helm 3→4 migrationHas a dedicated 8-hour course; module 1 here is only an overviewHelm 8-hour course
Kustomize in depth, Argo CD installation and Application, sync waves, ApplicationSet, multi-tenancy, FluxHas a dedicated 8-hour course (hours 1–2 cover GitOps principles, Kustomize and manifest sources)GitOps and Argo CD 8-hour course
Advanced PromQL, alerting rules and Alertmanager, Grafana dashboards, Thanos/MimirThe observability stack itself is a coursePrometheus & Grafana 8 + 1-hour course
Full AKS reference architecture (hub-spoke, private clusters, egress, Defender, cost)Module 7 here only compares the three platformsAKS 8-hour course · Hour 7 (EKS)
PDB, PriorityClass preemption, QoS, ResourceQuotaCovered in earlier hours; module 4 only ties together the disruption overviewHour 2 · Release strategies and PDB · Scheduling and preemption · Hour 5 · Quotas
Full multi-member etcd disaster recovery, CA rotation (CKA content)Module 6 is an overview only; managed clusters do not need itkubernetes.io "Operating etcd clusters" · etcd official Disaster recovery
Argo Rollouts / Flagger progressive deliveryCanary principles were covered in hour 2Argo CD Hour 6 · Argo Rollouts
Multi-cluster (Fleet Manager, Cluster API), service mesh, operator developmentBeyond 1 hourSee capstone page · next learning path

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Hour 6 covers a lot, so start with “principles + animation + commands”, then do the labs on kind or AKS after class.
Learning progress
A quiz score of ≥ 70%, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser (key name k8s60-part6-progress-v1).
Using kind and AKS together
Delivery, HPA, debug, eviction and etcd labs are done on kind. Modules 5 and 7 and the capstone lab use the AKS aks-lab (for costs see module 0; be sure to clean up after class).
Version note This hour is based on Kubernetes v1.37. metrics.k8s.io and configurable HPA tolerance are GA in 1.37. HPA scale-to-zero (minReplicas: 0) is Beta in 1.37 and enabled by default. Native Histograms enter Beta in 1.37. The HugepageAwareEviction feature for node-pressure eviction is Beta in 1.37 (enabled by default). kube-proxy ipvs and kube-dns are listed as deprecated in the 1.37 release notes. Pod disruption conditions (DisruptionTarget) went GA in 1.31, and graceful node shutdown went GA in 1.28. Linux graceful node shutdown is still Beta (enabled by default). etcd snapshot verification and restore follow etcdutl (etcdctl snapshot status/restore are deprecated). Helm details follow 4.3.2 (2026-11-13). AKS details follow the learn.microsoft.com pages from 2026-07 to 11.

Module 0 · Warm-up (AKS setup)

Reuse the kind cluster and shop app from hours 1–5, then prepare Helm 4 and an AKS cluster (used by the module 5 upgrade lab and the module 7 health check and capstone lab)
Before class ≈ 20 min (AKS creation takes about 8–12 min)kind v0.33.0 · AKS 1.36→1.37
Prerequisites
  • Completed hours 1–5: the kind cluster lab (1 control plane + 2 workers, node image kindest/node:v1.37.0), with the namespace shop containing web (nginx), api (podinfo 6.17.0), db (postgres:17 StatefulSet), Gateway API routes, NetworkPolicy, RBAC and PSS restricted.
  • Lab machine: Azure VM Ubuntu 24.04 (Standard_D4s_v5), resource group rg-k8s-lab, region canadacentral. Docker 29.x, kubectl 1.37, kind v0.33.0 and Azure CLI are installed.
  • Subscription permissions: you must be able to create AKS / ACR / role assignments (Owner, or Contributor + User Access Administrator).
  • The lab machine also needs jq (modules 4 and 6 parse JSON). The aws / gcloud commands in module 7 are for reading and comparison only; installing them is not required. If you want hands-on EKS, prepare by following Hour 7 module 0.

Step 1: confirm the environment from the previous hour still works

kubectl config use-context kind-lab
kubectl get nodes -o wide
kubectl -n shop get deploy,sts,svc,httproute,networkpolicy
kubectl get ns shop --show-labels | grep pod-security
NAME                STATUS   ROLES           AGE   VERSION
lab-control-plane   Ready    control-plane   5h    v1.37.0
lab-worker          Ready    <none>          5h    v1.37.0
lab-worker2         Ready    <none>          5h    v1.37.0
deployment.apps/api   2/2   2   2   5h
deployment.apps/web   2/2   2   2   5h
statefulset.apps/db   1/1         4h
...
shop   Active   5h   pod-security.kubernetes.io/enforce=restricted,...
If the environment has been deleted, rebuild the cluster with kind-lab.yaml from hour 1, then run the “restore shop in one step” manifest at the end of the hour 5 capstone lab. All kind labs in this hour depend only on the api (podinfo) Deployment and Service in the shop namespace. Missing other components does not affect the kind labs in modules 1–4 and 6 (the etcd restore rehearsal in module 6 creates its own temporary kind cluster ops).

Step 2: install metrics-server (needed on kind; HPA and kubectl top depend on it)

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# kind's kubelet uses a self-signed certificate, so add --kubelet-insecure-tls in this lab environment (do not do this in production)
kubectl -n kube-system patch deploy 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 top nodes

Step 3: install Helm 4 (official get-helm-4 script)

curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-4
chmod 700 get_helm.sh
./get_helm.sh
helm version
version.BuildInfo{Version:"v4.3.2", GitCommit:"…", GitTreeState:"clean", GoVersion:"go1.2x.x"}

You can also use the community-maintained apt repository (hosted by Buildkite, packages.buildkite.com/helm-linux/helm-debian) or sudo snap install helm --classic. These are not packages officially maintained by the Helm project.

Step 4: create ACR and AKS (deliberately 1.36; upgrade to 1.37 in module 5)

RG=rg-k8s-lab; LOC=canadacentral; AKS=aks-lab
ACR=acrk8slab$RANDOM          # globally unique, all lowercase
az group create -n $RG -l $LOC
az acr create -g $RG -n $ACR --sku Basic

# List the versions available in this region (check whether 1.36 / 1.37 are listed, and whether 1.38 is in preview)
az aks get-versions -l $LOC -o table
KubernetesVersion    Upgrades                 SupportPlan
-------------------  -----------------------  --------------------------------------
1.38.0(preview)      None available           KubernetesOfficial
1.37.1               1.38.0(preview)          KubernetesOfficial, AKSLongTermSupport
1.36.5               1.37.1                   KubernetesOfficial, AKSLongTermSupport
1.35.9               1.36.5                   KubernetesOfficial, AKSLongTermSupport
K8S_OLD=$(az aks get-versions -l $LOC --query "values[?starts_with(version,'1.36')].version | [0]" -o tsv)
echo $K8S_OLD     # if the JMESPath query returns nothing because of CLI version differences, enter 1.36.x manually

az aks create -g $RG -n $AKS -l $LOC \
  --kubernetes-version $K8S_OLD \
  --tier free \
  --node-count 3 --node-vm-size Standard_D4s_v5 --zones 1 2 3 \
  --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium \
  --enable-managed-identity \
  --enable-oidc-issuer --enable-workload-identity \
  --enable-aad --enable-azure-rbac \
  --attach-acr $ACR \
  --auto-upgrade-channel none --node-os-upgrade-channel NodeImage \
  --generate-ssh-keys
ParameterPurposeReason for this value
--tier free|standard|premiumControl plane tier: Free has no financially backed SLA (recommended under <10 nodes, up to 1,000). Standard has an SLA (99.95% with availability zones, 99.9% without, up to 5,000 nodes). Premium = Standard + LTS (you must also set --k8s-support-plan AKSLongTermSupport)Use free for the lab; use at least standard in production
--network-plugin azure --network-plugin-mode overlayAzure CNI Overlay: Pod IPs come from a separate CIDR (default 10.244.0.0/16) and do not use VNet address spaceNote: if you write only --network-plugin azure without a mode, AKS uses the legacy VNet mode for compatibility
--network-dataplane ciliumAzure CNI powered by Cilium (eBPF dataplane, built-in NetworkPolicy engine)Consistent with NAP and AKS Automatic
--enable-oidc-issuer --enable-workload-identityProvides the OIDC issuer and webhook for the Workload Identity in hour 5Always enable in production
--enable-aad --enable-azure-rbacEntra ID authentication + Azure RBAC for Kubernetes authorizationYou need to assign yourself an AKS RBAC role (see below)
--attach-acrAssign AcrPull to the kubelet managed identityNo imagePullSecret needed
--auto-upgrade-channel noneTurn off automatic cluster upgradesWith automatic upgrades on, you cannot run a --control-plane-only upgrade, and module 5 demonstrates it
--node-os-upgrade-channel NodeImageNode images refresh weekly (default for new Standard clusters)Recommended in production together with a maintenance window
--zones 1 2 3Spread nodes across 3 availability zonescanadacentral supports availability zones. Disks (LRS) are zone-bound; see hour 4

Step 5: kubelogin, credentials and RBAC roles

az aks install-cli                 # install or update kubectl and kubelogin (or download from GitHub Azure/kubelogin)
ME=$(az ad signed-in-user show --query id -o tsv)
AKS_ID=$(az aks show -g $RG -n $AKS --query id -o tsv)
az role assignment create --assignee $ME --role "Azure Kubernetes Service RBAC Cluster Admin" --scope $AKS_ID

az aks get-credentials -g $RG -n $AKS --overwrite-existing
kubelogin convert-kubeconfig -l azurecli     # reuse the token from az login, so no device-code sign-in is needed
kubectl config get-contexts
kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.azure.com/node-image-version
NAME                                STATUS   ROLES    AGE   VERSION   ZONE              NODE-IMAGE-VERSION
aks-nodepool1-12345678-vmss000000   Ready    <none>   6m    v1.36.5   canadacentral-1   AKSUbuntu-2404gen2containerd-2026xx.xx.x
aks-nodepool1-12345678-vmss000001   Ready    <none>   6m    v1.36.5   canadacentral-2   …
aks-nodepool1-12345678-vmss000002   Ready    <none>   6m    v1.36.5   canadacentral-3   …
Role assignments take a few minutes to take effect. If kubectl get nodes returns Forbidden ... User "xxx" cannot list resource "nodes", wait 2–5 minutes and try again. Azure RBAC authorization is performed by AKS's authorization webhook calling Azure, and Kubernetes RoleBindings work for Entra users too (the two are OR-ed).

Cost estimate and cleanup (read this first)

ResourceEstimateNotes
3 × Standard_D4s_v5 (Linux)About 0.2 USD per hour per VM (pay-as-you-go rate in Canada Central, order of magnitude)Main cost; the Azure pricing calculator is authoritative
AKS control plane Free tier0Standard tier is billed separately per cluster-hour
OS disks, standard load balancer, public IP, ACR Basic, Log Analytics (if enabled)About 1–3 USD per dayContainer Insights is billed by data ingestion
TotalAbout 0.7 USD per hour, roughly 15–20 USD for a full dayWhen not in use, run az aks stop (after stopping, node VMs are not billed, but disks still are)
az aks stop -g rg-k8s-lab -n aks-lab                 # pause (clusters with NAP enabled cannot be stopped)
az group delete -n rg-k8s-lab --yes --no-wait        # delete everything (this also removes the MC_ node resource group)
kind delete cluster --name lab                       # local kind
Self-check list

Module 1 · Production delivery toolchain overview: Helm, Kustomize and GitOps

00:00 – 06:00 · What problem each of the three tools solves, how to choose between them, and minimal working examples. For the deep dives, see the two 8-hour Helm and Argo CD courses.
6 minHelm 4.3.2 · kubectl built-in Kustomize · Argo CD v3.6 / Flux v2.10★★★★☆ overview
Learning goals
  • Explain which link in the delivery chain Helm (templates + packages + release records), Kustomize (template-free base/overlay patches) and GitOps (pull-based continuous reconciliation) each solves, and why they are not mutually exclusive.
  • Write a minimal Kustomize base + overlay and deploy it with kubectl apply -k, and install a third-party chart with a single helm upgrade --install.
  • Understand the GitOps “pull + continuous reconciliation” model: why CI no longer needs cluster write credentials, and why a manual kubectl edit gets reverted.
  • Know where to go deeper: the Helm 8-hour course and the GitOps and Argo CD 8-hour course (hours 1–2 cover GitOps principles, Kustomize and manifest sources).
Prerequisites: Deployment / Service (hour 1), ConfigMap (hour 2), the server-side flow of kubectl apply (hour 1). Importance: ★★★★☆ (this hour covers selection and introductory material only; production details are in the dedicated courses)

What: the three links in the delivery chain

Turning shop from “a pile of YAML” into a repeatable, auditable, rollback-capable production delivery requires answering three questions. How are manifests parameterized and reused? (Helm or Kustomize) Who submits manifests to the cluster? (a person or CI pushes them, or a controller inside the cluster pulls them = GitOps) How do you roll back when something goes wrong? (helm rollback or git revert).

ToolEssenceProblem it solvesHow to roll backLearn more
Helm 4Package manager + Go template rendering + release records (stored as namespaced Secrets named sh.helm.release.v1.<name>.vN)Applications with many parameters and logic; distribution to multiple teams; installing third-party components (cert-manager, kube-prometheus-stack, Argo CD itself)helm rollback REL [REV] (creates a new revision)Helm Hour 1: Core Fundamentals · Hour 2: Writing Production-Ready Charts
KustomizeNo templates: the base is plain YAML that can be deployed directly; the overlay describes differences with patches, name prefixes and image rewrites; built into kubectl (-k)Differences between dev, staging and prod for internal apps; the “last mile” of changes to third-party rendered outputNo release records; relies on Git (git revert)Argo CD Hour 2 · Manifest sources: plain YAML, Kustomize, Helm and OCI
GitOps (Argo CD / Flux)A controller inside the cluster continuously compares the desired state in Git (or OCI) with the actual cluster state and reconciles themWho can change production, change auditing, drift detection and automatic correction, and the ability to rebuild the cluster from Gitgit revert → the controller syncs automaticallyArgo CD Hour 1 · The four GitOps principles

Why: why not “kubectl apply in CI” anymore

  • Duplication: three environments with nearly identical YAML means changing one field requires three edits. Helm values or Kustomize overlays remove the duplication.
  • Credentials: in push mode, CI holds cluster write permissions, which is the largest attack surface. In GitOps pull mode, CI only writes to Git, and the in-cluster controller only needs to read Git.
  • Drift: someone runs kubectl edit at midnight to fix one parameter without committing it, and the next release overwrites it. GitOps shows OutOfSync and can revert the change automatically with selfHeal.
  • Rollback: kubectl apply has no “versions”. Helm has revisions, and GitOps has Git history.

How: how the three combine (the most common production setup)

  1. CI builds the image, pushes it to ACR/ECR, and writes the new image digest into the GitOps repository (by editing values or with kustomize edit set image), then opens a PR.
  2. After the PR is merged, Argo CD / Flux detects the new commit and renders the manifests with Helm or Kustomize. When Argo CD renders Helm, it does not create a helm release Secret, so rollback relies on Git.
  3. The controller submits to the apiserver with server-side apply (authentication → authorization → admission; hours 1 and 5), then keeps watching the actual state.
  4. If a health check fails or someone changes something by hand, it shows Degraded / OutOfSync, and alerts or auto-corrects according to policy.

When: how to choose

ScenarioRecommendedReason
Installing third-party components (monitoring stack, cert-manager, Gateway implementations)Helm chart (pinned --version), brought under GitOpsUpstream ships as a chart, and values are the officially supported configuration surface
Your team's own microservices, with small differences between environmentsKustomize base + overlaysPlain YAML is easy to review, with no template language
Needs distribution to multiple teams or customers, with conditionals and loops in parametersHelm chart (pushed to an OCI registry)Versioned package + values schema validation
Multiple environments or clusters, requiring auditing and drift correctionGitOps (Argo CD: strong UI and multi-tenancy; Flux: lightweight, CRD-native, with a managed AKS extension)Pull mode, continuous reconciliation
A third-party chart differs by just one or two fields (for example, adding a toleration)Helm rendering + Kustomize patches (Argo CD multi-source / Kustomize helmCharts / Helm 4 post-renderer plugin)No forking of the chart
Two Helm 4 changes you must know (details in the Helm course) ① --atomic is renamed to --rollback-on-failure, and --force is renamed to --force-replace (the old names still work but show deprecation warnings). ② New installs use server-side apply by default, and --wait without a value means the watcher (based on kstatus); when omitted, the default is hookOnly. For a full comparison, see Helm Hour 7 · Migrating from Helm 3 to Helm 4.
Common misconceptions ① “Using Helm means you don't need GitOps.” Helm solves packaging; it does not solve who submits changes, when, and from where. ② “Kustomize replaces Helm.” The two are often used together: Helm renders third-party charts, and Kustomize handles environment differences. ③ “GitOps must use Argo CD.” Flux follows the same OpenGitOps principles, and AKS's managed GitOps extension is based on Flux (microsoft.flux). ④ “helm rollback can roll back a database.” It only re-applies old manifests, so database migrations are not reversed.

Diagram: from a Git commit to cluster objects

Developer / CIBuild image · update digest Image registryACR / ECR (OCI) Git repository (single source of truth) charts/ orvalues-prod.yaml base/overlays/prod apps/: Argo CD Applicationor Flux Kustomization / HelmRelease PR In-cluster GitOps controller (pull) ① Detect new commits (polling / webhook) ② Render: helm template or kustomize build ③ Diff: desired vs actual → Synced / OutOfSync ④ Sync: server-side apply (prune optional) ⑤ Continuous watch: drift → selfHeal Read kube-apiserver → etcd → controllers → kubeletnamespace shop: Deployment api / web, StatefulSet dbkubelet pulls the digest from the image registry kubelet pulls images (AcrPull / node role) Push mode (comparison): CI holds the kubeconfigDirect kubectl / helm writes to the cluster → risk of credential leakage
Figure 1-1: Helm and Kustomize are “renderers”; the GitOps controller is the “committer + guardian”; CI only writes to Git and the image registry

Comparison diagram: three ways to write the same api

Helm: templates + values replicas: {{ .Values.replicaCount }}image: {{ .Values.image.repo }}:{{ … }}values-prod.yaml: replicaCount: 3+ release records / rollback− templates are hard to review and easy to break with indentation Kustomize: base + overlay base/deployment.yaml (plain YAML)overlays/prod: replicas: [{name: api, count: 3}]images: [{name: …, digest: sha256:…}]+ plain YAML, built into kubectl− no release records, weak logic GitOps: who applies Application: source=repo/path (Helm or Kustomize both work)syncPolicy: automated {prune, selfHeal}+ auditing, drift correction, no CI credentials needed− one more system to operate
Figure 1-2: the first two answer “what do the manifests look like”; the third answers “how do the manifests reach the cluster safely and stay consistent”

Step-by-step animation: the path of one image upgrade under the three delivery methods

Choose a delivery method, then click “Play” to see who holds cluster credentials, which path a rollback takes, and what happens after a manual change.

Developergit push CI pipelineBuild · push image Git repositoryDesired state Renderer / committerhelm · kustomize Cluster apiserverDeployment api Cluster write credentials: — api image: podinfo:6.17.0
Ready. Click “Play”.
$ git commit -m "api: 6.17.0 → 6.17.1"

Core commands (minimal set)

CommandPurposeNotes
kubectl kustomize DIRRenders only the overlay, does not access the clusterEquivalent to kustomize build DIR; look at the output before deploying
kubectl apply -k DIR / kubectl diff -k DIR / kubectl delete -k DIRDeploy / preview differences / deleteCan add --server-side
helm repo add NAME URL, helm search repoAdd a chart repository, look up versionsOCI registries do not need repo add; use oci:// directly
helm upgrade --install REL CHART -n NS --create-namespace --version V -f values.yamlIdempotent install/upgradePreferred for manual installs outside CI and GitOps; add --rollback-on-failure to roll back automatically on failure
helm list -A, helm history REL, helm rollback REL [REV]View and roll backRelease records are stored in a namespaced Secret
helm template REL CHART -f v.yamlRender onlyCan pipe into | kubectl apply --dry-run=server -f - so the apiserver validates it
argocd app create|get|diff|sync|historyArgo CD CLIYou can also kubectl apply an Application object directly
flux get kustomizations, flux reconcile ks NAME --with-sourceFlux CLIAKS: az k8s-configuration flux create -t managedClusters

Minimal Kustomize: base + prod overlay

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml          # plain Deployment: name api, image ghcr.io/stefanprodan/podinfo:6.17.0
  - service.yaml
labels:
  - pairs: { app.kubernetes.io/part-of: shop }
    includeSelectors: false  # does not change selectors (commonLabels is deprecated because it changes the immutable selector)
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop
resources: [ ../../base ]
replicas:
  - { name: api, count: 3 }
images:
  - name: ghcr.io/stefanprodan/podinfo
    newTag: "6.17.1"         # in production, prefer a digest: sha256:…
configMapGenerator:
  - name: api-config
    literals: [ LOG_LEVEL=warn ]   # the name includes a content hash: config change → Pod template change → rolling update

Minimal Helm: install a third-party chart

helm repo add podinfo https://stefanprodan.github.io/podinfo
helm repo update
helm search repo podinfo/podinfo --versions | head -3
helm upgrade --install demo podinfo/podinfo -n demo --create-namespace \
  --version <version from the previous step> --set replicaCount=2 --wait --timeout 3m
helm -n demo history demo
helm -n demo get values demo --all | head

Minimal GitOps: one Argo CD Application

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata: { name: shop-prod, namespace: argocd }
spec:
  project: default
  source:
    repoURL: https://github.com/you/k8s6-gitops.git
    targetRevision: main
    path: kshop/overlays/prod            # if the directory has kustomization.yaml, it is rendered with Kustomize automatically
  destination: { server: https://kubernetes.default.svc, namespace: shop }
  syncPolicy:
    automated: { prune: true, selfHeal: true }
  ignoreDifferences:                     # lets HPA (module 2) own the replicas field
    - { group: apps, kind: Deployment, jsonPointers: [ /spec/replicas ] }

How to verify: kubectl kustomize overlays/prod | grep -E "replicas|image:|api-config"; helm -n demo status demo; kubectl -n argocd get applications. Common errors: wrong overlay path (accumulating resources: … no such file), chart version does not exist, no recognizable manifests under the Application's path.

Lab 1: the same api, deployed once with Kustomize and once with Helm (about 8 min, kind)

Prepare the base (reuse the api config from the shop app in hours 1–5; to avoid conflicts with the existing api, use the name api-k and the namespace shop-dev)
mkdir -p ~/k8s6/kshop/{base,overlays/dev} && cd ~/k8s6/kshop
kubectl create deploy api-k --image=ghcr.io/stefanprodan/podinfo:6.17.0 --port=9898 \
  --dry-run=client -o yaml > base/deployment.yaml
kubectl create svc clusterip api-k --tcp=9898:9898 --dry-run=client -o yaml > base/service.yaml
cat > base/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: [deployment.yaml, service.yaml]
labels:
  - pairs: { app.kubernetes.io/part-of: shop }
EOF
Write the dev overlay and render it first
cat > overlays/dev/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-dev
namePrefix: dev-
resources: [../../base]
replicas: [{ name: api-k, count: 1 }]
configMapGenerator:
  - name: api-config
    literals: [LOG_LEVEL=debug]
EOF
kubectl create ns shop-dev
kubectl kustomize overlays/dev | grep -E "name:|replicas|namespace" | head
  name: dev-api-config-7g8k2m9d5h
  namespace: shop-dev
  name: dev-api-k
  namespace: shop-dev
  replicas: 1
...
Deploy, change the config, and observe the hash change
kubectl apply -k overlays/dev
sed -i 's/LOG_LEVEL=debug/LOG_LEVEL=info/' overlays/dev/kustomization.yaml
kubectl diff -k overlays/dev | head -20      # new ConfigMap name (different hash)
kubectl -n shop-dev get cm

This example Deployment does not reference the ConfigMap, so it will not roll. In a real overlay, reference it with envFrom.configMapRef.name: api-config; Kustomize rewrites that to the hashed name, which triggers a rollout.

Install the same app with Helm (upstream podinfo chart)
helm repo add podinfo https://stefanprodan.github.io/podinfo && helm repo update
helm upgrade --install api-h podinfo/podinfo -n shop-dev --set replicaCount=1 --wait --timeout 3m
helm -n shop-dev list
kubectl -n shop-dev get secret -l owner=helm
NAME    NAMESPACE  REVISION  STATUS    CHART            APP VERSION
api-h   shop-dev   1         deployed  podinfo-6.x.x    6.x.x
NAME                          TYPE                 DATA   AGE
sh.helm.release.v1.api-h.v1   helm.sh/release.v1   1      15s
Compare rollback methods
helm -n shop-dev upgrade api-h podinfo/podinfo --set replicaCount=2 --wait
helm -n shop-dev rollback api-h 1 --wait && helm -n shop-dev history api-h
# Kustomize has no “rollback command”: go back to the previous Git commit and apply -k (under GitOps, the controller does this)
(Optional) GitOps preview: following Argo CD Hour 1 · Install Argo CD, install Argo CD on kind, push overlays/dev to your Git repository and create an Application. Run kubectl -n shop-dev scale deploy dev-api-k --replicas=3 and watch selfHeal change it back to 1.
Cleanup: helm -n shop-dev uninstall api-h; kubectl delete -k overlays/dev; kubectl delete ns shop-dev

Case 1: migrating from “kubectl apply in Jenkins” to GitOps

Problem: Jenkins held cluster-admin kubeconfigs for 3 production clusters, and after a credential leak it was required to fix this. Approach: CI only builds images and opens PRs against the GitOps repository (updating the digest); Argo CD pulls inside the cluster; write access to production namespaces is granted only to Argo CD's ServiceAccount and a break-glass group. Result: CI no longer holds cluster credentials, and every change is an auditable Git commit. For migration steps and Image Updater, see Argo CD Hour 6 · From CI to GitOps.

Case 2: a third-party chart is missing just one toleration

Problem: the monitoring stack must run on a dedicated, tainted node pool, but a sub-component of the chart does not expose tolerations. Approach: do not fork the chart; let Argo CD render the Helm chart and then apply a Kustomize patch on top (or use the Helm 4 post-renderer plugin). Note: in Helm 4, --post-renderer must be a plugin name, so the ./kustomize.sh script from the Helm 3 era needs to be reworked. See Helm Hour 6 · post-renderer and Kustomize.

Case 3: HPA and GitOps fighting over replicas

Symptom: after enabling HPA, the api replica count keeps jumping between 2 and 6. Cause: the Deployment in Git hard-codes replicas: 2, and selfHeal keeps reverting the replicas that HPA scaled out. Approach: do not declare replicas in the manifests (in a Helm template, use if not .Values.autoscaling.enabled), or add ignoreDifferences for /spec/replicas in the Application. This is prerequisite knowledge for module 2 (autoscaling) in this hour.

Common errors and fixes

error: accumulating resources: accumulation err='accumulating resources from '../../base': … no such file or directory'

Cause: the relative path in the overlay's resources is wrong, or the base directory is missing kustomization.yaml.

ls overlays/prod ../../base 2>&1; kubectl kustomize overlays/prod
The Deployment "api" is invalid: spec.selector: Invalid value: …: field is immutable

Cause: the deprecated commonLabels is used (or labels with includeSelectors: true), so the new labels are written into the selector, and a Deployment's selector is immutable.

Fix: switch to labels (default includeSelectors: false). kustomize edit fix can migrate old fields. Objects that are already broken must be deleted and recreated.

Error: INSTALLATION FAILED: cannot re-use a name that is still in use

Cause: a release with the same name already exists (possibly in the failed state).

helm -n NS list -a
helm -n NS upgrade --install REL CHART      # idempotent form

For more release state problems (pending-upgrade and so on), see Helm Hour 7 · Stuck releases.

Argo CD: ComparisonError: … kustomize build … failed / Unknown (unrecognized source type)

Cause: there is no kustomization.yaml or Chart.yaml under the Application's path, or rendering fails (the same error you would get from local kubectl kustomize).

argocd app get shop-prod --show-operation
kubectl -n argocd logs deploy/argocd-repo-server --tail=50

Make sure rendering succeeds locally before you commit. For deeper troubleshooting, see Argo CD Hour 7 · OutOfSync loops and sync failures.

The app stays OutOfSync, and the diff shows only replicas or a certain annotation

Cause: another controller in the cluster (HPA, or a webhook injection) is changing that field. Fix: use ignoreDifferences, or remove the field from the manifest so the real owner manages it.

Command-line exercise

1. Render only overlays/prod and have the apiserver run a server-side validation (without actually writing anything).

Reference answer
kubectl kustomize overlays/prod | kubectl apply --dry-run=server -f -
# or kubectl apply -k overlays/prod --dry-run=server

2. Install the podinfo chart into the demo namespace idempotently with one command: pinned version, automatic rollback on failure, and waiting up to 5 minutes.

Reference answer
helm upgrade --install demo podinfo/podinfo -n demo --create-namespace \
  --version <VERSION> --rollback-on-failure --timeout 5m

Scenario analysis: a team has 12 internal microservices, 3 environments and 2 clusters, and also needs to install kube-prometheus-stack and cert-manager. Propose a tool combination.

Reference answer

Internal microservices use a Kustomize base + overlays (one overlay per environment). Third-party components use Helm charts at pinned versions. Both are deployed by Argo CD (or Flux) pulling from Git, and environments and clusters are generated with ApplicationSet or a directory convention. CI only builds images and updates digests through PRs, and rollback is uniformly git revert. For depth, see Argo CD Hour 3 · Repository layout.

Verified video resources

▶
What is Helm in Kubernetes? Helm and Helm Charts explained | Kubernetes Tutorial 23 — TechWorld with Nana
English · recorded in the Helm 3 era; the concepts still apply (for Helm 4 differences, follow this hour and the Helm course)
▶
What is GitOps, How GitOps works and Why it's so useful — TechWorld with Nana
English · the GitOps pull model and its benefits
▶
ArgoCD Tutorial for Beginners | GitOps CD for Kubernetes — TechWorld with Nana
English · Argo CD introduction (predates v3; follow the Argo CD course for commands)

No verified video with a usable video ID was found for the Kustomize topic.

Official docs and follow-up courses

Video storyboard script

This courseware cannot generate a video or MP3 directly, so a storyboard and a narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: three nearly identical YAML files (dev/staging/prod) overlap, with the differences highlighted; a “cluster key” sits on the CI server.
Narration: copying YAML and running kubectl apply from CI is where most teams start, and it is also where the problems start.
Shot 2 · 0:20–0:50
Visual: Helm templates + values on the left, Kustomize base + overlay on the right, both producing the same Deployment in the middle.
Narration: Helm uses templates and parameters, and Kustomize layers patches on top. Both are renderers, and both answer the question of what the manifests look like.
Shot 3 · 0:50–1:30
Visual: the key moves from CI to Argo CD inside the cluster; an Argo CD arrow points to Git, and a loop icon turns.
Narration: GitOps has a controller inside the cluster pull from Git, while CI only writes to Git. The controller keeps comparing and correcting drift.
Shot 4 · 1:30–2:00
Visual: git revert on one commit, and the cluster automatically returns to the old version; the screen shows the covers of the Helm and Argo CD courses.
Narration: rollback is just reverting a commit. To go deeper, continue with the two 8-hour courses on Helm and Argo CD.
or pass the quiz with a score of ≥ 70%

Module 2 · Autoscaling: HPA · VPA · KEDA · node scaling

06:00 – 14:00 · Elasticity at three levels: number of Pods, Pod size, and number of nodes
8 minautoscaling/v2 · tolerance GA (1.37)scale-to-zero Beta (1.37, enabled by default)
Learning goals
  • Use the formula desiredReplicas = ceil(currentReplicas × currentMetric / targetMetric) to work out HPA results by hand, and explain how tolerance, the stabilization window and scaling policies adjust them.
  • Configure the four metric types of HPA v2 (Resource / Pods / Object / External, plus ContainerResource) and behavior.
  • Explain the 1.37 changes: metrics.k8s.io GA, configurable tolerance GA, and minReplicas: 0 (HPAScaleToZero) Beta.
  • Tell apart VPA, KEDA, Cluster Autoscaler, Karpenter and AKS Node Auto Provisioning (NAP), so they do not fight each other.
Prerequisites: requests/limits and QoS (hour 2), metrics-server (module 0). Importance: ★★★★★

What: three levels of autoscaling

LevelComponentWhat it adjustsTrigger
Pod countHPA (built into kube-controller-manager), KEDA (event-driven; still creates an HPA underneath)spec.replicas (through the scale subresource)CPU/memory utilization, custom metrics, external metrics (queue length and so on)
Pod sizeVPA (standalone project: recommender / updater / admission-controller)Container requests/limitsHistorical usage; the InPlaceOrRecreate mode uses in-place resize (in-place resize went GA in K8s 1.35)
Node countCluster Autoscaler, Karpenter, AKS NAP (managed Karpenter)NodePending (unschedulable) Pods; idle or consolidatable nodes

Why: why it is needed

Traffic has peaks and troughs. Sizing for the peak wastes money, while sizing for the average makes latency spike at peak. HPA handles replica changes on a scale of seconds to minutes, and node scaling handles capacity changes on a scale of minutes. Together they let you avoid both waste and overload.

How: the HPA control loop

  1. kube-controller-manager processes each HPA every 15 seconds (--horizontal-pod-autoscaler-sync-period).
  2. Reads metrics from metrics.k8s.io (Resource, served by metrics-server, GA in 1.37), custom.metrics.k8s.io (Pods/Object), or external.metrics.k8s.io (External, served by KEDA / Prometheus Adapter).
  3. Resource utilization = usage ÷ requests. If any container has no matching requests, that metric cannot be computed (the HPA event shows missing request for cpu).
  4. No action is taken while the ratio is within the tolerance (default 0.1, i.e. ±10%). Since 1.37 it can be set per direction in behavior.scaleUp/scaleDown.tolerance (GA, introduced in 1.33).
  5. Each metric produces its own desired value, and the largest one wins. Unready Pods and Pods with missing metrics are handled conservatively in the calculation (assumed to be 0% when scaling up, and 100% when scaling down).
  6. Adjusted by behavior. The default scale-down stabilization window is 300 seconds (it uses the highest recommendation in the window, to prevent flapping), with at most a 100% reduction every 15 seconds. The default scale-up has no window, with at most a 100% increase or 4 Pods every 15 seconds, whichever is larger (selectPolicy: Max).
  7. Changes the Deployment's replicas through the scale subresource; the Deployment controller then rolls out the Pods.
1.37: scale-to-zero (Beta, enabled by default) spec.minReplicas: 0 requires at least one Object or External metric. CPU and memory can only be measured on running Pods and cannot wake a workload from 0, so the apiserver rejects the setting otherwise. The feature gate HPAScaleToZero must be enabled on both kube-apiserver and kube-controller-manager (it is enabled by default in Beta). While at 0 replicas, the HPA condition ScaledToZero=True is set. Whether managed clusters expose this feature follows the platform's announcements.

When: which one to choose

ScenarioRecommended
Stateless web/API, load-related CPUHPA (CPU utilization 50–70%) + node scaling
Queue consumers, scheduled batch jobs, need to scale to zeroKEDA (ScaledObject / ScaledJob, 60+ scalers); or, in 1.37, an HPA External metric + minReplicas 0
You don't know what requests to set; single-replica serviceVPA (start in Off mode to look at recommendations only)
Nodes: a fixed set of VM sizesCluster Autoscaler (scales per node pool)
Nodes: you want the right sizes picked automatically and fragmentation consolidatedKarpenter; on AKS use NAP (--node-provisioning-mode Auto)

Node scaling comparison

Cluster AutoscalerKarpenter / AKS NAP
ModelScales existing node groups (AKS node pools = VMSS)Chooses VM sizes directly for Pending Pods and creates nodes (NodePool / AKSNodeClass CRDs, karpenter.sh/v1)
ConsolidationRemoves under-utilized nodesActive consolidation, replacement with cheaper sizes, drift replacement
Enabled on AKSaz aks nodepool update --enable-cluster-autoscaler --min-count 1 --max-count 5az aks create … --node-provisioning-mode Auto --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium
LimitsLimited by fixed node pool sizesNAP does not support Windows node pools or IPv6. Once enabled, the cluster cannot use az aks stop. AKS Automatic enables it by default.
Common misconceptions ① “HPA computes utilization from limits.” It uses requests. ② “HPA and VPA can both work on CPU at the same time.” They interfere with each other (VPA changes requests, which changes the utilization denominator). When used together, have HPA use custom metrics, or let VPA manage memory only. ③ “Adding HPA means Pods never go Pending.” HPA only creates Pods. Without node capacity, Pods stay Pending, and node scaling is needed. ④ “Slow scale-down is a bug.” The default 300-second stabilization window is intentional, to prevent flapping.

Diagram: metrics pipeline and three levels of scaling

Node · kubelet / cAdvisor/metrics/resource (CPU, memory)Pod: api ×N (requests must be set) metrics-servermetrics.k8s.io (GA) PrometheusAdapter / KEDAcustom / external HPA controller (kcm)Every 15s: compute → tolerance →stabilization window → policy → scale subresource Deployment / ReplicaSetreplicas: 2 → 5New Pods: schedulable or Pending Node scalingCluster Autoscaler: VMSS +1Karpenter / NAP: create a VM of the right size Pending VPArecommender reads history → recommends requestsupdater: InPlaceOrRecreate / Recreate KEDA operatorScaledObject → manages one HPA (1↔N) and handles 0↔1 activation itself; external event sources: Service Bus, Kafka, Prometheus, cron…
Figure 2-1: HPA only changes the replica count. Whether Pods actually run depends on node capacity (node scaling) and Pod size (VPA/requests)

Data flow: the timeline of one scale-up

t=0 load risesCPU 180%/req ~15–60s metricsmetrics-server window HPA sync2 → 6 replicas Scheduling2 Pending 1–3 minNew node Ready Pod ReadyreadinessProbe passes End to end, this commonly takes 1–4 minutes. If a peak arrives faster than that, keep a margin (a lower target utilization, a higher minReplicas, or scheduled scaling).
Figure 2-2: scale-up latency = metrics collection + HPA period + scheduling + node provisioning + image pull + application startup

Interactive simulator: HPA control loop

Drag the “load” slider to change the CPU usage per replica (percentage of the 100m requests × replica count = total load), then click “Run” to simulate one 15-second cycle per second. Watch the formula, the tolerance, the scale-down stabilization window (shortened to an adjustable value for the demo) and the scale-up policy (at most +100% or +4 per cycle).

minReplicas 2 · maxReplicas 10

Click “Run” or “Step”.
$ kubectl get hpa api -n shop -w

Core commands

CommandPurposeNotes
kubectl autoscale deploy api --cpu-percent=60 --min=2 --max=10Quickly create an HPAGenerates an autoscaling/v2 object; manage it with YAML in production
kubectl get hpa -wWatch TARGETS and REPLICASTARGETS shows cpu: 45%/60%; <unknown> means the metric cannot be retrieved
kubectl describe hpa apiCheck Conditions and EventsAbleToScale / ScalingActive / ScalingLimited / ScaledToZero
kubectl top pods --containersCurrent usageFrom metrics.k8s.io
kubectl get --raw /apis/metrics.k8s.io/v1/namespaces/shop/podsQuery the metrics API directlyStable at v1 since 1.37; v1beta1 is still available during the transition (check what the cluster actually serves: kubectl api-versions | grep metrics)
az aks nodepool update --enable-cluster-autoscaler --min-count 1 --max-count 5Enable CA on the AKS node poolaz aks update --cluster-autoscaler-profile scale-down-unneeded-time=5m
az aks update --enable-keda / --enable-vpaAKS managed KEDA / VPA add-onsAKS 1.37 add-on versions: KEDA 2.20.2, VPA 1.7.1 (check the AKS version page for the current values)

Production-grade HPA (behavior + tolerance)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: api, namespace: shop }
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: api }
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource: { name: cpu, target: { type: Utilization, averageUtilization: 60 } }
    - type: Pods                                   # needs a custom metrics adapter
      pods:
        metric: { name: http_requests_per_second }
        target: { type: AverageValue, averageValue: "50" }
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      tolerance: 0.05                              # 1.37 GA: scale-up reacts more sensitively
      policies: [{ type: Percent, value: 100, periodSeconds: 15 }, { type: Pods, value: 4, periodSeconds: 15 }]
      selectPolicy: Max
    scaleDown:
      stabilizationWindowSeconds: 300
      policies: [{ type: Percent, value: 20, periodSeconds: 60 }]   # scale down by at most 20% per minute

KEDA ScaledObject (queue-driven, can scale to 0)

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: worker, namespace: shop }
spec:
  scaleTargetRef: { name: worker }
  minReplicaCount: 0
  maxReplicaCount: 20
  triggers:
    - type: azure-servicebus
      metadata: { queueName: orders, messageCount: "50" }
      authenticationRef: { name: sb-workload-identity }     # TriggerAuthentication, using Workload Identity

VPA (observe the recommendations first)

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata: { name: db, namespace: shop }
spec:
  targetRef: { apiVersion: apps/v1, kind: StatefulSet, name: db }
  updatePolicy: { updateMode: "Off" }      # recommendation only; InPlaceOrRecreate is GA in VPA 1.6.0; InPlace is Alpha in 1.7.0
  resourcePolicy:
    containerPolicies: [{ containerName: "*", controlledResources: ["memory"] }]

Verify: kubectl describe vpa db and check Target / LowerBound / UpperBound. Common errors: the VPA CRD is not installed (no matches for kind "VerticalPodAutoscaler"); using HPA (CPU) and VPA (CPU) on the same workload. Versions: the latest upstream VPA is 1.8.1 (2026-10), and the latest KEDA is 2.21.0 (2026-09).

Lab 2: podinfo load test and HPA observation (about 10 min, kind)

Confirm that requests are set and metrics are available
kubectl -n shop get deploy api -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'
kubectl -n shop top pods -l app=api

If requests are empty, first run kubectl -n shop set resources deploy/api --requests=cpu=100m,memory=64Mi --limits=memory=128Mi.

Create the HPA: apply hpa-api.yaml from the “Commands” tab with the Pods metric removed (kind has no custom metrics adapter).
kubectl apply -f hpa-api.yaml
kubectl -n shop get hpa api
NAME   REFERENCE        TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
api    Deployment/api   cpu: 3%/60%   2         10        2          20s
Generate load (the PSS restricted policy from hour 5 rejects the default busybox Pod, so add a security context override. If a NetworkPolicy denies traffic by default, add a label that the api allows to the load Pod, such as app=web)
kubectl -n shop run load --image=busybox:1.37 --restart=Never --labels=app=web \
  --overrides='{"spec":{"securityContext":{"runAsNonRoot":true,"runAsUser":65534,"seccompProfile":{"type":"RuntimeDefault"}},"containers":[{"name":"load","image":"busybox:1.37","command":["/bin/sh","-c","while true; do wget -q -O- http://api.shop:9898 >/dev/null; done"],"securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}'
# In a second terminal
kubectl -n shop get hpa api -w
api   Deployment/api   cpu: 3%/60%     2   10   2    2m
api   Deployment/api   cpu: 187%/60%   2   10   2    2m30s
api   Deployment/api   cpu: 187%/60%   2   10   7    2m45s    ← ceil(2×187/60)=7
api   Deployment/api   cpu: 71%/60%    2   10   7    3m15s
api   Deployment/api   cpu: 64%/60%    2   10   7    3m45s    ← 64/60=1.07, outside the 0.05 tolerance, but ceil(7×1.07)=8
api   Deployment/api   cpu: 58%/60%    2   10   8    4m

For a heavier load, run several load Pods in parallel, or use hey: kubectl run hey --image=…/hey -- -z 3m -c 50 http://api.shop:9898 (choose a trusted hey image yourself).

Watch the inputs behind the HPA's decisions
kubectl -n shop describe hpa api | sed -n '/Conditions/,$p'
kubectl -n shop events --for hpa/api
  AbleToScale     True    ScaleDownStabilized  recent recommendations were higher than current one, applying the highest recent recommendation
  ScalingActive   True    ValidMetricFound     the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)
  ScalingLimited  False   DesiredWithinRange   the desired count is within the acceptable range
Normal  SuccessfulRescale  horizontal-pod-autoscaler  New size: 7; reason: cpu resource utilization (percentage of request) above target
Stop the load and watch the scale-down stabilization window
kubectl -n shop delete pod load
kubectl -n shop get hpa api -w     # Scale-down starts only after about 5 minutes (300s scaleDown window + 20%-per-minute policy)
(AKS, optional) Node-level scaling
kubectl config use-context aks-lab
az aks nodepool update -g rg-k8s-lab --cluster-name aks-lab -n nodepool1 \
  --enable-cluster-autoscaler --min-count 3 --max-count 6
kubectl create deploy filler --image=registry.k8s.io/pause:3.10 --replicas=20
kubectl set resources deploy/filler --requests=cpu=1
kubectl get pods -l app=filler --field-selector=status.phase=Pending | wc -l
kubectl get nodes -w           # New nodes appear after 1–3 minutes
kubectl delete deploy filler   # Nodes scale back in after about 10 minutes (default scale-down-unneeded-time)

Cost: each additional D4s_v5 node costs about 0.2 USD per hour. Delete filler as soon as the verification is done.

Cleanup: kubectl -n shop delete hpa api (the capstone lab recreates it).

Case 1: Black Friday traffic and scaling delay

Problem: traffic grows 5x in 2 minutes. The HPA scales out, but new nodes take 3 minutes to arrive, and P99 latency spikes in the meantime.

Approach: ① lower the target utilization from 80% to 55% to leave headroom; ② before the event, use a CronJob or a KEDA cron scaler to raise minReplicas in advance; ③ reserve nodes with low-priority placeholder Pods (pause image + negative PriorityClass). Real Pods preempt them when they arrive, and node scaling refills the capacity in the background; ④ pre-pull images and slim them down.

Limitation: placeholder Pods have a cost, so budget for them at peak.

Case 2: Service Bus consumers scale to 0 overnight

Enable the KEDA add-on on AKS. The ScaledObject uses Workload Identity to read the queue length, with minReplicaCount: 0, and scales up to 30 during the daytime peak. With NAP, idle nodes are consolidated, so overnight compute cost approaches 0. On a 1.37 cluster, you can also evaluate native HPA scale-to-zero (External metrics need a metrics adapter, which KEDA provides).

Case 3: VPA recommendations reveal over-provisioning

Run VPA in updateMode: Off for 40 services for two weeks, then compare Target with actual requests: on average, CPU requests were 3x too high. After gradually lowering the requests, the node count dropped from 18 to 11. Watch the memory baseline of runtimes such as the JVM to avoid OOMKilled (hour 2).

Common errors and fixes

TARGETS shows <unknown>/60% · FailedGetResourceMetric: failed to get cpu utilization: missing request for cpu in container "api"

Cause: some container (including a sidecar or a native sidecar initContainer) has no CPU requests, or metrics-server is unavailable.

kubectl -n shop get deploy api -o jsonpath='{range .spec.template.spec.containers[*]}{.name}{" "}{.resources.requests}{"\n"}{end}'
kubectl get apiservice | grep metrics
kubectl -n kube-system logs deploy/metrics-server | tail

Set requests on every container, or use a ContainerResource metric to look only at the main container.

unable to get metrics for resource cpu: no metrics returned from resource metrics API

Cause: the Pod just started (metrics-server needs at least one collection cycle), or metrics-server cannot reach the kubelet (kind needs --kubelet-insecure-tls; in production, check the kubelet certificate and the network policy for port 10250).

HPA replica count flaps between two values

Cause: noisy metrics, a tolerance that is too small, a scale-down window set to 0, or HPA and GitOps/Helm both managing replicas.

Fix: restore the scaleDown stabilization window (≥ 300s) and raise the tolerance as needed. Remove replicas from the manifest, or set ignoreDifferences on /spec/replicas in Argo CD (Module 1, Case 3).

spec.minReplicas: Invalid value: 0: must be greater than or equal to 1

Cause: HPAScaleToZero is not enabled on the apiserver (clusters before 1.37, or managed platforms that do not expose it), or no Object/External metric is configured.

Fix: check the cluster version and feature gates. If you cannot enable it, use KEDA (minReplicaCount: 0) instead.

Pod stays Pending: 0/3 nodes are available: 3 Insufficient cpu (the nodes do not scale out)

Cause: CA/NAP is not enabled, max-count has been reached, the subscription quota is insufficient, or the Pod's nodeSelector/affinity cannot be satisfied by any node pool (CA ignores such Pods).

kubectl describe pod <pod> | sed -n '/Events/,$p'
kubectl get events -A --field-selector reason=NotTriggerScaleUp
az aks nodepool show -g rg-k8s-lab --cluster-name aks-lab -n nodepool1 --query "{auto:enableAutoScaling,min:minCount,max:maxCount}"
az vm list-usage -l canadacentral -o table | grep -i "DSv5"
Command-line exercises

1. The workload has 4 replicas, average CPU utilization is 90%, the target is 60%, and the tolerance is 0.1. What is the desired replica count? Show your calculation.

Reference answer

The ratio is 90/60 = 1.5. The deviation of 0.5 > 0.1, so a change is needed: ceil(4 × 1.5) = 6. The default scale-up policy allows up to +100% or +4 Pods every 15 seconds (whichever is larger), so 4→6 is allowed and completes in one period.

2. Write the commands that show the HPA's recent scaling events, and read the CPU usage of the Pods in the shop namespace directly from the metrics API.

Reference answer
kubectl -n shop events --for hpa/api --types=Normal
kubectl get --raw /apis/metrics.k8s.io/v1/namespaces/shop/pods | jq '.items[] | {name:.metadata.name, cpu:.containers[].usage.cpu}'

Scenario analysis: traffic drops 1 minute after a promotion ends, but the api replica count stays the same for 5 minutes. The ops team wants to set the scaleDown stabilization window to 0. What is your recommendation?

Reference answer

The default 300-second stabilization window is there to prevent flapping, so this behavior is expected. Setting it to 0 would cause repeated scaling on small traffic rebounds, leading to cold starts and dropped connections. If you really need faster scale-down to save cost, shorten the window to 60–120 seconds and combine it with a policy that scales down by at most 10–20% per minute, and watch for flapping.

Teaching videos

No verified video was found. Titles such as “Kubernetes Autoscaling: HPA vs. VPA vs. Keda vs. CA vs. Karpenter vs. Fargate” came up in search, but the video IDs could not be verified, so no link is listed.

Official docs

Video storyboard script

This courseware cannot generate video or MP3 files directly, so the storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: the traffic curve rises and falls; the boxes for the three fixed Pods turn red at peak.
Narration: Traffic changes, and the replica count should change with it.
Shot 2 · 0:20–1:00
Visual: the formula ceil(2 × 187 / 60) = 7 is filled in step by step; the tolerance range is shown as a gray band.
Narration: Every fifteen seconds, the HPA multiplies the current replica count by the ratio of the current metric to the target, then rounds up. If the ratio is inside the tolerance range, it does nothing.
Shot 3 · 1:00–1:30
Visual: a time series of recommendations; on scale-down, the highest value in the window is used.
Narration: Scale-down has a default 300-second stabilization window. It takes the highest recommendation in that period, which prevents flapping.
Shot 4 · 1:30–2:10
Visual: a Pending Pod → Karpenter creates a new node; KEDA wakes the consumer up from 0.
Narration: The HPA only changes the replica count. When nodes are not enough, hand off to the cluster autoscaler or Karpenter. Event-driven scaling and scale-to-zero are handled by KEDA, or by the HPA scale-to-zero feature in 1.37.
or score ≥ 70% on the quiz

Module 3 · Observability and kubectl debug

14:00 – 22:00 · Metrics tell you that something is wrong, logs and events tell you why, and kubectl debug lets you get into the live environment
8 minmetrics.k8s.io GA · Native Histograms Beta (1.37)★★★★★
Learning goals
  • Distinguish metrics-server (which provides only current values for HPA and kubectl top) from Prometheus (time-series storage and alerting). Know what kube-state-metrics, node-exporter, and cAdvisor each expose.
  • Define the key SLIs for the cluster and write the PromQL for them: restart count, Pending, CPU throttling, OOMKilled, apiserver latency, and error rate.
  • Understand the log path: container stdout/stderr → node /var/log/pods → Fluent Bit / OTel Collector → backend. Get comfortable with kubectl logs and kubectl events.
  • Master the three kubectl debug modes (ephemeral container with --target, --copy-to, and node/) and the profiles (default: general).
  • Understand the AKS managed options: Azure Monitor managed service for Prometheus, Azure Managed Grafana, and Container insights.
Going deeper: for PromQL, alerting rules, Alertmanager, dashboards, and monitoring architecture, see the Prometheus & Grafana 8 + 1 hour course. This module covers only what Kubernetes troubleshooting needs. Prerequisites: Pod lifecycle (hour 1), probes (hour 2), PSS (hour 5). Importance: ★★★★★

What: three pillars + events

SignalQuestion it answersSource in K8sTypical backend
MetricsHow much? How fast? Is it abnormal?kubelet/cAdvisor (container resources), kube-state-metrics (object state), node-exporter (nodes), component /metrics (apiserver, etcd, scheduler), application /metrics (built into podinfo)Prometheus / Azure Monitor managed Prometheus
LogsWhat happened? What are the error details?Container stdout/stderr (written by the kubelet via CRI to /var/log/pods/<ns>_<pod>_<uid>/<ctr>/N.log on the node), node journal (kubelet, containerd), apiserver audit logsLoki, Elasticsearch, Azure Monitor Logs (Container insights)
TracesWhich service is slow for a request?Applications report through the OpenTelemetry SDKTempo, Jaeger, Application Insights
EventsWhat decisions did the control plane make?Event objects (scheduling failures, image pull failures, probe failures, OOM, eviction). By default, only about 1 hour is kept.kubectl events; an event exporter forwards them to the logging system

Why: why metrics-server is not enough

metrics-server keeps only the most recent sample in memory. It serves metrics.k8s.io (GA in 1.37) for the HPA and kubectl top. It has no history, no alerting, and no object state. In production, you need the Prometheus ecosystem: kube-prometheus-stack (a Helm chart, currently 93.x, 2026-11) installs the Prometheus Operator, Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter, and a set of default alerting rules and dashboards in one go. For installation, ServiceMonitor, and PrometheusRule details, see Prometheus hour 5 · kube-prometheus-stack and the Prometheus Operator.

How: key SLIs and PromQL

SLIPromQL (kube-prometheus-stack metric names)Meaning
Container restartsincrease(kube_pod_container_status_restarts_total{namespace="shop"}[15m]) > 2CrashLoop early warning
Pending Podsum by (namespace) (kube_pod_status_phase{phase="Pending"}) > 0Capacity or scheduling problem
CPU throttlingsum by (pod) (rate(container_cpu_cfs_throttled_periods_total{namespace="shop"}[5m])) / sum by (pod) (rate(container_cpu_cfs_periods_total{namespace="shop"}[5m]))> 25% means the CPU limit is too tight (hour 2)
OOMKilledkube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1Memory limit too low, or a leak
Memory near the limitcontainer_memory_working_set_bytes / on(pod,container) kube_pod_container_resource_limits{resource="memory"}The working set is what OOM decisions are based on
apiserver P99 latencyhistogram_quantile(0.99, sum by (le, verb) (rate(apiserver_request_duration_seconds_bucket{verb!~"WATCH|CONNECT"}[5m])))Control plane health
apiserver 5xx ratiosum(rate(apiserver_request_total{code=~"5.."}[5m])) / sum(rate(apiserver_request_total[5m]))—
Node not readykube_node_status_condition{condition="Ready",status="true"} == 0See Module 8; for node pressure, see Module 4
Application error rate (podinfo)sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))RED method; metric names depend on what the application actually exposes
1.37: Native Histograms BetaPrometheus native histograms for Kubernetes component metrics enter Beta in 1.37. Native histograms use sparse exponential buckets instead of fixed le buckets, which gives higher precision and fewer series. Prometheus must enable the matching scrape protocol support. Classic _bucket queries remain usable during the transition. For the exact switches, see the 1.37 release notes.

Three kubectl debug modes

ModeCommandMechanismUse case
Ephemeral containerkubectl debug -it POD --image=busybox:1.37 --target=apiAdds a container to a running Pod through the pods/ephemeralcontainers subresource. --target shares the process namespace of the target container, so you can run ps and read /proc/1/rootdistroless images have no shell; use it for situations that cannot be restarted
Copy Podkubectl debug POD -it --copy-to=api-dbg --container=api -- sh, --set-image=api=…Creates a modified copy (you can change the command, change the image, and share processes). Labels are removed by default, so it does not enter a Service (--keep-labels keeps them)CrashLoopBackOff (change the command to sleep, then get in and look)
Node debuggingkubectl debug node/NODE -it --image=busybox:1.37Creates a Pod on the node that uses the host namespaces, with the node's root filesystem mounted at /host. After chroot /host, you can use journalctl and crictlkubelet/containerd problems, node disk

Profiles (--profile; kubectl currently defaults to general): general, baseline, restricted (meets PSS restricted: non-root, drop ALL; suits namespaces hardened in hour 5), netadmin (adds NET_ADMIN/NET_RAW, so you can run tcpdump), and sysadmin (privileged). --custom accepts a partial container spec for further customization.

Common misconceptions ① “Ephemeral containers can be deleted.” They cannot be deleted on their own; they disappear only when the Pod is deleted. You also cannot set ports or probes. ② “kubectl logs shows all the logs.” It reads only the current files on the node (plus the previous container instance with --previous). Rotated logs and logs from deleted nodes are gone, so production must collect logs centrally. ③ “Events are kept indefinitely.” They are kept for about 1 hour by default (apiserver --event-ttl). ④ In a PSS restricted namespace, an ephemeral container with the default general profile may be rejected. Use --profile=restricted.

Comparison with similar technologies (AKS)

NeedSelf-managedAzure managed
Metricskube-prometheus-stackAzure Monitor managed service for Prometheus (az aks update --enable-azure-monitor-metrics; optionally --enable-control-plane-metrics)
VisualizationGrafanaAzure Managed Grafana (linked with --grafana-resource-id), or the built-in Azure Monitor dashboards with Grafana in the portal
LogsFluent Bit + Loki / ESContainer insights (az aks enable-addons --addon monitoring); data goes to Log Analytics

Architecture diagram: metrics and logs pipelines

Worker node Pod apistdout · /metrics kubelet + cAdvisor/metrics/cadvisor /var/log/pods/shop_api-…/api/0.log (CRI format) Fluent Bit /OTel Collector DS node-exporter DS:9100 journald: kubelet, containerd(view after running kubectl debug node/ and then chroot /host) Prometheus (Operator)ServiceMonitor / PodMonitor discover targetsScrape → TSDB → ruleskube-state-metrics: object state Alertmanager → Teams/PagerDuty Grafana dashboards Log backendLoki / ES / Log AnalyticsSearch by namespace/pod labels kube-apiserverkubectl logs (reads files through the kubelet)kubectl events (Event objects) AKS: ama-metrics (managed Prometheus) and ama-logs (Container insights) run as a DaemonSet/Deployment
Figure 3-1: kubectl logs reads files on the live node, while centralized logging is for archived search; the two complement each other

Workflow for an ephemeral container with kubectl debug

kubectl debug--target=api PATCH pods/…/ephemeralcontainers Admission: PSA checkThe profile determines the fields kubelet watchCRI starts it in the same sandbox attach terminalShares net + target pid namespace RBAC: needs patch permission on pods/ephemeralcontainers and create permission on pods/attach (hour 5)
Figure 3-2: an ephemeral container does not change the Pod's spec.containers and does not trigger a restart

Step-by-step animation: from one alert to the root cause (api memory leak)

Demonstrates a real troubleshooting path: alert (PromQL) → dashboard → events → logs → kubectl debug → fix. Each step shows the real command and output below it.

Click “Play.”
ALERT KubePodCrashLooping firing

Core commands

CommandPurposeKey flags
kubectl logs POD -c CTRGet container logs--all-containers, -f, --tail=100, --since=10m, --timestamps
kubectl logs POD --previousLogs from the previous (crashed) container instanceRequired for CrashLoopBackOff
kubectl logs -l app=api --prefixAggregate logs across multiple Pods by label--max-log-requests=10
kubectl logs deploy/apiPick one Pod from a DeploymentOnly one Pod
kubectl eventsEvents (sorted by time; easier to read than get events)--for pod/NAME, --types=Warning, -w, -A, -o kyaml
kubectl top pod/nodeCurrent resource usage--containers, --sort-by=memory
kubectl debugDebugging--target, --copy-to, --set-image, --share-processes (default true), --profile (default general), --custom
kubectl get --raw /metricsapiserver's own metricsFor example, | grep apiserver_requested_deprecated_apis (Module 5)

Install kube-prometheus-stack (kind, optional after class)

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm search repo prometheus-community/kube-prometheus-stack --versions | head -3
helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace \
  --version <version from the previous step> --set grafana.adminPassword='ChangeMe!' --wait --timeout 10m
kubectl -n monitoring get pods
kubectl -n monitoring port-forward svc/kps-prometheus 9090:9090

Resource needs: about 2 vCPU / 3 GiB. A kind cluster on D4s_v5 is sufficient. In production, pin the chart version and manage the values through GitOps.

kubectl debug examples

# ① Ephemeral container: shares the process namespace of the api container (use the restricted profile for restricted namespaces)
kubectl -n shop debug -it deploy/api --image=busybox:1.37 --target=api --profile=restricted -- sh
#   Inside the debug container: ps; ls /proc/1/root/; wget -qO- localhost:9898/env

# ② Copy the Pod: replace the crashing container's command, then get in and check the configuration
kubectl -n shop debug api-7d9c-xyz -it --copy-to=api-dbg --container=api -- sh
kubectl -n shop debug api-7d9c-xyz --copy-to=api-dbg2 --set-image=api=ghcr.io/stefanprodan/podinfo:6.17.0

# ③ Node debugging: inspect kubelet / containerd
kubectl debug node/lab-worker -it --image=busybox:1.37 --profile=sysadmin
#   chroot /host; journalctl -u kubelet --since "10 min ago" | tail; crictl ps -a | head
kubectl get pods -A | grep node-debugger      # Remember to delete it after you exit
kubectl delete pod node-debugger-lab-worker-xxxxx
Targeting container "api". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-7xk2p.
/ $ ps
PID   USER     TIME  COMMAND
    1 10001     0:01 ./podinfo --port=9898 ...
   23 10001     0:00 sh

How to verify: kubectl -n shop get pod POD -o jsonpath='{.spec.ephemeralContainers[*].name}'. Common errors: ephemeral containers are disabled for this cluster (very old versions); pods "x" is forbidden: violates PodSecurity (switch the profile). Production uses: troubleshooting distroless images, and network packet capture (netadmin profile + netshoot image).

Lab 3: logs, events, and the three kubectl debug modes (about 10 min, kind)

Create a CrashLoopBackOff
kubectl -n shop create deploy crashy --image=ghcr.io/stefanprodan/podinfo:6.17.0 -- ./podinfo --port=bad
kubectl -n shop patch deploy crashy --type=json -p='[{"op":"add","path":"/spec/template/spec/securityContext","value":{"runAsNonRoot":true,"runAsUser":10001,"seccompProfile":{"type":"RuntimeDefault"}}},{"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]'
kubectl -n shop get pods -l app=crashy -w
Events + logs from the previous instance
P=$(kubectl -n shop get pod -l app=crashy -o name | head -1)
kubectl -n shop events --for $P --types=Warning
kubectl -n shop logs $P --previous --tail=20
kubectl -n shop get $P -o jsonpath='{.status.containerStatuses[0].lastState.terminated}{"\n"}'
LAST SEEN   TYPE      REASON    OBJECT              MESSAGE
10s         Warning   BackOff   pod/crashy-6b…      Back-off restarting failed container podinfo in pod crashy-6b…
Error: invalid argument "bad" for "--port" flag: strconv.ParseInt: parsing "bad": invalid syntax
{"exitCode":1,"reason":"Error",...}
Copy the Pod and change the command to get into the live environment
kubectl -n shop debug ${P#pod/} -it --copy-to=crashy-dbg --container=podinfo -- sh
# In the copy: ls /home/app; ./podinfo --help | head; exit
kubectl -n shop delete pod crashy-dbg
Debug a running api with an ephemeral container (distroless approach)
API=$(kubectl -n shop get pod -l app=api -o name | head -1)
kubectl -n shop debug -it $API --image=busybox:1.37 --target=api --profile=restricted -- sh -c 'ps; wget -qO- localhost:9898/healthz; echo; cat /proc/1/cmdline | tr "\0" " "'
kubectl -n shop get $API -o jsonpath='{.spec.ephemeralContainers[*].name}{"\n"}'
Node debugging
kubectl debug node/lab-worker -it --image=busybox:1.37 --profile=sysadmin -- chroot /host sh -c 'ls /var/log/pods | head; df -h /var | tail -1'

kind nodes are Docker containers, so journalctl may not be available. On AKS nodes, you can see the full kubelet journal.

(Optional) PromQL: after installing kube-prometheus-stack, run the restart and throttling queries from the “How it works” tab in the Prometheus UI, and watch the restart count for crashy.
Cleanup: kubectl -n shop delete deploy crashy; kubectl get pods -A | grep node-debugger | awk '{print $2}' | xargs -r kubectl delete pod

Case 1: CPU limit causes P99 jitter

Symptom: average CPU is only 30%, but P99 latency spikes periodically. Evidence: a throttling-ratio query shows that 40% of CFS periods are throttled. Approach: raise or remove the CPU limit (keep the requests), and use an HPA to handle load. For latency-sensitive services, watch container_cpu_cfs_throttled_periods_total.

Case 2: rolling out managed observability on AKS

az monitor account create -g rg-k8s-lab -n amw-k8s-lab -l canadacentral        # Azure Monitor workspace
az grafana create -g rg-k8s-lab -n grafana-k8s-lab                              # Azure Managed Grafana (requires the amg extension)
az aks update -g rg-k8s-lab -n aks-lab --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $(az monitor account show -g rg-k8s-lab -n amw-k8s-lab --query id -o tsv) \
  --grafana-resource-id $(az grafana show -g rg-k8s-lab -n grafana-k8s-lab --query id -o tsv)
az aks enable-addons -g rg-k8s-lab -n aks-lab --addon monitoring                # Container insights

Note: starting with AKS 1.37, managed Prometheus applies namespace-scoped access to the Secrets referenced by basicAuth in ServiceMonitor/PodMonitor. Configure this before upgrading, following the AKS version notes (see the upgrade checklist in Module 5). Container insights is billed by log ingestion volume, so configure data collection rules to collect only the namespaces you need.

Case 3: troubleshooting distroless images in production

Production images have no shell. In the past, the team “temporarily switched to a debug image and redeployed,” which destroyed the evidence. Instead, grant the on-call team the pods/ephemeralcontainers permission (the audit log records each debug session), and use kubectl debug --target --profile=restricted to get in. When packet capture is needed, use the netadmin profile with the netshoot image, and make sure the namespace PSS allows it (or copy the Pod into a separate debug namespace).

Common errors and fixes

Error from server (BadRequest): previous terminated container "api" in pod "api-…" not found

Cause: the container has not restarted yet, or the Pod has been recreated (the new Pod has no “previous instance”).

Fix: look in the centralized logging system, or run kubectl get pod -o yaml and check lastState.terminated (includes exitCode, reason, and message).

Error from server (Forbidden): pods "api-…" is forbidden: violates PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "debugger-xxxx" …)

Cause: the ephemeral container created with the default general profile does not meet restricted.

kubectl -n shop debug -it POD --image=busybox:1.37 --target=api --profile=restricted
error: unable to upgrade connection: container not found ("debugger-xxxx")

Cause: the ephemeral container image failed to pull, or it exits immediately (for example, the image has no sh).

kubectl -n shop get pod POD -o jsonpath='{.status.ephemeralContainerStatuses}' | jq
kubectl top: error: Metrics API not available

Cause: metrics-server is not installed, or the APIService v1(beta1).metrics.k8s.io is unavailable (False (FailedDiscoveryCheck)).

kubectl get apiservice | grep metrics
kubectl -n kube-system describe deploy metrics-server | tail -20
Prometheus target DOWN: context deadline exceeded (ServiceMonitor cannot scrape the Pods)

Cause: the NetworkPolicy from hour 3 denies traffic from the monitoring namespace to shop by default, or the ServiceMonitor's label selector does not match Prometheus's serviceMonitorSelector.

Fix: add an ingress rule to shop that allows traffic from kubernetes.io/metadata.name: monitoring (port 9898), and check whether the ServiceMonitor has the release label.

Command-line exercises

1. List the logs from the last 10 minutes for all Pods with app=api in shop, with the Pod name prefix and timestamps.

Reference answer
kubectl -n shop logs -l app=api --all-containers --prefix --timestamps --since=10m

2. Use netshoot inside the distroless api Pod to capture packets on port 9898 (the namespace PSS is baseline).

Reference answer
kubectl -n shop debug -it POD --image=nicolaka/netshoot --target=api --profile=netadmin -- tcpdump -i any -nn port 9898 -c 20

netadmin adds NET_ADMIN/NET_RAW, which may not satisfy restricted. In a restricted namespace, copy the Pod into a debug namespace instead.

Scenario analysis: an alert shows OOMKilled for api, but kubectl top shows memory at only 60% of the limit. How do you explain this, and how do you continue troubleshooting?

Reference answer

kubectl top shows a current sample, but the OOM happens at a momentary peak, and the new container after the kill uses very little. Use Prometheus to check the historical peak of container_memory_working_set_bytes and kube_pod_container_status_last_terminated_reason. Combine that with kubectl logs --previous to see the requests before the crash. If needed, raise the limit, or run VPA in Off mode to observe recommendations, and look for sudden large requests or a memory leak.

Verified teaching videos

▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · about 2021 · Prometheus architecture, scrape model, metric types
▶
Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1 — TechWorld with Nana
English · installing the Prometheus Operator with Helm (the chart version has been updated; follow the commands in this hour)

No kubectl debug tutorial with a verifiable video ID was found. Please follow the official docs.

Official docs

Later courses in this series

Video storyboard script

This courseware cannot generate video or MP3 files directly, so the storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: alert pop-up “KubePodCrashLooping”.
Narration: Metrics tell you that something went wrong, but not why.
Shot 2 · 0:25–1:00
Visual: terminal output of kubectl events and logs --previous, side by side.
Narration: Events tell you what the control plane saw. Logs from the previous container instance tell you why the app exited.
Shot 3 · 1:00–1:40
Visual: an animation of an ephemeral container joining a Pod, with ps showing the target process.
Narration: kubectl debug adds a tool-equipped ephemeral container to a running Pod. It shares the process namespace without restarting anything or destroying the evidence.
Shot 4 · 1:40–2:00
Visual: icons for Prometheus, Grafana, and Container insights connected to AKS.
Narration: On AKS, you can build the same capabilities with managed Prometheus, Grafana, and Container insights.
or score ≥ 70% on the quiz

Module 4 · Reliability: node-pressure eviction, node shutdown, and the disruption landscape

22:00 – 29:00 · When and in what order the kubelet actively kills Pods; what happens when a node shuts down; which of the six ways a Pod can disappear respect PDBs and graceful termination
7 minPod disruption conditions GA (1.31) · Non-graceful node shutdown GA (1.28)Graceful node shutdown Beta (on by default) · HugepageAwareEviction Beta (1.37)
Learning goals
  • Explain the kubelet's eviction signals (memory.available, nodefs.*, imagefs.*, containerfs.*, pid.available), the Linux default hard thresholds, and the roles of soft thresholds, grace periods, evictionMinimumReclaim, and the pressure transition period.
  • Work through the official rules for node-pressure eviction order: first check whether usage exceeds requests, then Priority, and finally how far usage exceeds requests. Explain why Guaranteed does not mean “never evicted.”
  • Configure graceful node shutdown (shutdownGracePeriod, shutdownGracePeriodCriticalPods, and the priority-based shutdownGracePeriodByPodPriority), and distinguish it from non-graceful shutdown (the out-of-service taint).
  • Use a table to tell apart six Pod termination paths: kubectl delete, API-initiated eviction (drain), scheduler preemption, node-pressure eviction, taint-based eviction, and OOM Kill. Cover which ones respect PDBs, which respect terminationGracePeriodSeconds, and the reason in the DisruptionTarget condition.
Content covered elsewhere (review it): requests/limits, QoS, and allocatable (hour 2 · Module 1); PDBs and drain, unhealthyPodEvictionPolicy (hour 2 · Module 4); PriorityClass and scheduler preemption (hour 2 · Module 8); podFailurePolicy and DisruptionTarget (hour 2 · Module 7); the out-of-service taint and forced volume detach (hour 4 · Module 8); ResourceQuota / LimitRange (hour 5 · Module 8). Importance: ★★★★★

What: Node-pressure Eviction

The kubelet checks node resources every housekeeping-interval (default 10 seconds). When an eviction signal crosses its threshold, the kubelet first tries to reclaim node-level resources (remove exited containers and unused images). If that is not enough, it makes some Pods fail (phase=Failed, reason=Evicted) to protect the node itself. This is a local decision made by the kubelet. It does not go through the Eviction API and does not respect PDBs.

SignalMeaningLinux default hard thresholdCorresponding node condition / taint
memory.availableCapacity − working set (excluding inactive_file). Starting in 1.37, it also subtracts the total hugepage amount by default (HugepageAwareEviction Beta).<100Mi (500Mi on Windows)MemoryPressure · node.kubernetes.io/memory-pressure:NoSchedule
nodefs.available / nodefs.inodesFreeFilesystem holding the kubelet root directory (emptyDir, logs, Pod directories)<10% / <5%DiskPressure · node.kubernetes.io/disk-pressure:NoSchedule
imagefs.available / imagefs.inodesFreeFilesystem where the container runtime stores images (and writable layers), if separate<15% / <5%
containerfs.available / containerfs.inodesFreeUsed when the writable layer is on its own disk (split image filesystem)Follows nodefs or imagefs
pid.availableMaximum PIDs − current process countNone by defaultPIDPressure · node.kubernetes.io/pid-pressure:NoSchedule
KubeletConfiguration fieldPurposeDefault
evictionHardHard threshold: evicts immediately once crossed, with a grace period of 0 seconds (does not wait for terminationGracePeriodSeconds)See the table above
evictionSoft + evictionSoftGracePeriodSoft threshold: evicts only after the threshold has been crossed for a set duration, for example memory.available<1.5Gi for 1m30sNone
evictionMaxPodGracePeriodMaximum graceful termination time given to a Pod during a soft eviction (the smaller of this value and the Pod's own grace period)0
evictionMinimumReclaimThe minimum amount to reclaim each time, to avoid repeated evictions when usage sits right at the thresholdAll resources are 0
evictionPressureTransitionPeriodHow long the node condition must wait before it changes from True back to False (debounce)5m
systemReserved / kubeReservedReserved from allocatable for the system and kubelet (allocatable = capacity − reserved − hard eviction threshold; hour 2)Set by the distribution / cloud platform

How: which Pods are evicted? The official ordering rules

  1. Pods whose usage exceeds their requests go first (BestEffort Pods have requests of 0, so any usage counts as exceeding). Within this group, order by Priority from low to high, then by how far usage exceeds requests, from largest to smallest.
  2. Pods whose usage is below their requests go last (Guaranteed, and well-behaved Burstable Pods), ordered by Priority from low to high within the group.
  3. Inode and PID pressure have no concept of requests, so they are ordered by Priority only.

The official docs state clearly that the kubelet does not rank by QoS class directly. It uses the three parameters above instead. QoS has its effect only as a result: Guaranteed Pods usually do not exceed their requests, so they rank later. The kubelet also keeps running static Pods. The kernel OOM killer, on the other hand, selects processes based on oom_score_adj (Guaranteed −997, BestEffort 1000, Burstable between 2 and 999, system-node-critical −997). It is faster and blunter than kubelet eviction.

Node shutdown: graceful and non-graceful

MechanismStatusHow it worksKey configuration
Graceful node shutdown (Linux)Beta, on by default since 1.21The kubelet delays shutdown through a systemd inhibitor lock. After detecting the shutdown, it marks the node NotReady (reason node is shutting down), terminates regular Pods first, and then critical Pods.shutdownGracePeriod: 30s, shutdownGracePeriodCriticalPods: 10s (both default to 0, meaning disabled; the latter must be smaller than the former)
Priority-based graceful shutdownBeta (the 1.37 page marks it as on by default)Terminates Pods in batches by PriorityClass, with a separate grace period for each batchshutdownGracePeriodByPodPriority list
Graceful node shutdown (Windows)Beta, on by default since 1.34The kubelet registers preshutdown handling when it runs as a Windows serviceSame fields as above
Non-graceful node shutdownGA (1.28)When the kubelet has no chance to run the shutdown process (power loss, kernel crash), the administrator adds the node.kubernetes.io/out-of-service taint (NoExecute or NoSchedule) after confirming the node is down. The control plane then force-deletes the Pods and detaches their volumes.See hour 4, Module 8. There is also a timeout that forces volume detach after 6 minutes

Gracefully terminated Pods show Reason: Terminated and Message: Pod was terminated in response to imminent node shutdown. Controllers recreate them on other nodes. Planned maintenance on cloud platforms (such as AKS node image upgrades, or EKS/GKE node replacement) usually uses cordon + drain (the Eviction API). Only Spot reclaim and host failures depend on the kubelet's shutdown handling.

Why: one table to understand the six ways a Pod can disappear

MethodInitiatorRespects PDB?Respects terminationGracePeriodSeconds?DisruptionTarget reason
kubectl delete pod / controller scale-in / rolling updateUser / controllerNoYes—
API-initiated eviction (kubectl drain, upgrades, CA scale-in)Eviction APIYes (returns 429 if not allowed)YesEvictionByEvictionAPI
Scheduler preemptionkube-schedulerTries to, but not guaranteedYesPreemptionByScheduler
Taint-based eviction (NotReady/unreachable for longer than tolerationSeconds, default 300s)Node lifecycle controller (taint manager)NoYes (but the kubelet cannot run it when the node is unreachable)DeletionByTaintManager
Node-pressure eviction / graceful node shutdown / critical Pod preemptionkubeletNoHard threshold 0s; soft threshold uses evictionMaxPodGracePeriod; shutdown follows the shutdown configurationTerminationByKubelet
OOM Kill (container exceeds its memory limit, or node memory is exhausted)Linux kernelNoNo (SIGKILL, exit code 137)— (container lastState reason=OOMKilled)

The PDB page states clearly that involuntary disruptions (node-pressure eviction, hardware failure) cannot be blocked by a PDB, but they count against the budget. After node-pressure eviction removes a replica, a drain may get stuck because the budget is used up.

When: production configuration recommendations

  • Critical services: Guaranteed, or Burstable with “requests ≈ actual usage,” plus a higher PriorityClass. Use BestEffort only for disposable batch work.
  • Set soft thresholds (for example memory.available<500Mi for 1m) to give applications time to exit gracefully, and keep the hard threshold as the last line of defense. On managed clusters, adjust this through node configuration (AKS custom node configuration, EKS node template / launch template, GKE node system configuration), and follow what the platform supports.
  • Set sizeLimit on emptyDir, and set requests/limits for ephemeral-storage on containers, so that one Pod cannot fill nodefs and take down the whole node.
  • On self-managed nodes, enable graceful shutdown (shutdownGracePeriod ≥ the longest terminationGracePeriodSeconds + the time for critical Pods).
Common misconceptions ① “A PDB protects the replica count under node memory pressure.” It does not; the kubelet does not look at PDBs. ② “Guaranteed Pods are never evicted.” They are simply ranked last; they can still be evicted or OOM-killed if system processes consume all the node's memory. ③ “Evicted Pods disappear automatically.” They remain in the API in the Failed state until Pod GC (terminated-pod-gc-threshold) or manual cleanup removes them. ④ “kubectl delete is the same as drain.” Delete bypasses PDBs. ⑤ “A hard eviction waits for preStop.” The hard threshold grace period is 0.

Decision flow: what the kubelet does every 10 seconds

Collect signalscAdvisor / CRI stats Threshold crossed?hard: immediately · soft: must persist Set node conditionMemoryPressure=True → taint Reclaim node-level resourcesGC containers · delete unused images Still short → evictOne Pod at a time No → if the condition is True, wait the 5m transition period before it returns to False Ordering (memory signal) Group 1: usage > requests (evicted first)BestEffort (requests=0), Burstable Pods over their requestsWithin the group: Priority low → high, then overage large → small Group 2: usage ≤ requests (last)Guaranteed, well-behaved Burstable PodsWithin the group: Priority low → high
Figure 4-1: eviction is the kubelet's local self-rescue. It does not go through the apiserver's Eviction subresource, so PDBs do not apply

Timeline: three termination paths on the same node

drain (API eviction) Check PDB (429/200) preStop + SIGTERM (grace period) A replacement Pod is already running elsewhere Soft-threshold eviction Crossed for 1m30s SIGTERM (≤ maxPodGrace) Failed / Evicted Hard-threshold eviction Triggered as soon as it is crossed Grace period 0s (terminated immediately) Failed / Evicted The value of soft thresholds: they give applications time to flush buffers and disconnect. The hard threshold is the last line of defense that protects the node.
Figure 4-2: both are “evicted,” but the degree of graceful termination differs a lot

Interactive simulator: node memory pressure → kubelet eviction order

Node capacity is 4000Mi, with 600Mi used by the system and kubelet. batch-1 (BestEffort) has a memory leak that grows by 200Mi every 10-second cycle. After you select threshold mode, click “Step” or “Run” and watch the MemoryPressure condition, the taint, the eviction order, and the evicted Pods.

Node lab-worker
kubelet eviction order (first to last)
Click “Step” or “Run.”
Usage ≤ requestsUsage > requestsEvicted
$ kubectl describe node lab-worker | grep -A6 Conditions

Core commands

CommandPurposeNotes
kubectl get --raw "/api/v1/nodes/NODE/proxy/configz" | jq .kubeletconfigView the kubelet configuration actually in effectRequires nodes/proxy permission. Look at evictionHard and shutdownGracePeriod
kubectl describe node NODE | sed -n '/Conditions/,/Addresses/p'MemoryPressure / DiskPressure / PIDPressureWhen the condition is True, the matching NoSchedule taint appears
kubectl get pods -A --field-selector=status.phase=FailedFind evicted (Failed) PodsThe STATUS column shows Evicted or Error
kubectl get pod P -o jsonpath='{.status.reason}{" "}{.status.message}'Eviction reasonFor example, Evicted The node was low on resource: memory.
kubectl get pod P -o jsonpath='{.status.conditions[?(@.type=="DisruptionTarget")]}'Disruption reason conditionFor the reason, see the table in “How it works”
kubectl create --raw /api/v1/namespaces/NS/pods/P/eviction -f eviction.jsonCall the Eviction API directlyReturns 429 TooManyRequests if the PDB does not allow it
kubectl events -A --types=Warning | grep -Ei "evict|pressure"Eviction and pressure eventskubelet events: Evicted, EvictionThresholdMet
kubectl delete pods -A --field-selector=status.phase=FailedClean up leftover Failed PodsFirst confirm that there is no evidence you need to keep

KubeletConfiguration snippet (self-managed nodes / node template)

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
systemReserved:  { cpu: 200m, memory: 500Mi }
kubeReserved:    { cpu: 200m, memory: 500Mi }
evictionHard:
  memory.available: "200Mi"
  nodefs.available: "10%"
  imagefs.available: "15%"
  nodefs.inodesFree: "5%"
evictionSoft:            { memory.available: "500Mi" }
evictionSoftGracePeriod: { memory.available: "1m" }
evictionMaxPodGracePeriod: 60
evictionMinimumReclaim:  { memory.available: "200Mi" }
evictionPressureTransitionPeriod: 5m
shutdownGracePeriod: 60s
shutdownGracePeriodCriticalPods: 20s

Note: once you set any item in evictionHard, whether unlisted signals use their defaults or 0 depends on version behavior. In production, list every threshold you need explicitly. On managed clusters, you generally cannot edit the kubelet file directly, so use the platform's node configuration feature instead.

emptyDir and ephemeral storage limits (the kubelet can also evict an individual Pod for these)

containers:
  - name: worker
    resources:
      requests: { ephemeral-storage: 100Mi }
      limits:   { ephemeral-storage: 500Mi }     # exceeded → kubelet evicts the Pod
volumes:
  - name: cache
    emptyDir: { sizeLimit: 200Mi }               # exceeded → evicted (Usage of EmptyDir volume "cache" exceeds the limit)

Lab 4: seeing the difference between kubelet eviction and API eviction (about 10 min, kind)

Read the kubelet's eviction and shutdown configuration
kubectl config use-context kind-lab
kubectl get --raw "/api/v1/nodes/lab-worker/proxy/configz" | \
  jq '.kubeletconfig | {evictionHard, evictionPressureTransitionPeriod, shutdownGracePeriod, shutdownGracePeriodCriticalPods}'
{
  "evictionHard": { "imagefs.available": "0%", "nodefs.available": "0%", "nodefs.inodesFree": "0%" },
  "evictionPressureTransitionPeriod": "5m0s",
  "shutdownGracePeriod": "0s",
  "shutdownGracePeriodCriticalPods": "0s"
}

To keep disk pressure on developer machines from causing evictions, kind usually sets the disk thresholds to 0%. A graceful shutdown value of 0 means it is disabled. Production nodes (AKS/EKS/GKE) use different values, so run the same commands on your own cluster to compare.

Make the kubelet evict a Pod for exceeding its emptyDir limit (satisfies the PSS restricted policy of the shop namespace)
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata: { name: filler, namespace: shop, labels: { app: filler } }
spec:
  securityContext: { runAsNonRoot: true, runAsUser: 65534, seccompProfile: { type: RuntimeDefault } }
  containers:
    - name: c
      image: busybox:1.37
      command: ["sh","-c","dd if=/dev/zero of=/cache/blob bs=1M count=40; sleep 3600"]
      securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ["ALL"] } }
      resources: { requests: { cpu: 10m, memory: 16Mi }, limits: { memory: 64Mi } }
      volumeMounts: [{ name: cache, mountPath: /cache }]
  volumes:
    - name: cache
      emptyDir: { sizeLimit: 20Mi }
EOF
kubectl -n shop get pod filler -w          # Becomes Evicted / Error after about 10–60 seconds
kubectl -n shop get pod filler -o jsonpath='{.status.phase}{" | "}{.status.reason}{" | "}{.status.message}{"\n"}'
kubectl -n shop events --for pod/filler
Failed | Evicted | Usage of EmptyDir volume "cache" exceeds the limit "20Mi".
Warning  Evicted   pod/filler   Usage of EmptyDir volume "cache" exceeds the limit "20Mi".

This is a local eviction by the kubelet, enforcing the temporary storage limit on a single Pod. A bare Pod is not recreated after eviction, which is one reason not to run bare Pods directly in production.

Comparison: API eviction is subject to PDBs, but delete is not
kubectl -n shop create deploy rel --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=2
kubectl -n shop patch deploy rel --type=json -p='[{"op":"add","path":"/spec/template/spec/securityContext","value":{"runAsNonRoot":true,"runAsUser":10001,"seccompProfile":{"type":"RuntimeDefault"}}},{"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]'
kubectl -n shop rollout status deploy/rel
kubectl -n shop create pdb rel --selector=app=rel --min-available=2
P=$(kubectl -n shop get pod -l app=rel -o jsonpath='{.items[0].metadata.name}')
cat > eviction.json <<EOF
{"apiVersion":"policy/v1","kind":"Eviction","metadata":{"name":"$P","namespace":"shop"}}
EOF
kubectl create --raw /api/v1/namespaces/shop/pods/$P/eviction -f eviction.json
Error from server (TooManyRequests): Cannot evict pod as it would violate the pod's disruption budget.
kubectl -n shop delete pod $P              # Direct delete: succeeds, the PDB does not apply
kubectl -n shop get pdb rel                 # ALLOWED DISRUPTIONS is 0 until the new Pod is Ready
Understand DisruptionTarget: change the PDB to --min-available=1 (first kubectl -n shop delete pdb rel, then create it again). Run the create --raw from the previous step again, then check the conditions of the evicted Pod right away:
kubectl -n shop get pod $P -o jsonpath='{.status.conditions[?(@.type=="DisruptionTarget")]}{"\n"}'
{"type":"DisruptionTarget","status":"True","reason":"EvictionByEvictionAPI","message":"Eviction API: evicting", …}
(Optional, AKS/self-managed nodes): before running sudo systemctl poweroff on a test node, run a Pod with a preStop hook on that node. With shutdownGracePeriod enabled, watch for Message: Pod was terminated in response to imminent node shutdown. kind nodes are containers, so they are not suitable for demonstrating shutdown.
Cleanup: kubectl -n shop delete pod filler --ignore-not-found; kubectl -n shop delete deploy rel; kubectl -n shop delete pdb rel; rm -f eviction.json

Case 1: batch jobs get online services evicted along with them

Symptom: a nightly ETL job (BestEffort) runs alongside api on the same nodes. The node has MemoryPressure, and the kubelet evicted the ETL first, but two api replicas were evicted too. Cause: api is Burstable, with 64Mi of requests and 300Mi of actual usage. It is in group 1 (usage above requests), so it ranks ahead along with the ETL. Approach: based on VPA recommendations, raise api's memory requests to its P95 usage (group 2). Give api PriorityClass 100000 and the ETL −10. Move the ETL to a separate, tainted node pool. Configure soft thresholds to give api time to exit gracefully.

Case 2: logs fill the node → DiskPressure chain reaction

Symptom: a Pod writes debug logs to an emptyDir. nodefs drops below 10%, so the node gets the disk-pressure taint and new Pods cannot be scheduled there. Meanwhile the kubelet starts deleting unused images and evicting Pods, and when evicted Pods are recreated, their images must be pulled again. Approach: set sizeLimit on all emptyDirs, set ephemeral-storage limits on containers, write application logs to stdout, and alert on kube_node_status_condition{condition="DiskPressure",status="true"} (Module 3).

Case 3: drain gets stuck during node maintenance, while the kubelet also evicts a replica at the same time

Symptom: during an upgrade, api has only 1 Ready replica left, and drain returns 429 and hangs for 30 minutes. Cause: memory-pressure eviction on another node removed one api replica. Involuntary disruptions cannot be blocked by a PDB, but they count against the budget, so the PDB's ALLOWED DISRUPTIONS dropped to 0. Approach: before upgrading, check node pressure and Failed Pods. Set maxUnavailable: 1 on the PDB with unhealthyPodEvictionPolicy: AlwaysAllow (hour 2). Plan capacity so that no pressure eviction is triggered during the upgrade (Module 5).

Common errors and fixes

Status: Failed · Reason: Evicted · Message: The node was low on resource: memory. Threshold quantity: 100Mi, available: 87232Ki. Container api was using 412Mi, request is 64Mi, has larger consumption of memory.

Cause: node memory-pressure eviction. The message already tells you that usage is far above requests, which is why this Pod ranks first.

kubectl describe node NODE | sed -n '/Conditions/,/Addresses/p'
kubectl top pods -A --sort-by=memory | head
kubectl get pod P -o jsonpath='{.spec.containers[*].resources}'

Raise requests to the real usage, limit unbounded caches, or lower the priority of disposable workloads or isolate them into a separate node pool.

Warning EvictionThresholdMet node/NODE Attempting to reclaim ephemeral-storage (node DiskPressure)

Cause: nodefs/imagefs is below the threshold. The kubelet first cleans up dead containers and unused images, then evicts Pods.

kubectl debug node/NODE -it --image=busybox:1.37 --profile=sysadmin -- chroot /host sh -c 'df -h /var/lib; du -sh /var/log/pods/* | sort -h | tail -5'

Set sizeLimit on emptyDirs; adjust container log rotation (containerLogMaxSize); expand the node OS disk.

Error from server (TooManyRequests): Cannot evict pod as it would violate the pod's disruption budget.

Cause: API eviction was rejected by a PDB (429). This can happen when replicas are not Ready, or when the budget is already used up by other disruptions.

kubectl get pdb -A; kubectl -n shop describe pdb api
kubectl -n shop get pods -l app=api -o wide

Official guidance: pause automated operations and investigate first. Only delete the Pod directly after you confirm that the interruption is acceptable.

Error from server (InternalError): … This pod has more than one PodDisruptionBudget, which the eviction subresource does not support.

Cause: multiple PDBs select the same Pod, so the Eviction API returns 500. Fix: run kubectl get pdb -A -o wide to find the overlapping selectors, then merge them into one.

After a node shuts down, the Pod stays in Terminating, and the StatefulSet replica is slow to be recreated.

Cause: the shutdown was not graceful, so kubelet cannot confirm the deletion. To avoid dual writes, the StatefulSet does not create a Pod with the same name early.

Fix: after you confirm the node is really powered off, add the node.kubernetes.io/out-of-service=nodeshutdown:NoExecute taint (for the detach steps, see hour 4, Module 8). After recovery, remove the taint.

Command-line exercise

1. List all Pods in the cluster that were evicted (Failed with reason Evicted), and output the namespace, name, and message.

Reference answer
kubectl get pods -A --field-selector=status.phase=Failed \
  -o jsonpath='{range .items[?(@.status.reason=="Evicted")]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.status.message}{"\n"}{end}'

2. Write an Eviction request that evicts the Pod api-0 in the shop namespace, and explain what 429 means.

Reference answer
echo '{"apiVersion":"policy/v1","kind":"Eviction","metadata":{"name":"api-0","namespace":"shop"}}' > ev.json
kubectl create --raw /api/v1/namespaces/shop/pods/api-0/eviction -f ev.json

429 means the eviction would violate a PDB right now (it can also be API rate limiting). Retry later, or first fix the replica readiness problem.

Scenario analysis: when a node is under memory pressure, which of these three Pods is evicted first? A: Guaranteed, Priority 0, usage = requests. B: Burstable, Priority 100000, requests 128Mi, usage 400Mi. C: BestEffort, Priority 0, usage 200Mi.

Reference answer

B and C are both in group 1, where usage exceeds requests. Within the group, they are sorted by Priority from low to high, so C (0) comes before B (100000). A is last, in group 2. The order is C → B → A. Note that B has a higher priority but still ranks ahead of A because it exceeds its requests. This is why setting requests correctly matters more than raising priority.

Teaching video

No verified video was found. For the node-pressure eviction and graceful shutdown topics, no high-quality video was found whose ID could be verified through the YouTube oEmbed API. Use the official docs and the storyboard below as your reference.

Official docs

Video storyboard script

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: the node's memory bar turns from green to red, the MemoryPressure light comes on, and the node gets the memory-pressure taint.
Narration: when a node is running low on memory, kubelet sacrifices some Pods to keep the node itself alive.
Shot 2 · 0:20–1:00
Visual: Pod cards are sorted in three passes: exceeds requests, then priority, then amount exceeded. The top card is marked Evicted.
Narration: first check whether usage exceeds requests. Then check priority. Finally, check how far over the limit the Pod is. So setting requests correctly matters more than raising priority.
Shot 3 · 1:00–1:30
Visual: a PDB shield blocks drain's evictions, but it cannot block kubelet's evictions.
Narration: a PDB only constrains the eviction API. Node-pressure eviction, taint-based eviction, and OOM do not check it.
Shot 4 · 1:30–2:00
Visual: a node shutdown countdown: regular Pods exit first, and critical Pods exit last. On another node, the power is cut, and an SRE applies the out-of-service label.
Narration: graceful shutdown gives Pods time to exit. For a power loss, which is a non-graceful shutdown, first confirm the node is down, then use the out-of-service taint so the control plane can take over.
Or get a score of ≥ 70% on the quiz

Module 5 · Cluster Upgrades and Maintenance

29:00 – 37:00 · Upgrade one minor version at a time: check deprecated APIs first, then upgrade the control plane, and finally replace nodes with a rolling surge and PDBs
8 minVersion skew policy · AKS 1.36 → 1.37★★★★★ High-risk operation
Learning objectives
  • Recite the version skew rules: kubelet and kube-proxy can lag the apiserver by at most 3 minors, kubectl by ±1, and controller-manager and scheduler by at most 1.
  • Before upgrading, check deprecated APIs with the apiserver_requested_deprecated_apis metric, pluto, and kubent. Compare the results with the 1.37 deprecation list.
  • Describe the kubeadm upgrade order (upgrade plan/apply → drain → kubelet → uncordon). Know that you must take an etcd snapshot before upgrading (see Module 6 for how), and that kubeadm upgrades renew certificates automatically.
  • Explain how drain interacts with PDBs (Eviction API, 429), and configure max-surge, max-unavailable, drain-timeout, and soak on AKS.
  • Upgrade the control plane and node pools step by step on AKS. Configure automatic upgrade channels, the node OS channel, and scheduled maintenance.
Prerequisites: PDBs and drain (hour 2), StatefulSets (hours 2 and 4), and the difference between disruptions and evictions (Module 4). Importance: ★★★★★

What: Version Skew Policy

ComponentRelative to kube-apiserverAllowed when apiserver = 1.37
kubelet, kube-proxyCannot be newer. Can be up to 3 minors older (2 minors if kubelet < 1.25).1.37 / 1.36 / 1.35 / 1.34
kube-controller-manager, kube-scheduler, cloud-controller-managerCannot be newer. Can be up to 1 minor older.1.37 / 1.36
kubectl±1 minor1.38 / 1.37 / 1.36
HA with multiple apiserversNo more than 1 minor apart from each otherBriefly mixed during an upgrade

Upgrade order: apiserver → controller-manager / scheduler / CCM → kubelet (drain first; kubelet cannot be upgraded in place across minors) → kube-proxy. You cannot skip a minor, even on a single-node cluster. Upgrade first to the latest patch of the current minor, then to the latest patch of the next minor. On AKS, the control plane can lead the node pools by up to 3 minors (since 1.28). Non-LTS clusters also cannot skip minors. LTS clusters can jump between LTS versions when the skew and validation checks are met.

Why: why you must keep upgrading

  • Upstream maintains each minor version for only about 14 months (1.37 EOL 2027-10-28). AKS community versions are supported for 12 months after GA (1.37: GA 2026-10, EOL 2027-10). With the Premium tier and LTS, support can be extended to 24 months (1.37 LTS EOL 2028-10).
  • Upgrades initiated by the AKS platform: starting 2027-06-01, clusters that stay on an unsupported version beyond the 60-day grace period are upgraded automatically by AKS. These upgrades ignore maintenance windows, do not stop for deprecated APIs, and can override PDBs that block drain.

How: pre-upgrade checklist (1.36 → 1.37)

Check itemMethod1.37 notes
Deprecated / removed APIskubectl get --raw /metrics | grep apiserver_requested_deprecated_apis; pluto detect-all-in-cluster; kubent; the AKS portal highlights themThe k8s.io/deprecated annotation in audit logs identifies the callers
kube-proxy modekubectl -n kube-system get cm kube-proxy -o yaml | grep modeipvs is deprecated (from 1.37, startup warnings; expected to be disabled by default in 1.40 and removed in 1.43). Migrate to nftables (GA in 1.33).
Cluster DNSkubectl -n kube-system get deploy -l k8s-app=kube-dns -o wide (check whether the image is coredns or kube-dns)kube-dns is deprecated in 1.37. Migrate to CoreDNS.
cgroup versionstat -fc %T /sys/fs/cgroup/ (cgroup2fs means v2)Since 1.35, the kubelet failCgroupV1 default is true, so kubelet does not start by default on cgroup v1 nodes.
kubectl usageSearch scripts for kubectl run … -fDeprecated in 1.37
Webhook and operator compatibilityCheck the version matrix for admission webhooks, CRD controllers, and Ingress/Gateway controllersA webhook outage blocks Pod creation during the upgrade
Can PDBs be satisfied?kubectl get pdb -A: any PDB with ALLOWED DISRUPTIONS at 0 will block drainA single replica with minAvailable: 1 is the most common blocker
Capacity and quotaSurge needs extra VM and subnet IP quotaIn overlay mode, Pods do not use VNet IPs, but nodes still do
AKS-specificaz aks get-upgrades; the "breaking changes" section of the AKS versions page1.37: for managed Prometheus, the ServiceMonitor basicAuth Secret moves to namespace-scoped access. When a Standard node pool is upgraded to 1.37, LocalDNS may be enabled if you have not configured it explicitly. Custom DNS must support both TCP and UDP port 53.
BackupVelero backup (hour 4); etcd snapshots for self-managed clusters (Module 6)Rollback is possible only through restore. There is no downgrading a minor version.

When: choose an upgrade method

MethodBest forRisk
In-place rolling (surge; AKS default max-surge 1, production recommended 33%)Most stateless workloads with PDBsGets stuck if PDBs are not satisfied; needs surge quota
max-unavailable (no surge; cordon and drain in place)Insufficient quota or capacityWith low remaining capacity, Pods stay Pending and PDBs are more likely to block. Not supported for system pools.
Blue-green node pool (create a 1.37 node pool → migrate → delete the old pool)Fast rollback needed, or a major OS changeDouble the cost for a short time
Blue-green clusterCrossing multiple minors, or architecture refactoringRequires traffic cutover and data migration. GitOps makes rebuilding easier.
Common misconceptions ① "AKS automatic upgrades mean you don't need to do anything." Automatic upgrades stop for deprecated APIs (platform-initiated upgrades excepted), can be blocked by PDBs, and still need monitoring and maintenance windows. ② "drain deletes DaemonSet Pods." It doesn't. You need --ignore-daemonsets to proceed. emptyDir data is lost unless you use --delete-emptydir-data. ③ "PDBs prevent node outages." PDBs only limit voluntary disruptions (evictions) and have no effect on node failures. ④ "You can upgrade node pools before the control plane." No. Node pool versions cannot be higher than the control plane version.

Upgrade order and version skew window

Version axis 1.34 1.35 1.36 (current) 1.37 (target) ① kube-apiserver ② kcm / scheduler ③ kubelet / kube-proxy allowed range: 1.34 – 1.37 (lag ≤ 3) kubectl: 1.36 – 1.38 (±1) Upgrade the control plane firstThen upgrade nodes (drain)
Figure 5-1: the control plane goes first, and nodes follow in batches within the skew window. A kubelet that lags 3 minors must be upgraded before the control plane can be upgraded again.

AKS node pool rolling upgrade (surge)

① Add surge nodeNew version 1.37 ② Cordon old nodeunschedulable ③ Drain (Eviction)Governed by PDBs · timeout 30m ④ Soak (optional)0–30 minutes ⑤ Reinstall old nodeBecomes the next buffer ⑥ Delete surgeRestore the original node count Repeat ②–⑤ for each batch. Batch size = max-surge.
Figure 5-2: AKS official process (Configure rolling upgrades, 2026-05). Reinstalled old nodes become the buffer for the next batch.

Step-by-step animation: rolling upgrade of a 3-node pool (max-surge 1, PDB minAvailable 2)

api has 3 replicas and a PDB with minAvailable: 2. Watch the surge node, the cordon, the PDB-governed evictions one at a time (the second eviction is rejected with 429 until the first new Pod is Ready), and the node reinstall. Switch to the single-replica PDB to see how drain gets stuck.

Click Play.
RunningPending / evictingCreatingTerminating
$ az aks nodepool upgrade -g rg-k8s-lab --cluster-name aks-lab -n nodepool1 --kubernetes-version 1.37.1 --max-surge 1

Core commands

CommandPurposeKey flags
kubectl versionClient/server version (check ±1)—
kubectl get nodes -o widekubelet version on each nodeYou will see mixed versions during the upgrade
kubectl drain NODEcordon + evict through the Eviction API--ignore-daemonsets --delete-emptydir-data --timeout=10m. --disable-eviction bypasses PDBs (dangerous).
kubectl cordon / uncordon NODEDisable / re-enable scheduling—
kubeadm upgrade plan / apply vX.Y.Z / nodeUpgrade the control plane on a self-managed clusterFirst switch the apt source to the new minor (pkgs.k8s.io has one repository per minor)
az aks get-upgrades -g RG -n AKS -o tableAvailable versions—
az aks upgrade --kubernetes-version V --control-plane-onlyUpgrade the control plane onlyNot available while the automatic upgrade channel is enabled
az aks nodepool upgrade --kubernetes-version VUpgrade a node pool--max-surge 33%, --max-unavailable, --node-soak-duration, --node-image-only
az aks nodepool update --drain-timeout 45 --max-surge 33%Persist upgrade settingsdrain-timeout defaults to 30 minutes (5 minutes to 24 hours)
az aks update --auto-upgrade-channel stableCluster auto-upgrade channelnone (Standard default) / patch / stable / rapid / node-image (legacy, not recommended)
az aks update --node-os-upgrade-channel NodeImageNode OS image channelNone / Unmanaged / SecurityPatch / NodeImage (default for new Standard clusters)
az aks maintenanceconfiguration add -n aksManagedAutoUpgradeSchedule …Scheduled maintenance windowNode OS uses aksManagedNodeOSUpgradeSchedule. Windows of at least 4 hours are recommended.

Deprecated API check

kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis
pluto detect-all-in-cluster --target-versions k8s=v1.37.0 -o wide
kubent --target-version 1.37.0
apiserver_requested_deprecated_apis{group="flowcontrol.apiserver.k8s.io",removed_release="1.xx",resource="flowschemas",subresource="",version="v1beta3"} 1

This metric accumulates only over the apiserver process lifetime and resets on restart. Combine it with the k8s.io/deprecated annotation in audit logs to find the caller (userAgent). The removed_release in the example should follow your cluster's actual output.

kubeadm upgrade flow (self-managed cluster · control plane node)

sudo sed -i 's#/v1.36/#/v1.37/#' /etc/apt/sources.list.d/kubernetes.list   # switch the repo by minor
sudo apt-get update
sudo apt-mark unhold kubeadm && sudo apt-get install -y kubeadm='1.37.1-*' && sudo apt-mark hold kubeadm
sudo kubeadm upgrade plan
sudo kubeadm upgrade apply v1.37.1          # other control plane nodes: sudo kubeadm upgrade node
kubectl drain cp1 --ignore-daemonsets
sudo apt-mark unhold kubelet kubectl && sudo apt-get install -y kubelet='1.37.1-*' kubectl='1.37.1-*' && sudo apt-mark hold kubelet kubectl
sudo systemctl daemon-reload && sudo systemctl restart kubelet
kubectl uncordon cp1
# Worker nodes: upgrade kubeadm → sudo kubeadm upgrade node → drain → upgrade kubelet → restart → uncordon (one node at a time)

Control plane backup before upgrading (self-managed cluster)

On a kubeadm cluster, take an etcd snapshot and verify it before kubeadm upgrade apply (etcdctl snapshot save + etcdutl snapshot status; for the full steps and a restore drill, see Module 6). kubeadm upgrade also renews the control plane leaf certificates for one year (you can turn this off with --certificate-renewal=false). On AKS, EKS, and GKE, the platform manages etcd, so you neither need it nor can access it. Before upgrading, back up applications with Velero or AKS Backup instead (hour 4).

Lab 5: zero-downtime upgrade of AKS 1.36 → 1.37 (about 30–45 minutes, mostly waiting)

Cost and risk During surge, one extra D4s_v5 runs (about 0.2 USD/hour). An upgrade cannot be rolled back to 1.36. Run this only on the lab cluster.
Deploy the test app: 3-replica api + PDB + continuous probing
kubectl config use-context aks-lab
kubectl create ns shop
kubectl -n shop create deploy api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=3 --port=9898
kubectl -n shop set resources deploy/api --requests=cpu=100m,memory=64Mi
kubectl -n shop expose deploy api --port=9898
kubectl -n shop create pdb api --selector=app=api --min-available=2
kubectl -n shop get pdb api
# In another terminal: continuous probing, recording failures
kubectl -n shop run probe --image=busybox:1.37 --restart=Never -- /bin/sh -c \
  'while true; do wget -q -T 2 -O /dev/null http://api.shop:9898/healthz && echo "$(date +%T) ok" || echo "$(date +%T) FAIL"; sleep 1; done'
kubectl -n shop logs -f probe | grep -v " ok"

The probe itself can also be evicted. It has no controller, so it is not recreated after eviction. For accurate measurements, probe from outside the cluster with curl through a LoadBalancer or Gateway instead.

Pre-upgrade check
az aks get-upgrades -g rg-k8s-lab -n aks-lab -o table
kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis | head
kubectl get pdb -A
az aks nodepool update -g rg-k8s-lab --cluster-name aks-lab -n nodepool1 --max-surge 1 --drain-timeout 30
Name     ResourceGroup    MasterVersion    Upgrades
-------  ---------------  ---------------  --------------
default  rg-k8s-lab       1.36.5           1.37.1
Upgrade only the control plane
K8S_NEW=$(az aks get-upgrades -g rg-k8s-lab -n aks-lab --query "controlPlaneProfile.upgrades[?starts_with(kubernetesVersion,'1.37')].kubernetesVersion | [0]" -o tsv)
echo $K8S_NEW
time az aks upgrade -g rg-k8s-lab -n aks-lab --kubernetes-version $K8S_NEW --control-plane-only --yes
kubectl version
az aks nodepool list -g rg-k8s-lab --cluster-name aks-lab --query "[].{name:name,ver:orchestratorVersion}" -o table

At this point the apiserver is 1.37, and nodes are still 1.36 (within the skew window). The probe should show no FAIL, because the data plane is unaffected.

Upgrade the node pool and watch the surge and drain events
az aks nodepool upgrade -g rg-k8s-lab --cluster-name aks-lab -n nodepool1 \
  --kubernetes-version $K8S_NEW --max-surge 1 --node-soak-duration 1 --yes --no-wait
kubectl get nodes -w                      # In another terminal
kubectl get events --field-selector reason=Drain,reason=Surge,reason=Upgrade -w
kubectl -n shop get pods -o wide -w
Normal  Surge    node/aks-nodepool1-…-vmss000003  Created a surge node [aks-nodepool1-…-vmss000003 nodepool1] for agentpool nodepool1
Normal  Drain    node/aks-nodepool1-…-vmss000000  Draining node: [aks-nodepool1-…-vmss000000]
Normal  Upgrade  node/aks-nodepool1-…-vmss000000  Soak duration 1m0s after draining node: …
Verify
az aks show -g rg-k8s-lab -n aks-lab --query "{cp:kubernetesVersion,state:provisioningState}" -o table
kubectl get nodes -L kubernetes.azure.com/node-image-version
kubectl -n shop get pods -o wide        # api replicas should be spread across the new nodes

Acceptance: all nodes are on 1.37.x, and the probe log shows zero FAIL (or interruptions only when the probe Pod itself is evicted).

(Demo) PDB blocks drain: scale api down to 1 replica (PDB minAvailable 2 cannot be satisfied), run az aks nodepool upgrade --node-image-only, and observe the failure message and kubectl get pdb showing ALLOWED DISRUPTIONS=0. Then restore 3 replicas and retry with the same command (the later PUT resumes the interrupted upgrade).
Configure a long-term maintenance policy
az aks update -g rg-k8s-lab -n aks-lab --auto-upgrade-channel patch --node-os-upgrade-channel NodeImage
az aks maintenanceconfiguration add -g rg-k8s-lab --cluster-name aks-lab -n aksManagedAutoUpgradeSchedule \
  --schedule-type Weekly --day-of-week Sunday --interval-weeks 1 --start-time 02:00 --utc-offset -05:00 --duration 4
az aks maintenanceconfiguration list -g rg-k8s-lab --cluster-name aks-lab -o table
Cleanup: kubectl delete ns shop (keep the cluster for the Capstone lab, or run az aks stop).

Case 1: quarterly upgrade pipeline

Every quarter, dev clusters are upgraded 2 weeks after the new AKS version reaches GA, staging in week 4, and prod in week 6. Each step runs pluto and metric checks before the upgrade, and smoke tests and SLO comparisons after it. Prod uses the stable channel and a Sunday 02:00–06:00 maintenance window. Node pool max-surge is 33%, and drain-timeout is set to the longest graceful termination time.

Case 2: a PDB causes the upgrade to fail (UpgradeFailed / PodDrainFailure)

Problem: a single-replica service had minAvailable: 1, so node drain never finished, and the upgrade failed after 30 minutes. Approach: the platform blocks PDBs where replicas ≤ minAvailable with an admission policy (VAP, hour 5). For single-replica services, use maxUnavailable: 1 or accept a short interruption. Set --undrainable-node-behavior Cordon (check the AKS docs) to isolate nodes that cannot be drained, so the upgrade can continue on the other nodes.

Case 3: stateful database and weekly node image updates

The NodeImage channel replaces nodes every week, so the postgres StatefulSet is evicted once a week. Approach: run the database on a managed service (Azure Database for PostgreSQL), or on a dedicated node pool with its own maintenance window. A PDB with maxUnavailable: 0 blocks upgrades. Instead, allow 1 interruption within the maintenance window, and make sure the application can reconnect.

Common errors and fixes

error when evicting pods/"api-…" -n "shop" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.

Cause: the Eviction API returns 429. The PDB's ALLOWED DISRUPTIONS is 0 (not enough replicas, new Pods not ready, or Pods Pending).

kubectl get pdb -A
kubectl -n shop describe pdb api
kubectl -n shop get pods -l app=api -o wide

Add replicas or fix the reason for Pending. Do not bypass with --disable-eviction unless you accept the interruption.

(UpgradeFailed) Drain node aks-nodepool1-…-vmss000001 failed when evicting pod … PodDrainFailure

Cause: AKS cannot evict within drain-timeout, because a PDB blocks it or Pods take too long to terminate gracefully.

Fix: fix the PDB or the replica count, then rerun the upgrade command (it resumes from where it was interrupted). For Pods with long termination times, increase --drain-timeout. See the Microsoft troubleshooting doc error-code-poddrainfailure.

NotAllAgentPoolOrchestratorVersionSpecifiedAndUnchanged: Using managed cluster api, all Agent pools' OrchestratorVersion must be all specified or all unspecified…

Cause: the cluster has the automatic upgrade channel enabled, so --control-plane-only cannot be used.

Fix: run a full upgrade, or first run az aks update --auto-upgrade-channel none.

Upgrade rejected: deprecated API usage detected (Upgrade blocked due to deprecated API usage)

Cause: AKS detected that APIs removed in the target version are still being called, so it stops the upgrade by default.

Fix: find the caller (userAgent in the audit log), then update the manifests, Helm chart, or operator. After you confirm the fix and the metric data is stale, you can temporarily bypass the check as described in the AKS docs (see learn.microsoft.com, "Stop cluster upgrades on API breaking changes").

Upgrade reports quota / SubnetIsFull / cannot create surge node

Cause: insufficient vCPU quota or subnet IPs (especially with non-overlay Azure CNI).

Fix: request more quota, lower max-surge, or use max-unavailable (for non-system pools). For 1.35+ node pools, AKS automatically tries surge 1 if the full surge fails.

Command-line exercise

1. Write the command to upgrade the AKS node pool userpool to 1.37.1, with surge 33% each time, and watch for 5 minutes after each batch is drained.

Reference answer
az aks nodepool upgrade -g rg-k8s-lab --cluster-name aks-lab -n userpool \
  --kubernetes-version 1.37.1 --max-surge 33% --node-soak-duration 5

2. Manually maintain worker node w1 in a self-managed cluster: drain it safely, then restore scheduling after maintenance.

Reference answer
kubectl drain w1 --ignore-daemonsets --delete-emptydir-data --timeout=15m
# … maintenance / upgrade kubelet …
kubectl uncordon w1

Scenario analysis: a cluster has control plane 1.34 and nodes at 1.31. This is a self-managed cluster outside the AKS LTS scenario. The team wants to go straight to 1.37. How would you plan it?

Reference answer

The nodes already lag by 3 minors, so the nodes must be upgraded first (at least to 1.32+) before the control plane can be upgraded to 1.35. Then go one minor at a time: 1.35 → 1.36 → 1.37. At each step, check deprecated APIs, especially the deprecations listed in the 1.37 release notes (ipvs, kube-dns, and cgroup v1 nodes). Keep nodes within the skew window at every step. If time is tight, consider a blue-green approach: build a new 1.37 cluster, rebuild workloads with GitOps, and migrate the data.

Teaching video

No verified video was found. No high-quality video on the cluster upgrade topic was found whose ID could be verified through the official YouTube API.

Official docs

Video storyboard script

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: on the calendar, the 1.36 EOL date is circled in red.
Narration: each Kubernetes version is supported for only about a year, so upgrading is not optional.
Shot 2 · 0:20–0:50
Visual: the version axis. The apiserver moves first to 1.37, while kubelet stays within the 1.36 window.
Narration: upgrade the control plane first. Nodes can lag by up to three minors, then catch up in batches.
Shot 3 · 0:50–1:40
Visual: the animated surge flow, page by page. A new node appears, old nodes are cordoned, Pods are evicted one by one, and the PDB returns 429.
Narration: AKS first adds a node on the new version, then cordons and drains the old node. Evictions are governed by PodDisruptionBudgets, which keep enough replicas online at all times.
Shot 4 · 1:40–2:00
Visual: checklist: deprecated APIs, ipvs, kube-dns, cgroup v1, backups.
Narration: before upgrading, check deprecated APIs and the 1.37 deprecations, and make sure you have a backup first.
Or get a score of ≥ 70% on the quiz

Module 6 · Control Plane Operations Overview: etcd snapshots and restore, certificate rotation

37:00 – 43:00 · Two things a self-managed cluster (kubeadm) must do itself, and a managed cluster (AKS/EKS/GKE) leaves to the platform: backing up etcd and keeping certificates from expiring
6 minetcdctl backup · etcdutl verify/restore · kubeadm certs★★★★☆ Overview (full CKA workflow not covered)
Learning objectives
  • Explain the role of etcd in the cluster, why "etcd access = cluster root access," and why production should use an odd number of members (the official recommendation for production is 5 members).
  • Use etcdctl snapshot save to back up and etcdutl snapshot status to verify. State the three-step restore principle: stop all apiservers → restore all etcd members → restart apiservers (then restart the scheduler, controller-manager, and kubelet).
  • Know the kubeadm certificate validity periods (leaf certificates 1 year, CA 10 years), that kubeadm upgrade renews certificates automatically, and that after kubeadm certs renew all you must restart the control plane static Pods. Understand kubelet client and serving certificate rotation.
  • Compare with managed clusters: AKS az aks rotate-certs (rebuilds nodes, up to about 30 minutes of downtime) and automatic rotation. Be clear that an etcd backup is not an application backup. Use Velero for application-level backups (hour 4).
Scope note: this module is an overview only. Multi-member etcd disaster recovery, CA rotation, and external etcd topologies belong to the CKA and self-managed cluster topics. Refer to the official docs. Prerequisites: control plane components (hour 1), Secret encryption at rest and etcd (hour 5), Velero (hour 4).

What: what etcd stores

etcd is Kubernetes' only persistent store. All API objects (Deployments, Secrets, RBAC, CRDs and CRs, Leases, Events) live under /registry/… keys. The apiserver is the only component that should access etcd directly. Being able to read etcd means being able to read every Secret (unless encryption at rest is enabled, hour 5). etcd uses Raft consensus: N members tolerate ⌊(N−1)/2⌋ failures, so 3 members tolerate 1 failure and 5 members tolerate 2. If a majority of members is permanently lost, the cluster has failed. Running Pods may keep running, but no further changes can be made.

ToolPurposeNotes
etcdctlNetwork client for etcd: snapshot save, endpoint status/health, member list, alarm listRequires TLS: --cacert, --cert, --key (in kubeadm, under /etc/kubernetes/pki/etcd/)
etcdutlLocal tool that works directly on data files: snapshot status, snapshot restore, defragetcdctl snapshot status/restore has been deprecated since etcd 3.5 and is planned for removal in 3.6. The official recommendation is to use etcdutl instead.

Why: which layer to back up?

Backup methodRestore granularityApplies toManaged clusters
etcd snapshotThe API state of the whole cluster (point in time)Control plane disasters (etcd data corruption, mass accidental deletion of objects, rollback after a failed upgrade)Handled by the platform. Users cannot access etcd.
Velero / AKS Backup (hour 4)Select objects by namespace or label, plus PV snapshotsApplication migration, accidental namespace deletion, cross-cluster restoreUsers are responsible
GitOps repository (Module 1)Declarative manifests (no runtime state or data)"The cluster can be rebuilt from Git"Users are responsible

An etcd snapshot does not contain data on PVs (the database files are on disk), and you cannot restore just one namespace from it. So even on a self-managed cluster, you need both Velero and the database's own backups.

How: key points for snapshots and restore (single control plane kubeadm)

  1. Backup: ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 --cacert=… --cert=… --key=… snapshot save snap.db. You can find the certificate paths in the etcd static Pod's startup flags. The official recommendation is to encrypt snapshot files and store them off-site.
  2. Verify: etcdutl --write-out=table snapshot status snap.db outputs HASH, REVISION, TOTAL KEYS, and TOTAL SIZE.
  3. Restore: if apiservers are still running in the cluster, do not restore directly. First stop all apiservers. Then restore the snapshot to a new directory with etcdutl --data-dir <new dir> snapshot restore snap.db. Change the hostPath of the etcd-data volume in /etc/kubernetes/manifests/etcd.yaml to point to the new directory. On kubeadm clusters, also sync etcd.local.dataDir in kubeadm-config, or the next kubeadm upgrade will write back the old directory. Then restart the apiservers. Restarting kube-scheduler, kube-controller-manager, and kubelet is recommended to avoid stale caches.
  4. Versions: you can restore an etcd snapshot from the same major.minor version. Different patch versions are also supported.

Certificates: who issues them, how long they last, and how to renew them

Certificatekubeadm default validityHow to renew
Cluster CA, etcd CA, front-proxy CA10 years (caCertificateValidityPeriod: 87600h)CA rotation is a separate, complex process (see the official "Manual Rotation of CA Certificates")
apiserver, apiserver-kubelet-client, etcd server/peer, admin.conf, controller-manager.conf, scheduler.conf, super-admin.conf, and others1 year (certificateValidityPeriod: 8760h)Automatic renewal by kubeadm upgrade apply/node (you can turn this off with --certificate-renewal=false), or run kubeadm certs renew all manually and then restart the control plane static Pods
kubelet client certificate (/var/lib/kubelet/pki/kubelet-client-current.pem)1 yearkubeadm configured for automatic rotation (rotateCertificates: true)
kubelet serving certificateSelf-signed by default. With serverTLSBootstrap: true enabled, it is signed by the cluster CA.CSRs (signer kubernetes.io/kubelet-serving) are not approved automatically by default. Approve them with kubectl certificate approve or an approval controller.

Why restart after a manual renewal? Because not every component supports hot reloading of certificates. The official way to restart a static Pod is to move its manifest out of /etc/kubernetes/manifests/ temporarily, wait about 20 seconds (kubelet fileCheckFrequency), and then move it back. super-admin.conf belongs to the system:masters group and bypasses RBAC. Use it only as a break-glass credential, and do not distribute it.

When: what you still need to do on managed clusters

PlatformetcdCertificatesWhat you still need to watch
AKSManaged by the platform, not accessibleCluster CAs created after 2019-05 have a 30-year validity. RBAC-enabled clusters automatically rotate node kubelet client and serving certificates by default. Manual az aks rotate-certs rotates the CA and all child certificates, and it rebuilds all nodes, VMSS, and disks, with up to about 30 minutes of downtime. Afterward, run az aks get-credentials --overwrite-existing.Distribution and expiry of certificate-based kubeconfigs, Velero / AKS Backup
EKSManaged by the platformControl plane certificates are managed by AWS. Users access the cluster through IAM (access entries, hour 7).Node AMI updates, backups
GKEManaged by the platformControl plane certificates are managed by Google. Credential rotation is supported, but it triggers a rebuild.Maintenance windows, backups (Backup for GKE)
Common misconceptions ① "With an etcd snapshot, you don't need Velero." Snapshots do not include PV data and cannot be restored by namespace. ② "etcd restore can be done online." You must stop all apiservers first, or caches and storage will be inconsistent. ③ "kubeadm certs renew takes effect immediately." You must restart the control plane static Pods. ④ "Expired certificates only affect kubectl." Expired certificates on apiserver↔kubelet or apiserver↔etcd connections make the whole cluster unavailable. ⑤ "Sharing admin.conf with the team is convenient." It is a long-lived, high-privilege certificate credential, and it cannot be revoked on its own.

Architecture diagram: etcd and control plane certificates

Control plane node (kubeadm · static Pods) kube-apiserverapiserver.crt (1 year)apiserver-etcd-client.crt etcd (:2379 / :2380)etcd/server.crt · peer.crt/var/lib/etcd (data directory) mTLS scheduler / kcmscheduler.conf · controller-manager.conf /etc/kubernetes/pkica.crt · etcd/ca.crt · front-proxy-ca (10 years) kubelet (each node)Client certificate rotates automatically · serving certificate via serverTLSBootstrap + CSR approval etcdctl snapshot save→ snap-2026-11-17.dbVerify with etcdutl snapshot status Encrypt, then store off-siteObject storage (immutable / versioned) Managed clusters: the platform handles all of the aboveYou handle Velero + GitOps + database backups
Figure 6-1: certificates have two lifetimes. CAs last 10 years, and leaf certificates last 1 year. etcd snapshots must be encrypted and stored off-site.

Flowchart: single control plane etcd restore

① Stop all apiserversMove manifests aside ② etcdutl restore--data-dir new directory ③ Point etcd.yaml toNew hostPath + kubeadm-config ④ Start apiserversMove manifests back ⑤ Restart componentsscheduler·kcm·kubelet Multi-member cluster: each member must be restored from the same snapshot (each member's --name / --initial-cluster flags; follow the official etcd disaster recovery docs)
Figure 6-2: a restore loses all changes made after the snapshot. After the restore, controllers and GitOps reconcile the cluster back to the desired state.

Step-by-step animation: backup → accidental deletion → restore

Select a scenario, then press play. At each step, watch who reads and writes etcd, and which data will be lost.

Ops / CronJobetcdctl · kubeadm kube-apiserverRunning etcdrev 18342 · keys 1420 Snapshot file(none) Off-site storageEncrypted · versioned Cluster status: healthy
Click Play.
$ # Control plane node lab-control-plane

Core commands

CommandPurposeNotes
etcdctl … snapshot save FILEOnline snapshotLow impact on members. Requires TLS parameters.
etcdutl --write-out=table snapshot status FILEVerify snapshotReplaces the deprecated etcdctl snapshot status
etcdutl --data-dir DIR snapshot restore FILERestore to a new data directoryDIR is created. Replaces the deprecated etcdctl snapshot restore
etcdctl … endpoint status -w table / endpoint health / member listMember status, DB size, leaderWhen the DB nears its quota, it triggers a NOSPACE alert (hour 8 has a full case study)
kubeadm certs check-expirationCheck the expiry of all certificatesColumns: CERTIFICATE, EXPIRES, RESIDUAL TIME, CERTIFICATE AUTHORITY, EXTERNALLY MANAGED
kubeadm certs renew allManually renew all leaf certificatesOn multi-control-plane clusters, run this on each node. Then restart the static Pods.
kubectl get csr, kubectl certificate approve CSRApprove kubelet serving CSRssigner kubernetes.io/kubelet-serving
openssl x509 -in CERT -noout -enddateExpiry of any certificatekubelet: /var/lib/kubelet/pki/kubelet-client-current.pem
az aks rotate-certs -g RG -n AKSAKS rotates the CA and all child certificatesRebuilds nodes, with up to about 30 minutes of downtime; then az aks get-credentials --overwrite-existing

Backup script (kubeadm control plane node, example)

#!/usr/bin/env bash
set -euo pipefail
TS=$(date +%Y%m%d-%H%M%S); OUT=/var/backups/etcd; mkdir -p "$OUT"
ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
  --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key \
  snapshot save "$OUT/snap-$TS.db"
etcdutl --write-out=table snapshot status "$OUT/snap-$TS.db"
# Encrypt and upload off-site (example: age + Azure Blob; replace with your own key management plan)
# age -r "$AGE_RECIPIENT" -o "$OUT/snap-$TS.db.age" "$OUT/snap-$TS.db" && rm "$OUT/snap-$TS.db"
# az storage blob upload --account-name … -c etcd -f "$OUT/snap-$TS.db.age" -n "snap-$TS.db.age"
find "$OUT" -name 'snap-*' -mtime +7 -delete

Certificate check and manual renewal (kubeadm)

sudo kubeadm certs check-expiration
sudo kubeadm certs renew all
# Restart control plane static Pods (official method: move the manifest out, wait about 20 seconds for fileCheckFrequency, then move it back)
sudo mkdir -p /etc/kubernetes/manifests.off
sudo mv /etc/kubernetes/manifests/kube-apiserver.yaml /etc/kubernetes/manifests.off/ && sleep 20
sudo mv /etc/kubernetes/manifests.off/kube-apiserver.yaml /etc/kubernetes/manifests/
# Repeat for kube-controller-manager, kube-scheduler, and etcd. Update the local kubeconfig:
sudo cp /etc/kubernetes/admin.conf ~/.kube/config
CERTIFICATE                EXPIRES                  RESIDUAL TIME   CERTIFICATE AUTHORITY   EXTERNALLY MANAGED
admin.conf                 Nov 15, 2027 09:12 UTC   363d            ca                      no
apiserver                  Nov 15, 2027 09:12 UTC   363d            ca                      no
apiserver-etcd-client      Nov 15, 2027 09:12 UTC   363d            etcd-ca                 no
etcd-server                Nov 15, 2027 09:12 UTC   363d            etcd-ca                 no
CERTIFICATE AUTHORITY   EXPIRES                  RESIDUAL TIME   EXTERNALLY MANAGED
ca                      Nov 13, 2036 09:12 UTC   9y              no

Lab 6: take an etcd snapshot on kind, verify it, and rehearse a restore on a separate cluster (about 12 minutes)

Safety note The restore rehearsal runs on a newly created temporary kind cluster named ops. Do not restore on lab. kind nodes are Docker containers, and the control plane runs as kubeadm static Pods, which suits a demo.
Take a snapshot on lab (the etcd image includes etcdctl / etcdutl)
kubectl config use-context kind-lab
kubectl -n kube-system exec etcd-lab-control-plane -- etcdctl \
  --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key \
  snapshot save /var/lib/etcd/snap-lab.db
kubectl -n kube-system exec etcd-lab-control-plane -- etcdutl --write-out=table snapshot status /var/lib/etcd/snap-lab.db
docker exec lab-control-plane ls -lh /var/lib/etcd/
{"level":"info","msg":"saved","path":"/var/lib/etcd/snap-lab.db"}
Snapshot saved at /var/lib/etcd/snap-lab.db
+----------+----------+------------+------------+
|   HASH   | REVISION | TOTAL KEYS | TOTAL SIZE |
+----------+----------+------------+------------+
| 3c1f9a2e |    48211 |       1873 |     9.8 MB |
+----------+----------+------------+------------+

If the image does not include etcdutl, copy the snapshot out with docker cp lab-control-plane:/var/lib/etcd/snap-lab.db . to the lab VM, and verify it with an etcdutl of the same minor version as the cluster's etcd.

Check certificate expiry
docker exec lab-control-plane kubeadm certs check-expiration
docker exec lab-worker openssl x509 -in /var/lib/kubelet/pki/kubelet-client-current.pem -noout -enddate
Create a temporary cluster ops, take a snapshot, then simulate an accidental deletion
kind create cluster --name ops --image kindest/node:v1.37.0
kubectl config use-context kind-ops
kubectl create ns precious && kubectl -n precious create cm keep --from-literal=a=1
E='kubectl -n kube-system exec etcd-ops-control-plane -- etcdctl --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key'
$E snapshot save /var/lib/etcd/snap-ops.db
kubectl delete ns precious           # "accidental deletion"
kubectl get ns precious              # NotFound
Restore in this order: stop the apiserver → restore → change the directory → start
CP=ops-control-plane
# ① Stop the apiserver (move the static Pod manifest away)
docker exec $CP sh -c 'mkdir -p /root/off && mv /etc/kubernetes/manifests/kube-apiserver.yaml /root/off/'
sleep 25
# ② Restore to a new directory with etcdutl inside the etcd container (/var/lib/etcd is a hostPath, so the restore subdirectory is visible on the node)
docker exec $CP sh -c 'crictl exec $(crictl ps --name etcd -q) etcdutl --data-dir /var/lib/etcd/restore snapshot restore /var/lib/etcd/snap-ops.db'
# ③ Point the etcd-data volume's hostPath to the new directory (inside the container, --data-dir is still /var/lib/etcd)
docker exec $CP sh -c "grep -n 'path: /var/lib/etcd' /etc/kubernetes/manifests/etcd.yaml"
docker exec $CP sh -c "sed -i 's#path: /var/lib/etcd\$#path: /var/lib/etcd/restore#' /etc/kubernetes/manifests/etcd.yaml"
sleep 25                              # kubelet notices the manifest change and recreates the etcd static Pod
# ④ Start the apiserver
docker exec $CP sh -c 'mv /root/off/kube-apiserver.yaml /etc/kubernetes/manifests/'
sleep 30; kubectl get ns precious; kubectl -n precious get cm keep
NAME       STATUS   AGE
precious   Active   6m
NAME   DATA   AGE
keep   1      6m

Before running sed, check the grep output to confirm that only the etcd-data volume line ends with path: /var/lib/etcd. A real kubeadm cluster must also sync etcd.local.dataDir in the kubeadm-config ConfigMap, and restart kube-scheduler, kube-controller-manager, and kubelet as the official docs recommend. Check the tools in the etcd image against the version you are actually running.

Cleanup: kind delete cluster --name ops; kubectl config use-context kind-lab; docker exec lab-control-plane rm -f /var/lib/etcd/snap-lab.db

Case 1: a self-managed cluster's certificates all expire together after one year

Symptom: a kubeadm cluster that was never upgraded ran for a full year. One day, kubectl reported x509: certificate has expired, and then controller-manager and scheduler also could not connect to the apiserver. Response: on the control plane node, run kubeadm certs renew all, restart the static Pods, and update the admin kubeconfig. Root cause and improvement: kubeadm renews certificates automatically only during upgrades, so a cluster that is never upgraded will inevitably see its certificates expire. Improvement: upgrade at least once a quarter (Module 5), and alert on the remaining days of certificate validity. For example, use the Prometheus blackbox exporter to probe the apiserver certificate. See Prometheus hour 5 · Blackbox monitoring.

Case 2: accidentally deleting a CRD removes all its CRs

Symptom: someone ran kubectl delete crd on an operator's CRD, and all the matching CRs were cascade-deleted. Response: on a self-managed cluster, weigh restoring the whole cluster from the latest etcd snapshot (which loses all changes made after the snapshot) against rebuilding the CRs from the GitOps repository. The final choice was to rebuild from GitOps and restore the missing objects with Velero, using etcd restore only as a last resort. Improvement: protect CRDs from deletion with RBAC restrictions and a ValidatingAdmissionPolicy that rejects deletion (hour 5). In GitOps, set Prune=false on CRDs.

Case 3: AKS compliance requires rotating the CA every 12 months

Approach: run az aks rotate-certs in a maintenance window. It rebuilds nodes and causes up to about 30 minutes of downtime, so notify people in advance and prepare. Every automation that uses certificate-based kubeconfigs must re-fetch credentials, and Entra ID users continue working through kubelogin after get-credentials. In multi-cluster environments, rotate one cluster at a time, dev first, then prod. See AKS hour 6 · Stop/start, certificate rotation, and routine maintenance.

Common errors and fixes

Error: context deadline exceeded (etcdctl snapshot save hangs)

Cause: missing or incorrect TLS parameters (etcd only accepts mTLS), or a wrong endpoint address.

kubectl -n kube-system get pod etcd-lab-control-plane -o yaml | grep -E "cert-file|key-file|trusted-ca|listen-client"
Deprecated: Use `etcdutl snapshot status` instead. / unknown command "restore" for "etcdctl snapshot"

Cause: etcdctl snapshot status/restore has been deprecated since etcd 3.5 and is planned for removal in 3.6. Fix: use etcdutl, with a version whose major.minor matches the cluster's etcd.

After a restore, the apiserver won't start / etcd log: member … has already been bootstrapped

Cause: the snapshot was restored into an old data directory without deleting it first, or the manifest still points to the old directory. In a multi-member cluster, only some members were restored.

Fix: restore into a brand-new directory and change the hostPath in etcd.yaml. In a multi-member cluster, restore all members from the same snapshot (follow the official etcd docs for each member's parameters).

Unable to connect to the server: x509: certificate has expired or is not yet valid

Cause: the client certificate in the kubeconfig or the apiserver certificate has expired. It can also be node clock skew.

sudo kubeadm certs check-expiration
timedatectl status
kubectl config view --raw -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d | openssl x509 -noout -enddate
After AKS runs rotate-certs: x509: certificate signed by unknown authority

Cause: the CA has been rotated, but the local kubeconfig still uses the old CA. Fix: az aks get-credentials -g RG -n AKS --overwrite-existing. If az aks show shows a failed Certificate Rotating status, rerun az aks rotate-certs as described in the docs.

Command-line exercise

1. Write two commands that take an etcd snapshot on a kubeadm control plane and verify it.

Reference answer
ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key snapshot save /var/backups/snap.db
etcdutl --write-out=table snapshot status /var/backups/snap.db

2. A kubeadm cluster's apiserver certificate expires in 10 days, and the cluster cannot be upgraded for now. Write the steps to handle it.

Reference answer
sudo kubeadm certs check-expiration
sudo kubeadm certs renew all          # on each control plane node
# Move the kube-apiserver / kube-controller-manager / kube-scheduler / etcd manifests out for 20 seconds each, then move them back
sudo cp /etc/kubernetes/admin.conf ~/.kube/config
sudo kubeadm certs check-expiration   # Confirm RESIDUAL TIME is about 365d

Scenario analysis: the team proposes "AKS should also take an etcd snapshot every day." How do you respond?

Reference answer

etcd on AKS is managed by the platform. Users cannot access it and do not need to back it up. Focus your effort on Velero / Azure Backup for AKS to back up namespace objects and PVs (hour 4), backups of the database itself, and the GitOps repository as a rebuildable source of declarations. Also rehearse restores regularly.

Teaching video

No verified video was found. For the etcd backup and restore and kubeadm certificate topics, no video was found whose ID could be verified through the YouTube oEmbed API.

Official docs

Video storyboard script

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: a locked connection between apiserver and etcd, with etcd filled with /registry keys.
Narration: all cluster state lives in etcd. If you can read etcd, you can read every Secret.
Shot 2 · 0:20–0:50
Visual: etcdctl takes a snapshot, etcdutl prints a hash table, and the locked snapshot is sent to off-site storage.
Narration: back up with etcdctl. Verify and restore with etcdutl. Encrypt snapshots and store them off-site.
Shot 3 · 0:50–1:30
Visual: five restore steps light up in order: stop the apiservers, restore, change the directory, start, restart the components.
Narration: before restoring, stop all API servers. Restore to a new directory, then point etcd to it.
Shot 4 · 1:30–2:00
Visual: a certificate calendar: leaf certificates last one year, and CAs last ten years. An AKS icon shows "Managed by the platform."
Narration: kubeadm certificates last one year by default and renew automatically during upgrades. On managed clusters, the platform is responsible. You are responsible for application backups.
Or get a score of ≥ 70% on the quiz

Module 7 · Production Differences on Managed Clusters: AKS / EKS / GKE Comparison

43:00 – 51:00 · The same Kubernetes 1.37, but the three clouds differ in key ways: responsibility boundaries, networking, identity, upgrades, scaling, and cost. For a deep dive into AKS, see the AKS course. For EKS, see hour 7.
8 minAKS Standard / Automatic · EKS Auto Mode · GKE Autopilot★★★★☆ Architecture choices
Learning objectives
  • Draw the responsibility boundary of "managed control plane + the data plane you run," and name what each cloud's fully managed mode (AKS Automatic, EKS Auto Mode, GKE Autopilot) manages.
  • Compare networking (whether Pod IPs use VPC or VNet addresses), identity (how people sign in, and how Pods access cloud resources without static credentials), upgrades (support windows, channels, and how nodes are replaced), and node scaling (Cluster Autoscaler, Karpenter, NAP, Autopilot).
  • Map the general capabilities from this lesson (HPA, PDBs, eviction, version skew, observability) to each platform's specific settings. Know which things remain your responsibility even when managed.
  • Run a read-only production readiness check on aks-lab, and know the equivalent commands for EKS and GKE.
Go deeper: AKS 8-hour course (networking, identity and security, scaling, upgrades and operations, advanced troubleshooting) · Hour 7: Kubernetes on AWS (EKS). This series does not yet have a dedicated GKE course, so refer to the official Google Cloud docs. Importance: ★★★★☆

What: responsibility boundaries for managed Kubernetes

All three clouds manage the control plane: the availability, backups, certificates, and patching of apiserver, etcd, scheduler, and controller-manager. Most of Module 6's work is no longer yours. The difference is how much of the data plane is managed:

Level of managementAKSEKSGKE
Control plane managed; nodes self-managed or semi-managedAKS Standard: you choose the node pool (VMSS) specs, scaling, and upgrade timingManaged node groups / self-managed nodes / FargateGKE Standard: you configure the node pools
"Fully managed" modesAKS Automatic: managed system node pool + NAP (Karpenter) + security baseline + upgrade channels, with the Standard tier and a Pod readiness SLAEKS Auto Mode: AWS manages core components such as Karpenter, VPC CNI, load balancing, and EBS CSI, plus the node lifecycleGKE Autopilot: Google manages the nodes, bills by Pod resource requests, and enforces a security baseline
Always your responsibilityWorkload requests/limits, probes, and PDBs (Modules 4 and 5); RBAC and network policies (hours 3 and 5); the image supply chain; application and data backups (hour 4, Module 6); cost; observability alerts and runbooks (Modules 3 and 8)

Why: the same Kubernetes, so where do the production differences lie?

DimensionAKSEKS (see hour 7 for details)GKE
Control plane cost and SLAFree (no financial SLA) / Standard (99.95% with availability zones, 99.9% without) / Premium (+ LTS for 24 months)0.10 USD per cluster per hour (standard support period). Extended support costs more. Single tier.Cluster management fee is charged per cluster. Regional clusters run control plane replicas across availability zones, so their SLA is higher than that of zonal clusters. Refer to the official pages for exact pricing and SLAs.
Version supportAbout 12 months after the community version's GA. With Premium + LTS, extended to 24 months.14 months of standard support + 12 months of extended support (surcharge). upgradePolicy.supportType controls behavior at end of support.Release channels Rapid / Regular (default) / Stable / Extended. Extended lets you stay on one minor version for up to 24 months (the extended period is billed by usage).
Automatic upgradesCluster channels none / patch / stable / rapid; node OS channel NodeImage, and so on; scheduled maintenance windows (Module 5)The control plane must be initiated manually, or the platform upgrades it after standard support ends. Auto Mode nodes are replaced automatically.All clusters are gradually upgraded automatically. Control the timing with maintenance windows and maintenance exclusions (such as "No minor upgrades").
Node upgrade methodRolling surge (max-surge / max-unavailable / soak), blue-green node poolsRolling replacement of managed node groups; Karpenter / Auto Mode drift-based replacementSurge rolling upgrades and blue-green node pool upgrades
Pod networkingAzure CNI Overlay (Pod IPs do not use the VNet) + Cilium dataplane; VNet mode is also availableVPC CNI: Pods get VPC IPs directly. Subnet planning is the top issue. Prefix delegation and custom networking are available.VPC-native (alias IPs); Pods use the subnet's secondary address ranges; GKE Dataplane V2 (based on eBPF/Cilium)
Human accessEntra ID + Azure RBAC for Kubernetes (kubelogin); local accounts can be disabledIAM + access entries (replacing the aws-auth ConfigMap)Google Cloud IAM + Kubernetes RBAC
Pod access to cloud resourcesWorkload Identity (OIDC federation, hour 5)EKS Pod Identity or IRSAWorkload Identity Federation for GKE
Node autoscalingCluster Autoscaler (node pools) or NAP (managed Karpenter)Karpenter (self-installed) or Auto Mode (managed Karpenter); Cluster Autoscaler is also possibleCluster autoscaler + node auto-provisioning; Autopilot does this automatically
Managed observabilityAzure Monitor managed Prometheus + Managed Grafana + Container insightsAmazon Managed Prometheus / Grafana + CloudWatch Container InsightsGoogle Cloud Managed Service for Prometheus + Cloud Logging/Monitoring
Managed GitOpsFlux extension (microsoft.flux)No built-in option (install Argo CD or Flux yourself)Config Sync (a Fleet feature; check the GKE docs for availability)

How: map this lesson's general capabilities to platform settings

Lesson moduleAKSEKSGKE
M2 Node scalingaz aks nodepool update --enable-cluster-autoscaler / --node-provisioning-mode AutoKarpenter NodePool + EC2NodeClass / Auto Modegcloud container clusters update --enable-autoscaling / Autopilot
M3 Observability--enable-azure-monitor-metricsAMP managed collector / ADOTManaged Service for Prometheus (managed collection is enabled by default; check the docs)
M4 Node pressure / shutdownCustom node configuration (subset of kubelet parameters); Spot evictionNode template / launch template; Spot interruption handlingNode system configuration; Spot VMs
M5 Upgradesaz aks upgrade, az aks nodepool upgrade --max-surgeeksctl upgrade cluster + node group updateRelease channels + maintenance windows / exclusions
M6 Control planeManaged by the platform; az aks rotate-certsManaged by the platformManaged by the platform; credential rotation

When: how to choose (single-cloud or multi-cloud selection)

  • Small team, minimal operations: AKS Automatic / EKS Auto Mode / GKE Autopilot. The trade-off is less control over nodes (for example, privileged DaemonSets and some kernel parameters are restricted).
  • Need special nodes (GPU topology, Windows, custom kernel parameters, a specific CNI): Standard mode + self-managed node pools.
  • Tight IP address space: AKS Overlay is a natural fit. EKS needs prefix delegation or custom networking. On GKE, plan the secondary range ahead of time.
  • Compliance requires no upgrades for a long time: AKS Premium + LTS, EKS extended support, or the GKE Extended channel. All of these cost extra, and you still cannot “never upgrade”.
  • Identity system: if your organization already runs on Entra ID / IAM / Google Cloud IAM, choose the platform that integrates with it. That way you avoid running two permission systems.
Common misconceptions ① “Managed means no upgrades needed”: all three have version support windows. After a version expires, you are forced to upgrade or pay more. ② “The control plane is free”: the AKS Free tier has no SLA. EKS and GKE charge a management fee per cluster (GKE has a free allowance; check the official pricing). ③ “PDBs don't matter in fully managed mode”: node replacement (drift, upgrades, consolidation) still goes through eviction. PDBs and replica counts decide whether there is downtime. ④ “The LoadBalancer Service behaves the same on all three”: annotations, health checks, source IP preservation, and internal LB syntax all differ. ⑤ “EKS Pod IPs use up addresses the same way AKS Overlay does”: the VPC CNI uses subnet IPs by default.

Responsibility boundary comparison

AKSEKSGKE Control plane (managed by Azure)Free / Standard / Premium(LTS) Control plane (managed by AWS)Standard support 14 months + extended 12 months Control plane (managed by Google)zonal / regional · release channels Automatic: system pool + NAP managedStandard: VMSS node poolsCA or NAP (Karpenter) Auto Mode: nodes and core add-ons managedManaged node groups / self-managed / FargateKarpenter Autopilot: nodes managed by GoogleStandard: node poolsCA + automatic node provisioning CNI Overlay + CiliumEntra ID · Workload Identity VPC CNI (Pods use VPC IPs)Access entries · Pod Identity / IRSA VPC native · Dataplane V2Cloud IAM · Workload Identity Federation You always own: workload specs (requests, probes, PDBs) · RBAC and NetworkPolicy · images and the supply chain · application and data backups · alerts and runbooks · costThe content of modules 2–5 and 8 applies on all three platforms.
Figure 7-1: the higher the layer, the more the platform handles. Fully managed mode also hands the middle layer to the platform, but the bottom layer always stays yours.

Where Pod IPs come from

AKS · Azure CNI OverlayNode IPs: VNet subnet 10.224.0.0/16Pod IPs: separate CIDR 10.244.0.0/16SNAT out of the cluster to the node IP✔ Does not use up VNet addresses EKS · VPC CNINode IPs: VPC subnetPod IPs: same subnet (ENI secondary IPs / prefixes)Pods are directly routable within the VPC⚠ Subnet IP exhaustion is a common failure GKE · VPC-native (alias IP)Node IPs: subnet primary rangePod IPs: subnet secondary rangeOne Pod range allocated per node⚠ Plan the size of the secondary range
Figure 7-2: IP planning is one of the decisions that is “hardest to change after go-live”, so finish it before you create the cluster (for AKS networking, see AKS Hour 2; for EKS, see Hour 7, Module 2)

Interactive comparison: pick a dimension and see how all three platforms handle it

Click a dimension button. Three cards show each platform's approach and key commands. The log below lists the questions to ask in a production review.

Pick a dimension to start.
# Review questions will appear here

Core command comparison (mostly read-only checks)

PurposeAKS (az)EKS (aws / eksctl)GKE (gcloud)
Available versionsaz aks get-versions -l LOC -o tableaws eks describe-cluster-versionsgcloud container get-server-config --region R
Get credentialsaz aks get-credentials -g RG -n C + kubelogin convert-kubeconfig -l azurecliaws eks update-kubeconfig --name Cgcloud container clusters get-credentials C --region R
Cluster overviewaz aks show -g RG -n C -o yamlaws eks describe-cluster --name Cgcloud container clusters describe C --region R
Upgradable versionsaz aks get-upgrades -g RG -n Ceksctl upgrade cluster --name C (preview without --approve); cluster insights: aws eks list-insightsgcloud container get-server-config (view default and available versions by channel)
Node poolsaz aks nodepool list -g RG --cluster-name C -o tableeksctl get nodegroup --cluster Cgcloud container node-pools list --cluster C --region R
Maintenance windowaz aks maintenanceconfiguration list— (you start the control plane upgrade)gcloud container clusters update C --maintenance-window-start …

aks-lab production readiness check (one query)

az aks show -g rg-k8s-lab -n aks-lab --query "{tier:sku.tier, k8s:currentKubernetesVersion, support:supportPlan,
  netPlugin:networkProfile.networkPlugin, mode:networkProfile.networkPluginMode, dataplane:networkProfile.networkDataplane,
  outbound:networkProfile.outboundType, aadRbac:aadProfile.enableAzureRbac, localAccounts:disableLocalAccounts,
  oidc:oidcIssuerProfile.enabled, wi:securityProfile.workloadIdentity.enabled,
  autoUpgrade:autoUpgradeProfile.upgradeChannel, nodeOs:autoUpgradeProfile.nodeOsUpgradeChannel,
  privateApi:apiServerAccessProfile.enablePrivateCluster, authIps:apiServerAccessProfile.authorizedIpRanges}" -o yaml
az aks nodepool list -g rg-k8s-lab --cluster-name aks-lab \
  --query "[].{name:name,mode:mode,vm:vmSize,zones:availabilityZones,auto:enableAutoScaling,surge:upgradeSettings.maxSurge}" -o table
aadRbac: true
authIps: null
autoUpgrade: none
dataplane: cilium
k8s: 1.37.1
localAccounts: false
mode: overlay
netPlugin: azure
nodeOs: NodeImage
oidc: true
outbound: loadBalancer
privateApi: null
support: KubernetesOfficial
tier: Free
wi: true
Name       Mode    Vm               Zones          Auto    Surge
---------  ------  ---------------  -------------  ------  -------
nodepool1  System  Standard_D4s_v5  ['1','2','3']  False   1

Compare against the production baseline: the tier should be Standard (or Premium), local accounts should be disabled, the API should be private or have authorized IP ranges, system and user pools should be separate, surge should be 33%, and you need an auto-upgrade channel plus a maintenance window. Field paths may change with the Azure CLI version, so use az aks show -o json as the reference.

Read-only checks for EKS / GKE (for reading)

aws eks describe-cluster --name eks-lab --query "cluster.{ver:version,support:upgradePolicy.supportType,access:accessConfig.authenticationMode,endpointPublic:resourcesVpcConfig.endpointPublicAccess,autoMode:computeConfig.enabled}"
aws eks list-access-entries --cluster-name eks-lab
aws eks list-insights --cluster-name eks-lab
gcloud container clusters describe gke-lab --region us-central1 \
  --format="yaml(currentMasterVersion,releaseChannel,autopilot,networkConfig.datapathProvider,workloadIdentityConfig,maintenancePolicy)"
gcloud container node-pools list --cluster gke-lab --region us-central1

Lab 7: three-platform selection review + read-only aks-lab health check (about 12 minutes)

Run the health check queries from the “Commands” tab against aks-lab, and enter the results in the “Current state” column of the table below. (Free tier, local accounts not disabled, and so on are the lab cluster's “deliberate simplifications”.)
Check itemProduction baselineCurrent state
Control plane tierStandard / Premium(fill in)
Nodes spread across availability zones + system and user pools separatedYes
Pod networkingOverlay + Cilium (or VNet mode after IP planning)
Human identityEntra ID + Azure RBAC, local accounts disabled
Workload identityWorkload Identity (no long-lived keys)
API accessPrivate cluster / VNet integration / authorized IP ranges
UpgradesChannel + maintenance window + surge 33% (module 5)
ObservabilityManaged Prometheus + alerts (module 3)
BackupVelero / AKS Backup (hour 4)
Verify the platform-independent parts inside the cluster (the same on all three)
kubectl config use-context aks-lab
kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.azure.com/agentpool
kubectl get pdb -A
kubectl get pods -A -o jsonpath='{range .items[?(@.status.qosClass=="BestEffort")]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}' | head
kubectl get --raw /metrics | grep -c apiserver_requested_deprecated_apis

These checks (zone spread, PDBs, BestEffort Pods, deprecated APIs) use exactly the same commands on EKS and GKE. Only the node label prefixes differ (eks.amazonaws.com/nodegroup, cloud.google.com/gke-nodepool).

Selection exercise: for each of the three scenarios below, write one recommendation (platform + mode + reason), then expand the reference answers.
  1. A five-person startup team, all stateless services, already on Microsoft 365 / Entra ID.
  2. A large retail company with an existing AWS landing zone. Its VPC address space is already allocated for connectivity to the on-premises data center, and it needs GPU inference nodes.
  3. A regulated industry that requires each Kubernetes minor version to be used for at least 18 months.
Reference answers

1: AKS Automatic (Entra integration, managed nodes, Standard SLA). 2: EKS Standard + Karpenter (GPU NodePool). Enable prefix delegation or custom networking on the VPC CNI so Pods get a separate secondary CIDR, or evaluate Auto Mode support for GPU instances. 3: AKS Premium + LTS, EKS extended support, or the GKE Extended channel. All of these cost extra. You still need to plan the final upgrade and the deprecated API checks.

(Optional) After you create an EKS cluster by following Hour 7, Module 0, run the read-only checks from the “Commands” tab against EKS, and compare the results side by side with the aks-lab results.
Cleanup: this lab is read-only, so there is nothing to clean up. If the course is over, follow the module 0 instructions: az aks stop or delete the resource group.

Case 1: the “hidden differences” of one app on three clouds

Background: A SaaS company deploys shop to both AKS and EKS. Problem: During a scale-up peak on EKS, Pods get stuck in ContainerCreating, and events show that no IP could be allocated. This never happened on AKS. Cause: With the EKS VPC CNI, Pods consume subnet IPs, so a /24 subnet ran out quickly. AKS uses Overlay, so Pod IPs come from a separate CIDR. Fix: On EKS, enable prefix delegation and enlarge the subnet, and cap Pod density per node with a Karpenter NodePool. Include a “per-platform IP budget” in capacity planning (hour 7, module 2).

Case 2: different support windows lead to “forced upgrades”

Problem: The team assumed all three platforms had the same support windows. The EKS cluster entered extended support and its costs went up, and a GKE cluster was automatically upgraded to a new minor version during its maintenance window, which exposed a deprecated API. Fix: Maintain one shared “version calendar” (the AKS supported versions page, the EKS version calendar, and the GKE release schedule). Run the same deprecated API check on every platform before upgrading (module 5). On GKE, use a maintenance exclusion to block minor upgrades during peak sales events.

Case 3: migrating from AKS Standard to AKS Automatic

Motivation: A platform team of three maintains 20 clusters, and node pool scaling and upgrades take up much of their time. Assessment: Automatic enforces Deployment safeguards and a baseline PSS. A few older DaemonSets that use hostPath cannot be deployed and need rework. NAP does not support Windows node pools. Fix: Create a new Automatic cluster, rebuild the workloads with GitOps (module 1), and shift traffic over namespace by namespace, instead of converting the cluster in place. For details, see AKS Hour 1 · AKS Standard and AKS Automatic.

Common errors and fixes (by platform)

AKS: Forbidden … User "xxx" cannot list resource "pods" … (right after an Azure RBAC role was assigned)

Cause: An Azure RBAC role assignment takes a few minutes to propagate, or the scope is a namespace and you are querying the whole cluster.

az role assignment list --assignee $(az ad signed-in-user show --query id -o tsv) --scope $AKS_ID -o table
kubectl auth can-i list pods -n shop
EKS: error: You must be logged in to the server (Unauthorized)

Cause: The current IAM identity has no access entry (or it still relies on the deprecated aws-auth ConfigMap).

aws sts get-caller-identity
aws eks list-access-entries --cluster-name eks-lab

See hour 7, module 3 (access entries and Pod Identity).

EKS: failed to assign an IP address to container (Pod stuck in ContainerCreating)

Cause: Subnet IPs are exhausted, or the node has hit its ENI/IP limit. Fix: Prefix delegation, enlarge or add subnets, or use custom networking. AKS Overlay does not have this problem, but you still need to watch the node subnet size (surge nodes need IPs too).

GKE: Pod rejected by Autopilot: … violates Autopilot policy / privileged containers or hostPath are not allowed

Cause: Autopilot enforces security constraints (similar to AKS Automatic's Deployment safeguards). Fix: Rework the workload to remove the privilege requirement. If you really need it, use a Standard mode node pool. Check the GKE docs for the exact allowlist.

All three platforms: after an upgrade, the external IP of a LoadBalancer Service changes or health checks fail

Cause: Each platform uses different LB annotations (internal LB, health probe path, source IP preservation with externalTrafficPolicy: Local). If you copy annotations over during a migration, they silently stop working. Fix: Check each annotation against the platform docs. Prefer Gateway API (hour 3), and use reserved static addresses for public IPs.

Command-line tasks

1. Use one az command to show the control plane tier, Kubernetes version, and network plugin mode of aks-lab.

Reference answer
az aks show -g rg-k8s-lab -n aks-lab --query "{tier:sku.tier,k8s:currentKubernetesVersion,mode:networkProfile.networkPluginMode}" -o table

2. Write the commands to get a kubeconfig on EKS and on GKE.

Reference answer
aws eks update-kubeconfig --name eks-lab --region us-east-1
gcloud container clusters get-credentials gke-lab --region us-central1

Scenario analysis: Management asks, “Since you already use managed Kubernetes, why do you still need modules 4 and 5 of this hour?” How do you answer?

Reference answer

The managed service covers the control plane (and part of the node lifecycle), but nodes still get replaced. Upgrades, node image updates, Karpenter/NAP consolidation, and Spot reclaims all evict Pods, and node-pressure eviction is still performed by the kubelet. Whether an app has zero downtime depends on replica count, PDBs, probes, requests, and graceful termination. All of these live in the workload spec, so they are your responsibility. Platform upgrades can also fail, or be forced through, because of deprecated APIs.

Video

No verified video found. No video for the AKS / EKS / GKE comparison topic could be verified with a YouTube oEmbed ID.

Official docs and next courses

Video storyboard

This course page cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: Three buildings (AKS, EKS, GKE), each with a roof labeled “Control plane managed” and a foundation labeled “Your workloads”.
Narration: All three manage the control plane, but the foundation, meaning your workload specs, is always your responsibility.
Shot 2 · 0:20–0:50
Visual: Three Pod IP sources side by side: Overlay, VPC CNI, and alias IP.
Narration: Networking is the hardest decision to change later. AKS Overlay does not use VNet addresses, EKS Pods use subnet addresses directly, and GKE uses a secondary range.
Shot 3 · 0:50–1:30
Visual: Version calendar: AKS 12 months (LTS 24), EKS 14+12, GKE channels and Extended.
Narration: Every platform has support windows and forced upgrades, and extended support always costs extra.
Shot 4 · 1:30–2:00
Visual: Badges for AKS Automatic, EKS Auto Mode, and GKE Autopilot. When a node is replaced, the PDB shield is still doing its job.
Narration: Fully managed modes reduce node operations, but nodes still get replaced. PDBs, probes, and requests still decide whether there is downtime.
Or score ≥ 70% on the quiz

Module 8 · Master Troubleshooting Decision Tree for Production Incidents

51:00 – 60:00 · Tie together the troubleshooting methods from the first six hours into one approach: triage by symptom, work from the outside in, and mitigate first, then find the root cause
9 minCovers hours 1–6★★★★★
Learning objectives
  • Use one fixed triage process (scope → recent changes → signals → hypothesis → verify → mitigate) to handle any K8s failure.
  • Pick the first commands to run based on the symptom: kubectl can't connect, Pod is abnormal, Service is unreachable, storage, permissions, scaling, upgrades, node NotReady.
  • Diagnose a NotReady node: kubelet, containerd, disk/memory/PID pressure (module 4), PLEG, network plugin, and certificates (module 6).
  • Use the incident response runbook template and the blameless postmortem template.
Prerequisites: All content from hours 1–6. Importance: ★★★★★

What: six triage questions

  1. What is the blast radius? One Pod / one Deployment / one namespace / one node / one availability zone / the whole cluster / external access only?
  2. What changed? Recent deployments (kubectl rollout history, helm history, Argo CD history, Git log), upgrades (module 5), configuration, certificate expiry, cloud platform events (Azure Service Health).
  3. What do the signals say? Events (kubectl events), status (describe), logs (logs --previous), metrics (Prometheus / top).
  4. Which layer? Work from the outside in: DNS / certificates / load balancer → Gateway / Service → EndpointSlice → Pod → container → node → control plane → cloud resources.
  5. How do you mitigate? Roll back (rollout undo / helm rollback / git revert), scale out, cordon the node, shift traffic, or pause GitOps auto-sync.
  6. How do you fix the root cause and prevent a repeat? Postmortem: root cause, contributing factors, detection gaps, and action items (alerts, tests, policies, runbooks).

Why: symptom → first command to run (summary of hours 1–6)

SymptomFirst command to runMost common causeSee
kubectl can't connect / 401 / 403kubectl config current-context, kubectl cluster-info, kubectl auth can-i --list, kubectl get --raw /readyz?verboseWrong context, expired token (kubelogin), authorized IP ranges, missing RBACHours 1 and 5; M7 (per-platform identity)
Pendingkubectl describe pod and check Events (FailedScheduling)Insufficient resources, taints or affinity, unbound PVC, quotaHours 2 and 4; M2 (node scaling)
ImagePullBackOff / ErrImagePullkubectl describe podTag does not exist, no permission on the private registry (AcrPull), Docker Hub rate limits, architecture mismatchHour 1; Docker course
CrashLoopBackOffkubectl logs --previous, lastState.terminatedConfiguration error, unreachable dependency, overly aggressive liveness probe, OOMKilled (137)Hours 1 and 2; M3
Running but not Readykubectl describe pod (Readiness probe failed)Wrong probe path or port, dependency not readyHour 2
CreateContainerConfigErrorkubectl describe podReferenced ConfigMap, Secret, or key does not existHour 2
FailedCreate (ReplicaSet event)kubectl describe rs, kubectl events --types=WarningPSS rejection, quota exceeded, admission webhook rejection or timeoutHour 5
Service unreachablekubectl get endpointslices -l kubernetes.io/service-name=X, netshoot to test DNS and portsSelector mismatch, wrong targetPort, NetworkPolicy deny, DNS (ndots)Hours 1 and 3
External access failskubectl get gateway,httproute -A, describe to check the Accepted / ResolvedRefs conditionsparentRefs or hostname mismatch, missing certificate Secret, LB has no IP assigned, ReferenceGrantHour 3
PVC Pending / FailedMount / Multi-Attachkubectl describe pvc/pod, kubectl get volumeattachmentWrong StorageClass, availability zone mismatch, RWO volume held by another nodeHour 4
Forbiddenkubectl auth can-i VERB RES --as=… -n …Missing Role or Binding, Azure RBAC scope, wrong SAHour 5
HPA not scaling outkubectl describe hpaMissing requests, metrics-server failure, maxReplicas reachedM2
Upgrade stuckkubectl get pdb -A, AKS upgrade eventsPDB cannot be satisfied, deprecated API, quotaM5
Pod shows Evicted / Failedkubectl get pod -o jsonpath='{.status.reason} {.status.message}', describe node ConditionsNode memory or disk pressure, emptyDir or ephemeral-storage limit exceeded, usage far above requestsM4
Helm release failed / GitOps OutOfSynchelm history, argocd app diffpending-* status, rendering error, a controller modifies fields (replicas)M1; Helm and Argo CD courses
x509 expired / etcd alerts (self-managed cluster)kubeadm certs check-expiration, etcdctl endpoint statusCertificates expired because the cluster was not upgraded for a year, etcd space quota, member failureM6
Node NotReadykubectl describe node (Conditions); on the node, journalctl -u kubelet, crictl pskubelet or containerd stopped, disk pressure, CNI not ready, expired certificates, VM failureThis module

How: how NotReady nodes work

The kubelet regularly updates its own Lease (in the kube-node-lease namespace, every 10 seconds by default) and its NodeStatus. If the node-lifecycle-controller receives no heartbeat within node-monitor-grace-period (about 40 seconds by default; check the version docs), it sets Ready to Unknown and adds the node.kubernetes.io/unreachable taint. Pods tolerate that taint for 300 seconds by default, after which they are evicted (taint-based eviction).

ConditionWhat True meansCommon root causesFirst check
Ready=False/Unknownkubelet unhealthy or unreachablekubelet crashed, containerd stopped, certificate expired, network partition, VM stoppedsystemctl status kubelet containerd, journalctl -u kubelet
DiskPressureFree space on nodefs / imagefs below the eviction thresholdContainer logs, accumulated images, emptyDir fulldf -h /var/lib/containerd /var/log, crictl rmi --prune
MemoryPressureAvailable memory below thresholdPods without limits, overcommitted nodekubectl top pods -A --sort-by=memory
PIDPressurePID count near the limitFork bomb, thread leakps -eLf | wc -l
NetworkUnavailableNode network not configuredCNI plugin not ready (Cilium or Calico Pods crashing)kubectl -n kube-system get pods -o wide | grep -E "cilium|calico"
“PLEG is not healthy” (the reason text for Ready=False)The Pod lifecycle event generator did not finish a relist within 3 minutesContainer runtime stuck or overloaded, node I/O saturation, too many containersIs crictl ps hanging, journalctl -u containerd, iostat

1.37 Alpha also introduces node lifecycle conditions (such as DrainInProgress), which may make drain state more observable in the future. Do not rely on them in production yet.

When: when to escalate to an incident

A user-visible SLO breach (error rate, latency), a data risk (storage or databases), or a security event (suspicious exec, privilege escalation) should be declared an incident right away, with an Incident Commander assigned. A single non-critical Pod restart goes through a normal ticket.

Common misconceptions ① “Just restart it and see”: this destroys evidence (logs, memory, connection state). Capture describe, logs --previous, and an events snapshot first. ② “Pod is healthy, so the service is healthy”: you also need to check EndpointSlices, Gateway conditions, NetworkPolicies, and external dependencies. ③ “Delete the node when it's NotReady”: AKS has automatic node repair. Before you do anything manual, check whether repair is already in progress, and cordon and drain the node to protect workloads.

Layered troubleshooting diagram, outside in

① Client / DNS / TLS certificate / WAF —— dig, curl -v, openssl s_client ② Load balancer / Gateway / HTTPRoute —— kubectl get gateway,httproute; check the conditions with describe ③ Service / EndpointSlice / kube-proxy (nftables) —— get endpointslices; nft list ruleset ④ NetworkPolicy / DNS (CoreDNS) —— netshoot: dig api.shop, nc -zv ⑤ Pod status / probes / events —— describe pod, events --for ⑥ Container: logs / exit code / resources —— logs --previous, top, debug ⑦ Node: kubelet / containerd / pressure —— debug node/, journalctl, crictl ⑧ Control plane / cloud resources —— /readyz, AKS diagnostics, Service Health At each layer, use one or two commands to confirm or rule it out, then move to the next layer. Don't skip layers and guess.
Figure 8-1 uses the same outside-in approach as the Docker course, just with more layers.

Incident response process

DetectAlert / user report Declare and assign rolesIC · communications · operations TriageScope · changes · signals MitigateRoll back · scale out · shift traffic Recover and verifySLO back to normal PostmortemBlameless · action items
Figure 8-2: mitigation comes before root cause. Get users back first, then investigate calmly.

Step-by-step animation: a real incident (502 spike after a release)

Follow the timeline to see which command was run at each step, what conclusion was reached, and why each decision was made.

Click “Play”.
14:02 ALERT ShopHighErrorRate 5xx ratio 23% (threshold 2%)

“First minute” troubleshooting command pack

NS=shop; TS=$(date +%Y%m%d-%H%M%S); mkdir -p ~/incident-$TS && cd ~/incident-$TS
kubectl config current-context > context.txt
kubectl get nodes -o wide > nodes.txt
kubectl -n $NS get all,endpointslices,pdb,hpa,httproute -o wide > ns.txt
kubectl -n $NS events --types=Warning > events.txt
kubectl -n $NS describe pods > pods-describe.txt
for p in $(kubectl -n $NS get pods -o name); do kubectl -n $NS logs $p --all-containers --previous > "$(basename $p)-prev.log" 2>/dev/null; kubectl -n $NS logs $p --all-containers --since=30m > "$(basename $p).log"; done
helm -n $NS history api 2>/dev/null | tail -5 > helm.txt; kubectl -n $NS rollout history deploy/api > rollout.txt
ls -la
CategoryCommandPurpose
Clusterkubectl get --raw '/readyz?verbose', kubectl get --raw '/livez?verbose'Individual apiserver checks
Clusterkubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail -30Cluster-wide alert events
Nodeskubectl describe node N | sed -n '/Conditions/,/Addresses/p'Pressure and Ready reason
Nodeskubectl get lease -n kube-node-leaseWhether heartbeats are updating
Nodes (AKS)az aks nodepool show … --query provisioningState, az vmss list-instancesVM-level status
Inside the nodekubectl debug node/N -it --image=busybox:1.37 --profile=sysadmin → chroot /hostsystemctl status kubelet containerd, journalctl -u kubelet -n 200, crictl ps -a, df -h
Networkkubectl run tmp --rm -it --image=nicolaka/netshoot -- bashdig, curl, nc, tcpdump (mind PSS)
Permissionskubectl auth can-i --list --as=system:serviceaccount:shop:api -n shopWhat the SA can do
Mitigatekubectl rollout undo deploy/api, helm rollback, argocd app rollback, kubectl cordon NRoll back / isolate
AKS diagnosticsPortal: “Diagnose and solve problems”; az aks command invoke; az aks show --query powerStatePlatform-level issues

Incident response runbook template

# Runbook: shop 5xx error rate rising
Alert triggered: ShopHighErrorRate (5xx > 2%, sustained for 5 minutes)   Severity: SEV2 (>10% escalates to SEV1)
Owner: on-call SRE (IC)  Communications: #inc-shop channel, status page updated every 15 minutes

1. Confirm (2 minutes): Grafana “shop overview”; kubectl -n shop get pods,hpa; is only one availability zone or node affected?
2. Recent changes (2 minutes): argocd app history shop-prod; helm -n shop history api; AKS activity log (upgrades and scaling)
3. Mitigation decision:
   - Release within the last 30 minutes → roll back immediately (argocd app rollback shop-prod <id> or git revert)
   - CPU saturated or HPA at its limit → temporarily raise maxReplicas and confirm node scaling
   - Dependency (db) failure → switch to read-only mode or turn on the fallback switch
4. Evidence: run the “first minute command pack” and attach the output to the incident ticket
5. Verify recovery: error rate < 1% for 15 minutes; close the incident and complete the postmortem within 48 hours

Postmortem template (blameless)

# Postmortem: <title> (SEV2, 2026-11-15 14:02–14:31, lasted 29 minutes)
## Summary: one sentence on what happened and how big the impact was
## Impact: share of affected users and requests, SLO budget consumed, data impact
## Timeline (UTC): detection → declaration → mitigation → recovery (attach command output and screenshots)
## Root cause: the technical root cause (for example, readinessProbe pointed at /healthz, and the new version was marked Ready before the DB connection pool finished initializing)
## Contributing factors: what made the problem worse (no canary, alert threshold too high, outdated runbook)
## What went well / role of luck
## Action items (owner · due date · tracking link)
- [ ] Change readinessProbe to /readyz and check dependencies (P1)
- [ ] Argo Rollouts canary + automated analysis (P2)
- [ ] Alert: Ready replica ratio < 80% (P2)

Lab 8: fault-injection drill (kind, about 15 minutes, in pairs: one person injects, one investigates)

For each fault, first diagnose it yourself using the decision tree on the “Troubleshooting” tab, then expand the answer. After each fault drill, run the matching recovery command.

Fault A: wrong Service selector
kubectl -n shop patch svc api -p '{"spec":{"selector":{"app":"api-v2"}}}'
Diagnosis and recovery
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api     # ENDPOINTS is empty
kubectl -n shop get pods --show-labels | grep api
kubectl -n shop patch svc api -p '{"spec":{"selector":{"app":"api"}}}'
Fault B: NetworkPolicy blocks DNS
cat <<'EOF' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: chaos-deny-egress, namespace: shop }
spec: { podSelector: {}, policyTypes: [Egress] }
EOF
Diagnosis and recovery
kubectl -n shop exec deploy/web -- nslookup api.shop 2>&1 | tail -2    # times out
kubectl -n shop get netpol
kubectl -n shop delete netpol chaos-deny-egress
Fault C: memory limit too small → OOMKilled
kubectl -n shop set resources deploy/api --limits=memory=8Mi
Diagnosis and recovery
kubectl -n shop get pods -l app=api        # CrashLoopBackOff / OOMKilled
kubectl -n shop get pod -l app=api -o jsonpath='{.items[0].status.containerStatuses[0].lastState.terminated.reason}'
kubectl -n shop rollout undo deploy/api
Fault D: node NotReady (kubelet stopped)
docker exec lab-worker2 systemctl stop kubelet
Diagnosis and recovery
kubectl get nodes -w                         # lab-worker2 becomes NotReady after about 40 seconds
kubectl describe node lab-worker2 | grep -A8 Conditions   # Kubelet stopped posting node status
kubectl get node lab-worker2 -o jsonpath='{.spec.taints}'  # unreachable taint
docker exec lab-worker2 systemctl status kubelet --no-pager | head -5
docker exec lab-worker2 systemctl start kubelet
Fault E: missing RBAC
kubectl -n shop create sa auditor
kubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:auditor
Diagnosis and recovery
kubectl -n shop create rolebinding auditor-view --clusterrole=view --serviceaccount=shop:auditor
kubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:auditor   # yes
kubectl -n shop delete rolebinding auditor-view; kubectl -n shop delete sa auditor
Fault F: Pod evicted by kubelet (module 4)
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata: { name: hog, namespace: shop }
spec:
  replicas: 1
  selector: { matchLabels: { app: hog } }
  template:
    metadata: { labels: { app: hog } }
    spec:
      securityContext: { runAsNonRoot: true, runAsUser: 65534, seccompProfile: { type: RuntimeDefault } }
      containers:
        - name: c
          image: busybox:1.37
          command: ["sh","-c","sleep 20; dd if=/dev/zero of=/scratch/x bs=1M count=30; sleep 3600"]
          securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ["ALL"] } }
          resources: { requests: { cpu: 10m, memory: 16Mi }, limits: { memory: 64Mi } }
          volumeMounts: [{ name: scratch, mountPath: /scratch }]
      volumes: [{ name: scratch, emptyDir: { sizeLimit: 10Mi } }]
EOF
Diagnosis and recovery
kubectl -n shop get pods -l app=hog -w           # old Pods show Error/Evicted, and the ReplicaSet keeps recreating new Pods
kubectl -n shop get pods -l app=hog --field-selector=status.phase=Failed   -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.status.reason}{" "}{.status.message}{"
"}{end}'
kubectl -n shop delete deploy hog
kubectl -n shop delete pods --field-selector=status.phase=Failed

Signal: Pods keep cycling through “evicted → recreated”, with the message Usage of EmptyDir volume "scratch" exceeds the limit "10Mi". Prevention: set sizeLimit based on real needs, and write large files to a PVC or object storage.

Review: for each fault, write one line: “detection signal → first command → root cause → prevention” (for example, for fault C, the prevention is a LimitRange minimum plus VAP validation, from hour 5).

Case 1: availability zone outage

Symptoms: Network problems in one availability zone in canadacentral; 1/3 of the nodes are NotReady. Response: Confirmed in Azure Service Health. Because hour 2 configured topologySpreadConstraints and PDBs, api still had 2/3 of its replicas serving traffic. HPA scaled out in the remaining zones, and the CA added nodes in the healthy zones. The stateful db (on LRS disks) cannot move across zones, so it depends on the hour 4 backup restore or ZRS disks. Action items: Move the database to ZRS or a managed service, and rehearse zone failure drills.

Case 2: admission webhook timeout blocks Pod creation cluster-wide

Symptoms: All Deployment rollouts are stuck, and ReplicaSet events show failed calling webhook … context deadline exceeded. Cause: All webhook Pods for the policy engine were on a node being drained, and failurePolicy: Fail is set. Response: Temporarily change the webhook's failurePolicy to Ignore, or delete the ValidatingWebhookConfiguration. After recovery, run several webhook replicas with a PDB and anti-affinity, and prefer ValidatingAdmissionPolicy (in-process CEL with no network dependency, hour 5).

Case 3: node disk full (DiskPressure)

A service writes debug logs to stdout at 5 MB per second, and kubelet log rotation cannot keep up. The node enters DiskPressure and starts evicting BestEffort Pods. Response: Lower the log level (commit it through GitOps), adjust the kubelet containerLogMaxSize (on AKS, through custom node configuration), set sizeLimit on emptyDir, and add an alert on kube_node_status_condition{condition="DiskPressure"}.

Interactive master troubleshooting decision tree (covers 6 hours)

Start from the symptom and work through step by step. Each leaf gives the diagnostic command and the direction for the fix.

Extra: quick reference for common errors

The connection to the server localhost:8080 was refused - did you specify the right host or port?

Cause: No kubeconfig (~/.kube/config does not exist, or KUBECONFIG points to an empty file), so kubectl falls back to the default localhost:8080.

echo $KUBECONFIG; ls -l ~/.kube/config
kind export kubeconfig --name lab        # or az aks get-credentials -g rg-k8s-lab -n aks-lab
Node lab-worker2 status: NotReady · Reason: KubeletNotReady · container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: cni plugin not initialized

Cause: The CNI plugin DaemonSet (Cilium, Calico, or kindnet) is not running on this node or is crashing, and /etc/cni/net.d is empty.

kubectl -n kube-system get pods -o wide --field-selector spec.nodeName=lab-worker2
kubectl -n kube-system logs ds/kindnet --tail=50     # AKS: cilium / azure-cns
PLEG is not healthy: pleg was last seen active 3m10s ago; threshold is 3m0s

Cause: kubelet's PLEG relist times out. The container runtime is responding slowly (containerd stuck, disk I/O saturated, or too many containers).

# On the node (kubectl debug node/… → chroot /host)
time crictl ps >/dev/null
journalctl -u containerd --since "15 min ago" | tail -50
systemctl restart containerd     # cordon and drain the node before running this
x509: certificate has expired or is not yet valid (kubectl or kubelet)

Cause: On a self-managed cluster, the certificate has expired (kubeadm defaults to 1 year), or the node clock is skewed. AKS rotates node kubelet certificates automatically. CA rotation uses az aks rotate-certs, which rebuilds the nodes with up to about 30 minutes of downtime, so it needs a maintenance window. For renewal steps, see module 6.

sudo kubeadm certs check-expiration
timedatectl status
Command-line tasks

1. List the 30 most recent Warning events across the whole cluster, and find all Pods that are not in the Running or Completed state.

Reference answer
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail -30
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded

2. A node is NotReady and you don't have SSH access. Write the command to get into the node and view the kubelet logs.

Reference answer
kubectl debug node/aks-user-12345678-vmss000002 -it --image=busybox:1.37 --profile=sysadmin
chroot /host
journalctl -u kubelet --since "30 min ago" | tail -100
systemctl status containerd

If the node is completely unreachable (kubelet is not working), a debug Pod cannot be scheduled, so use az vmss run-command invoke or AKS automatic node repair instead.

Scenario analysis: At 17:00 on Friday, after a release, the 5xx rate for api rose from 0.1% to 8%. All Pods are Running and Ready, and HPA is behaving normally. What do you do in the first 10 minutes?

Reference answer

① Declare an incident and assign an IC. ② The most recent change is this release, so mitigate first: GitOps git revert or argocd app rollback (or helm rollback). ③ Save evidence at the same time: logs from the new Pods, error samples, and Grafana screenshots. ④ After the rollback, verify that the error rate has recovered. ⑤ Afterwards: Ready but still erroring means the readinessProbe does not cover the dependencies (for example, DB connections or configuration). Add a canary with automated analysis, improve the probes, and write the postmortem.

Video

No verified video was found that covers Kubernetes troubleshooting methods and has a verifiable video ID. For a review of the course concepts, see:

▶
Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours] — TechWorld with Nana
English · about 4 hours · overall review (an older version; the commands in this hour take precedence)

Official docs

Video storyboard

This course page cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: An alert goes off, and the screen fills with red.
Narration: When something fails, what matters most is not memorizing every command. It is having a fixed process.
Shot 2 · 0:20–1:00
Visual: The layered troubleshooting diagram lights up from the outside in.
Narration: Work through the client, the gateway, the Service, and network policy, then down to the Pod, the container, the node, and the control plane. At each layer, one or two commands confirm it or rule it out.
Shot 3 · 1:00–1:40
Visual: Interactive decision tree: node NotReady → kubelet → PLEG.
Narration: When a node isn't ready, check its status conditions first. Then go onto the node and read the kubelet and containerd logs.
Shot 4 · 1:40–2:00
Visual: The postmortem document template, with action items checked off.
Narration: Mitigate first, then find the root cause, and finally use a blameless review to turn what you learned into alerts, tests, and policies.
Or score ≥ 70% on the quiz

Hours 1–6 Command Cheat Sheet

Command summary for the full course (hours 1–6) · Kubernetes 1.37 · Helm 4 · AKS · every code block can be copied with one click
Reference after classCovers 6 hours

Clusters and contexts (hour 1)

kubectl config get-contexts; kubectl config use-context kind-lab
kubectl config set-context --current --namespace=shop
kubectl cluster-info; kubectl version
kubectl get --raw '/readyz?verbose'
kubectl api-resources --namespaced=true -o wide
kubectl explain deploy.spec.strategy --recursive
kubectl get nodes -o wide -L topology.kubernetes.io/zone
kind create cluster --name lab --config kind-lab.yaml
kind delete cluster --name lab

Resources and output (hour 1)

kubectl apply -f x.yaml --server-side [--dry-run=server]
kubectl diff -f x.yaml
kubectl get pods -o wide --show-labels -l app=api
kubectl get deploy api -o yaml | kubectl neat   # plugin (optional)
kubectl get pods -o kyaml                       # 1.37 GA
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o custom-columns=N:.metadata.name,NODE:.spec.nodeName
kubectl label pod P tier=be --overwrite; kubectl annotate …
kubectl delete -f x.yaml; kubectl get all -n shop

Pod debugging (hours 1 and 6)

kubectl describe pod P; kubectl events --for pod/P -w
kubectl logs P -c C --previous --tail=100 --since=10m
kubectl logs -l app=api --all-containers --prefix
kubectl exec -it P -c C -- sh
kubectl debug -it P --image=busybox:1.37 --target=C --profile=restricted
kubectl debug P -it --copy-to=P-dbg --container=C -- sh
kubectl debug node/N -it --image=busybox:1.37 --profile=sysadmin
kubectl port-forward svc/api 9898:9898
kubectl top pods --containers --sort-by=memory

Deployments and rollouts (hours 1–2)

kubectl create deploy api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --replicas=2
kubectl set image deploy/api podinfo=ghcr.io/stefanprodan/podinfo:6.17.0
kubectl annotate deploy/api kubernetes.io/change-cause="v6.17.0"
kubectl rollout status|history|undo|pause|resume|restart deploy/api
kubectl rollout undo deploy/api --to-revision=2
kubectl scale deploy/api --replicas=3
kubectl set resources deploy/api --requests=cpu=100m,memory=64Mi --limits=memory=128Mi
kubectl patch pod P --subresource resize -p '{"spec":{"containers":[{"name":"c","resources":{"requests":{"cpu":"200m"}}}]}}'   # 1.35 GA
kubectl create pdb api --selector=app=api --min-available=1

Workloads and scheduling (hour 2)

kubectl get sts,ds,job,cronjob -A
kubectl create job once --from=cronjob/db-backup
kubectl rollout status sts/db
kubectl taint nodes N dedicated=gpu:NoSchedule[-]
kubectl cordon|uncordon N
kubectl drain N --ignore-daemonsets --delete-emptydir-data --timeout=10m
kubectl get pods -o wide --field-selector spec.nodeName=N
kubectl get priorityclass; kubectl get resourcequota,limitrange -n shop

Networking (hour 3)

kubectl expose deploy api --port=9898
kubectl get svc,endpointslices -l app=api
kubectl get endpointslices -l kubernetes.io/service-name=api
kubectl run tmp --rm -it --image=nicolaka/netshoot -- bash   # dig api.shop.svc.cluster.local
kubectl get gatewayclass,gateway,httproute,grpcroute -A
kubectl describe httproute shop   # Accepted / ResolvedRefs
kubectl get networkpolicy -A
ingress2gateway print --providers=ingress-nginx
kubectl -n kube-system get cm kube-proxy -o yaml | grep mode   # nftables recommended

Storage (hour 4)

kubectl get sc,pv,pvc -A; kubectl describe pvc data-db-0
kubectl get volumeattachment
kubectl patch pvc data-db-0 -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'
kubectl get volumesnapshotclass,volumesnapshot
kubectl -n shop exec db-0 -- pg_dump -U postgres app > app.sql
velero backup create shop-$(date +%F) --include-namespaces shop
velero restore create --from-backup shop-2026-11-15
kubectl patch pv PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

Security (hour 5)

kubectl auth can-i --list --as=system:serviceaccount:shop:api -n shop
kubectl auth whoami
kubectl create role|rolebinding|clusterrole|clusterrolebinding …
kubectl create token api -n shop --duration=10m
kubectl label ns shop pod-security.kubernetes.io/enforce=restricted --overwrite
kubectl label ns shop pod-security.kubernetes.io/warn=restricted --dry-run=server
kubectl get validatingadmissionpolicy,validatingadmissionpolicybinding
kubectl get secret -n shop; kubectl get sa -n shop

Helm 4 (M1 overview · see the Helm course for details)

helm create C; helm lint C; helm template R C -f v.yaml
helm upgrade --install R C -n NS --create-namespace -f v.yaml \
  --rollback-on-failure --timeout 10m --history-max 15
helm upgrade R C --wait=watcher          # wait using kstatus
helm history R; helm rollback R [REV]; helm uninstall R
helm get values|manifest|notes R [--revision N] [--all]
helm package C; helm push C-0.2.0.tgz oci://ACR.azurecr.io/helm
helm install R oci://ACR.azurecr.io/helm/C --version 0.2.0
helm show values oci://…/C; helm registry login ACR.azurecr.io

Kustomize (M1)

kubectl kustomize overlays/prod
kubectl apply -k overlays/prod [--server-side]
kubectl diff -k overlays/prod
kubectl delete -k overlays/dev
kustomize edit set image ghcr.io/stefanprodan/podinfo=…@sha256:…
kustomize edit fix              # commonLabels→labels etc.
kustomize build --enable-helm overlays/prod

Scaling (M2)

kubectl autoscale deploy api --cpu-percent=60 --min=2 --max=10
kubectl get hpa -w; kubectl describe hpa api
kubectl get --raw /apis/metrics.k8s.io/v1/namespaces/shop/pods
kubectl top nodes
az aks nodepool update -g RG --cluster-name AKS -n NP \
  --enable-cluster-autoscaler --min-count 1 --max-count 5
az aks update -g RG -n AKS --node-provisioning-mode Auto   # NAP
az aks update -g RG -n AKS --enable-keda --enable-vpa

GitOps (M1 · see the Argo CD course for details)

kubectl apply -n argocd --server-side --force-conflicts \
  -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.1/manifests/install.yaml
argocd admin initial-password -n argocd
argocd app list|get|diff|sync|history|rollback APP
kubectl -n argocd get applications
flux get kustomizations; flux reconcile ks NAME --with-source
az k8s-configuration flux create -g RG -c AKS -t managedClusters -n cfg \
  -u https://github.com/you/repo --branch main \
  --kustomization name=apps path=./overlays/prod prune=true

Upgrades and maintenance (M5)

kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis
pluto detect-all-in-cluster --target-versions k8s=v1.37.0
sudo kubeadm upgrade plan; sudo kubeadm upgrade apply v1.37.1
az aks get-upgrades -g RG -n AKS -o table
az aks upgrade -g RG -n AKS --kubernetes-version V --control-plane-only
az aks nodepool upgrade -g RG --cluster-name AKS -n NP --kubernetes-version V --max-surge 33%
az aks nodepool upgrade … --node-image-only
az aks update -g RG -n AKS --auto-upgrade-channel stable --node-os-upgrade-channel NodeImage
kubectl get events --field-selector reason=Drain,reason=Surge,reason=Upgrade

AKS az commands (M0 · M5 · M7)

az aks get-versions -l canadacentral -o table
az aks create -g RG -n AKS --tier standard --zones 1 2 3 \
  --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium \
  --enable-oidc-issuer --enable-workload-identity --enable-aad --enable-azure-rbac \
  --attach-acr ACR --generate-ssh-keys
az aks get-credentials -g RG -n AKS; kubelogin convert-kubeconfig -l azurecli
az aks nodepool add -g RG --cluster-name AKS -n user --mode User --zones 1 2 3
az aks enable-addons -g RG -n AKS --addons azure-keyvault-secrets-provider,azure-policy,monitoring
az aks update -g RG -n AKS --enable-azure-monitor-metrics
az aks update -g RG -n AKS --api-server-authorized-ip-ranges X.X.X.X/32
az aks command invoke -g RG -n AKS --command "kubectl get pods -A"
az aks stop|start -g RG -n AKS; az group delete -n RG --yes --no-wait

Eviction and disruption (M4)

kubectl get --raw "/api/v1/nodes/N/proxy/configz" | jq '.kubeletconfig.evictionHard'
kubectl describe node N | sed -n '/Conditions/,/Addresses/p'
kubectl get pods -A --field-selector=status.phase=Failed
kubectl get pod P -o jsonpath='{.status.reason} {.status.message}'
kubectl get pod P -o jsonpath='{.status.conditions[?(@.type=="DisruptionTarget")]}'
kubectl create --raw /api/v1/namespaces/NS/pods/P/eviction -f eviction.json   # 429 = rejected by PDB
kubectl taint nodes N node.kubernetes.io/out-of-service=nodeshutdown:NoExecute  # only after confirming the node is shut down
kubectl delete pods -A --field-selector=status.phase=Failed

etcd and certificates (M6 · self-managed clusters)

ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379   --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt   --key=/etc/kubernetes/pki/etcd/server.key snapshot save snap.db
etcdutl --write-out=table snapshot status snap.db
etcdutl --data-dir /var/lib/etcd-restore snapshot restore snap.db
etcdctl … endpoint status -w table; etcdctl … member list
sudo kubeadm certs check-expiration; sudo kubeadm certs renew all
kubectl get csr; kubectl certificate approve CSR
az aks rotate-certs -g RG -n AKS     # rebuilds nodes, up to about 30 minutes of downtime

Cross-platform comparison (M7)

# Credentials
az aks get-credentials -g RG -n C; kubelogin convert-kubeconfig -l azurecli
aws eks update-kubeconfig --name C --region R
gcloud container clusters get-credentials C --region R
# Versions and upgrades
az aks get-upgrades -g RG -n C -o table
aws eks describe-cluster-versions; aws eks list-insights --cluster-name C
gcloud container get-server-config --region R
# Node pools
az aks nodepool list -g RG --cluster-name C -o table
eksctl get nodegroup --cluster C
gcloud container node-pools list --cluster C --region R

Quick troubleshooting table (summary of hours 1–6)

SymptomFirst actionCommon causes
Pendingkubectl describe pod → FailedSchedulingInsufficient resources, taints, affinity, PVC, quota
ImagePullBackOffdescribe pod eventsWrong tag, no AcrPull, rate limits, architecture
CrashLoopBackOfflogs --previous, exit codeConfiguration, dependencies, OOM (137), liveness
Running but 0/1 Readydescribe pod probe eventsreadinessProbe path or port
Service unreachableget endpointslicesselector, targetPort, NetworkPolicy
Gateway 404/503describe httproute conditionsparentRefs, hostname, backend port, ReferenceGrant
PVC Pendingdescribe pvcStorageClass, WaitForFirstConsumer, availability zone
Forbiddenauth can-i … --asRoleBinding, Azure RBAC scope
PodSecurity rejectionRS event FailedCreatesecurityContext does not meet restricted
HPA <unknown>describe hpaMissing requests, metrics-server
GitOps stuck OutOfSyncargocd app diffController modifies fields → ignoreDifferences
Upgrade stuckget pdb -AALLOWED DISRUPTIONS = 0
Pod Evictedget pod -o jsonpath='{.status.message}'Node memory or disk pressure, emptyDir or ephemeral storage limit exceeded
Node NotReadydescribe node Conditionskubelet / containerd, disk pressure, CNI, PLEG
x509 certificate expired (self-managed)kubeadm certs check-expirationNot upgraded for a year, clock skew

For the full interactive flow, see Module 8 → Troubleshooting → master decision tree.

Recommended config snippet: a production-ready Deployment (summary of hours 2, 3, 5, and 6)

apiVersion: apps/v1
kind: Deployment
metadata: { name: api, namespace: shop, labels: { app: api, app.kubernetes.io/part-of: shop } }
spec:
  revisionHistoryLimit: 5
  strategy: { type: RollingUpdate, rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 } }
  selector: { matchLabels: { app: api } }
  template:
    metadata: { labels: { app: api } }
    spec:
      serviceAccountName: api
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: 30
      securityContext: { runAsNonRoot: true, runAsUser: 10001, seccompProfile: { type: RuntimeDefault } }
      topologySpreadConstraints:
        - { maxSkew: 1, topologyKey: topology.kubernetes.io/zone, whenUnsatisfiable: ScheduleAnyway, labelSelector: { matchLabels: { app: api } } }
      containers:
        - name: api
          image: ghcr.io/stefanprodan/podinfo:6.17.0      # use @sha256 digest in production
          ports: [{ name: http, containerPort: 9898 }]
          resources: { requests: { cpu: 100m, memory: 64Mi }, limits: { memory: 128Mi } }
          startupProbe:   { httpGet: { path: /healthz, port: http }, failureThreshold: 30, periodSeconds: 2 }
          readinessProbe: { httpGet: { path: /readyz,  port: http }, periodSeconds: 5 }
          livenessProbe:  { httpGet: { path: /healthz, port: http }, periodSeconds: 10, failureThreshold: 3 }
          lifecycle: { preStop: { sleep: { seconds: 5 } } }
          securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: ["ALL"] } }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: api, namespace: shop }
spec: { maxUnavailable: 1, selector: { matchLabels: { app: api } } }

lifecycle.preStop.sleep is a native sleep action (the image does not need a sleep command). Confirm that your cluster version enables it by default (recent versions do). When you use HPA (M2), do not manage replicas in GitOps.

Overall Capstone Lab + Final Quiz

Deliver shop from scratch on AKS (or kind): ACR → Helm / Kustomize → GitOps → Gateway + TLS → security baseline → database and backups → HPA → eviction protection → zero-downtime upgrade → troubleshooting → cleanup
After class ≈ 2–3 hoursCovers all modules in hours 1–6AKS cost about 2–4 USD
Scenario You are a platform engineer who needs to deliver shop (web nginx + api podinfo 6.17.0 + db postgres:17) to aks-lab as a “production service”. Requirements: images come from ACR and are deployed by digest; all deployments go through Git (GitOps); HTTPS for external access; namespace PSS restricted, default-deny networking, least privilege; the database is persistent and has recoverable backups; api scales on CPU; probes show zero failures during node upgrades; and a single injected fault can be located within 15 minutes.
Alternative environment: Without AKS, complete the lab on kind lab (replace ACR with a local registry or ghcr, and change the upgrade steps to reading plus a drain rehearsal).
Image: import or build, then push to ACR (Docker course · hour 1)
RG=rg-k8s-lab; AKS=aks-lab; ACR=<your ACR name>
az acr import -n $ACR --source ghcr.io/stefanprodan/podinfo:6.17.0 -t shop/api:6.17.0
az acr import -n $ACR --source docker.io/library/postgres:17 -t shop/db:17
mkdir -p ~/final/web && cd ~/final/web
cat > Dockerfile <<'EOF'
FROM nginx:1.29-alpine
RUN sed -i 's/listen  *80;/listen 8080;/' /etc/nginx/conf.d/default.conf && \
    chown -R 101:101 /var/cache/nginx /var/run /var/log/nginx
COPY index.html /usr/share/nginx/html/index.html
USER 101
EXPOSE 8080
EOF
echo '<h1>shop web</h1>' > index.html
az acr build -r $ACR -t shop/web:1.0.0 .
for r in api db web; do az acr repository show-tags -n $ACR --repository shop/$r -o tsv; done
API_DIGEST=$(az acr repository show -n $ACR --image shop/api:6.17.0 --query digest -o tsv); echo $API_DIGEST

Running nginx as non-root requires an unprivileged port (8080) and writable directories. With a read-only root filesystem, you also need emptyDir mounts for /var/cache/nginx and /var/run (hour 5). Check Docker Hub for the currently available base image tags.

Packaging: api uses a Helm chart; web, db, and policies use Kustomize overlays (M1; for writing charts, see Helm Hour 2)
cd ~/k8s6
sed -i "s#repository: .*#repository: $ACR.azurecr.io/shop/api#" shop-api/values.yaml
helm package shop-api && az acr login -n $ACR && helm push shop-api-0.2.0.tgz oci://$ACR.azurecr.io/helm
# GitOps repo layout (suggested):
# k8s6-gitops/
#   platform/          cert-manager, Gateway implementation, kube-prometheus-stack (Helm-type Application for Argo CD)
#   kshop/base/        web, db (STS + headless Svc + volumeClaimTemplates), Service
#   kshop/components/  netpol-default-deny, pss-restricted (Namespace labels), rbac-team, hpa
#   kshop/overlays/prod  images point to $ACR by digest; HTTPRoute; backup CronJob
#   apps/              Argo CD Applications: shop-api (Helm OCI, values-prod.yaml), shop-prod (Kustomize)

No shop-api chart yet? Use helm create shop-api to generate the skeleton, then adapt it following Helm Hour 1 · Deploy myapp (port 9898, probes /readyz and /healthz, and a securityContext that satisfies PSS restricted). You can also keep api on Kustomize (the overlay from module 1); either choice works. This lab deliberately uses both Helm and Kustomize to show two Argo CD source types.

GitOps deployment (M1; for installation and credentials, see Argo CD Hour 1)
kubectl config use-context aks-lab
kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.1/manifests/install.yaml
kubectl -n argocd rollout status deploy/argocd-repo-server
# Helm charts in ACR need Argo CD repo credentials (OCI): use an ACR token (az acr token create) or Workload Identity (follow the Argo CD docs)
argocd repo add $ACR.azurecr.io/helm --type helm --enable-oci --username <token-name> --password <token-password>
kubectl apply -f apps/        # shop-api (Helm) + shop-prod (Kustomize), both automated + prune + selfHeal
kubectl -n argocd get applications -w

kubelet pulls images through --attach-acr, and Argo CD only needs read credentials for the chart. Do not mix up the two identities.

External exposure: Gateway API + TLS (hour 3)
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata: { name: shop-gw, namespace: shop }
spec:
  gatewayClassName: <your-gatewayclass>
  listeners:
    - name: https
      protocol: HTTPS
      port: 443
      hostname: shop.example.com
      tls: { mode: Terminate, certificateRefs: [{ name: shop-tls }] }   # Secret generated by the cert-manager Certificate
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: shop, namespace: shop }
spec:
  parentRefs: [{ name: shop-gw }]
  hostnames: [shop.example.com]
  rules:
    - matches: [{ path: { type: PathPrefix, value: /api } }]
      filters: [{ type: URLRewrite, urlRewrite: { path: { type: ReplacePrefixMatch, replacePrefixMatch: / } } }]
      backendRefs: [{ name: api, port: 9898 }]
    - backendRefs: [{ name: web, port: 8080 }]
kubectl -n shop get gateway shop-gw -o jsonpath='{.status.addresses[0].value}{"\n"}'
GW=<address from the output above>
curl -sk --resolve shop.example.com:443:$GW https://shop.example.com/api/version

If you don't have a real domain, use a self-signed cert-manager ClusterIssuer. With a domain, use ACME (Let's Encrypt) with HTTP-01 or DNS-01. On AKS, you can also evaluate Gateway API support in the application routing add-on. The AKS docs are the source of truth.

Security baseline (hours 3 and 5)
kubectl get ns shop --show-labels | grep 'enforce=restricted'
kubectl -n shop get networkpolicy               # default-deny + allow gateway→web→api→db, DNS, monitoring
kubectl auth can-i delete deploy -n shop --as=system:serviceaccount:shop:api    # should be no
kubectl -n shop run bad --image=busybox:1.37 --restart=Never --overrides='{"spec":{"containers":[{"name":"bad","image":"busybox:1.37","securityContext":{"privileged":true}}]}}'   # should be rejected by PSS
Database and backups (hours 2 and 4)
kubectl -n shop get sts db; kubectl -n shop get pvc
kubectl -n shop exec db-0 -- psql -U postgres -c "create table if not exists orders(id serial primary key, item text); insert into orders(item) values ('final-lab');"
kubectl -n shop create job db-backup-now --from=cronjob/db-backup     # CronJob: pg_dump → Azure Files PVC / Blob
kubectl -n shop logs job/db-backup-now
# Restore drill: delete the table → restore from backup → verify the row count (or velero backup/restore, hour 4)
Scaling: HPA load test (M2)
kubectl -n shop get hpa
for i in 1 2 3; do kubectl -n shop run load$i --image=busybox:1.37 --restart=Never --labels=app=web \
  --overrides='{"spec":{"securityContext":{"runAsNonRoot":true,"runAsUser":65534,"seccompProfile":{"type":"RuntimeDefault"}},"containers":[{"name":"l","image":"busybox:1.37","command":["/bin/sh","-c","while true; do wget -q -O- http://api.shop:9898 >/dev/null; done"],"securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}'; done
kubectl -n shop get hpa api -w
kubectl -n shop delete pod load1 load2 load3

Note: Argo CD's ignoreDifferences must ignore /spec/replicas. Otherwise, selfHeal will reset the replicas that the HPA scaled out (Module 1, case 3).

Eviction protection check (M4)
kubectl -n shop get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass,PRIO:.spec.priority
kubectl -n shop get pods -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.volumes[?(@.emptyDir)].emptyDir}{"
"}{end}'   # check whether every emptyDir has a sizeLimit
kubectl get pods -A --field-selector=status.phase=Failed     # there should be no leftover Evicted pods
kubectl get --raw "/api/v1/nodes/$(kubectl get nodes -o name | head -1 | cut -d/ -f2)/proxy/configz" | jq '.kubeletconfig.evictionHard'

Acceptance: api, web, and db have no BestEffort pods; every emptyDir sets a sizeLimit; key services set a PriorityClass; record the hard eviction thresholds for the AKS nodes.

Zero-downtime node upgrade (M5)
# External probe (run on the lab VM):
while true; do curl -sk -o /dev/null -w "%{http_code}\n" --resolve shop.example.com:443:$GW https://shop.example.com/api/healthz; sleep 1; done | tee probe.log &
az aks nodepool upgrade -g $RG --cluster-name $AKS -n user --node-image-only --max-surge 33% --yes
# (If the control plane is still on 1.36, run --control-plane-only first, then upgrade the node pool to 1.37)
kill %1; grep -vc '^200$' probe.log     # expect 0
Fault injection and troubleshooting (M8): Ask a partner to inject one of faults A–F from the Module 8 lab at random, or make up your own (for example, a Git commit with a wrong image digest, or a NetworkPolicy rule that removes db access). Use the master decision tree to find the fault within 15 minutes, fix it through Git, and write a one-page postmortem.
Cleanup (required)
kubectl -n argocd delete applications --all      # cascade-deletes the workloads
az group delete -n rg-k8s-lab --yes --no-wait     # deletes the AKS, ACR, and MC_ resource groups (cannot be undone)
az group list --query "[?starts_with(name,'MC_rg-k8s-lab')].name" -o tsv    # confirm the node resource group is also deleted
kind delete cluster --name lab
Acceptance checklist (12 items)

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

1. From git push to a new pod receiving traffic, which components are involved?

CI builds and pushes the image to ACR → updates the digest in the GitOps repo → Argo CD detects the commit, renders the manifests (Helm/Kustomize), compares them, and applies them with SSA to the apiserver (authentication → authorization → admission: PSS, VAP) → etcd → the Deployment controller creates a new ReplicaSet → the scheduler picks a node → the kubelet pulls the image through CRI (containerd) using the kubelet's managed identity with AcrPull, then creates the container, and CNI configures networking → the readinessProbe passes → the EndpointSlice is updated → kube-proxy/Cilium and the Gateway start forwarding traffic.

2. How do Helm and Kustomize divide the work on your team?

Use Helm for third-party components and for apps you distribute. It's parameterized and keeps release records. Use Kustomize for internal apps that differ across environments, because its patches are easy to review. Put both under GitOps, and roll back with git revert. Argo CD renders Helm without creating Helm release records.

3. How do the HPA, Cluster Autoscaler, and PDB interact during a node upgrade?

During an upgrade, drain goes through the Eviction API, which respects PDBs. Evicted pods that can't fit on the remaining capacity go Pending, which triggers CA or NAP to add nodes. The HPA keeps the replica count matched to load. minReplicas should be high enough that the PDB can always be satisfied. If a PDB can't be satisfied, the upgrade gets stuck. With too few replicas, capacity is tight during the surge.

4. Why does a production cluster benefit from GitOps instead of running kubectl apply in CI?

CI no longer holds cluster write credentials. Every change is auditable and easy to roll back. Continuous reconciliation detects drift. The cluster can be rebuilt from Git. With a private cluster, CI doesn't need access to the API.

5. Before you upgrade a 1.36 cluster to 1.37, what's on your checklist?

Deprecated APIs (metrics + pluto/kubent), 1.37 deprecations (ipvs → nftables, kube-dns → CoreDNS, cgroup v1 nodes, kubectl run -f), webhook and operator compatibility, whether PDBs can be satisfied, surge quota, AKS-specific items (LocalDNS, the managed Prometheus basicAuth Secret), backups, the maintenance window, and a rollback plan (new node pool or blue-green).

6. A pod is Running and Ready, but users get 502 errors. In what order do you troubleshoot?

Work from the outside in: DNS and certificates → Gateway/HTTPRoute conditions and backend references → Service and EndpointSlice (selector, targetPort) → NetworkPolicy → curl localhost inside the pod to check the app → app logs and dependencies (db). Also check recent changes, and roll back first if you need to stop the bleeding.

Final quiz (12 questions, covering the 8 modules in this hour)

6-hour review roadmap

HourOne-line summaryLinks
Hour 1 · Architecture and Core ObjectsKubernetes works by declaring a desired state and having control loops keep reconciling toward it. An apply goes through authentication, authorization, and admission before it's written to etcd. Controllers and the scheduler watch those objects, and the kubelet turns them into running pods through the CRI and CNI.k8s-h1.ch.html
Hour 2 · Workloads and Schedulingrequests and limits determine scheduling and QoS. Probes and graceful termination determine zero-downtime behavior. Deployment, StatefulSet, DaemonSet, and Job each have a distinct role. Affinity, taints, and topology spread determine where pods land.k8s-h2.ch.html
Hour 3 · NetworkingEach pod gets its own IP. Services load-balance with EndpointSlices and kube-proxy (nftables). CoreDNS handles service discovery. The Gateway API v1.6 replaces the retired ingress-nginx, and NetworkPolicy enforces zero trust.k8s-h3.ch.html
Hour 4 · Storage and Stateful ApplicationsPVCs get PVs dynamically from a StorageClass through CSI. Access modes and zone topology determine whether a volume can be mounted. A StatefulSet with volumeClaimTemplates runs a database, and Velero handles backup and restore.k8s-h4.ch.html
Hour 5 · Security and Multi-TenancyAuthentication → RBAC authorization → admission (PSS, VAP). ServiceAccounts and Workload Identity give passwordless access to cloud resources. securityContext hardens containers. Secrets are encrypted with Key Vault. Quotas and audit logs support multi-tenancy.k8s-h5.ch.html
Hour 6 · Production Operations: Scaling, Upgrades, and TroubleshootingChoose between Helm, Kustomize, and GitOps. Use HPA and node scaling for load. Use metrics, logs, events, and kubectl debug to locate problems. Understand kubelet eviction and node shutdown. Upgrade with zero downtime within the version skew policy. Back up etcd and renew certificates. Compare the three major managed platforms. Use the master decision tree to troubleshoot systematically.This hour

Next steps

Certifications
CKAD (application developer: workloads, configuration, probes, Helm/Kustomize basics) → CKA (administrator: kubeadm install and upgrade, etcd backup and restore, networking, storage, troubleshooting) → CKS (security: supply chain, runtime security, network policies, auditing; you must pass CKA first). Exam versions follow the newer Kubernetes minor releases. Check the current Linux Foundation exam curriculum before you register.
Official docs sections
Concepts → Workloads / Services, Load Balancing, and Networking / Storage / Security / Policies. Tasks → Administer a Cluster (kubeadm upgrades, etcd) / Debug. Reference → API, kubectl, Feature Gates. Releases → release notes for each minor version and the Deprecated API Migration Guide.
Operator development
CRDs and the controller pattern → client-go informer/workqueue → controller-runtime / Kubebuilder (or Operator SDK) → status conditions and finalizers → envtest testing. Start by writing a “ShopBackup” CRD for shop.
Service mesh
mTLS, traffic splitting, retries and timeouts, observability: Istio (AKS has an Istio add-on, ambient mode), Linkerd, Cilium Service Mesh. The Gateway API's GAMMA (east-west routing) is the unified direction.
eBPF
Cilium (AKS CNI powered by Cilium), Hubble network observability, Tetragon runtime security, Inspektor Gadget (included on AKS nodes). Understand how eBPF programs replace iptables and sidecars.
Platform engineering
Multi-cluster (AKS Fleet Manager, Cluster API), internal developer platforms (Backstage), policy as code (Kyverno/Gatekeeper/VAP), cost governance (OpenCost), progressive delivery (Argo Rollouts/Flagger).
Next steps 🎓 Six 1-hour sessions: architecture → workloads → networking → storage → security → production operations. Next, take Hour 7 · Kubernetes on AWS (EKS), then review production problems and interview questions in hour 8. Follow-up courses on the learning path: Helm → GitOps with Argo CD → Prometheus & Grafana, plus AKS. Redo the capstone lab within two weeks without looking at the hints, and keep your GitOps repo as a personal portfolio piece.

Sources and versions

Sources for every technical fact in this hour. Verified on 2026-11-15. The restructured modules and new Modules 4, 6, and 7 were re-verified on 2026-11-17.
TopicFindingsSource (page date)
Kubernetes versionsSupports 1.37 (1.37.1, 2026-09-15, EOL 2027-10-28), 1.36, and 1.35. 1.34 is EOL.kubernetes.io/releases
v1.37 changesmetrics.k8s.io GA. HPA configurable tolerance GA. HPA scale-to-zero Beta (on by default). Native Histograms Beta. ipvs and kube-dns deprecated. failCgroupV1 defaults to true (since 1.35).v1.37 release blog (2026-08-26) and series posts (HPA scale to zero 2026-09-02, Native Histograms Beta 2026-09-11)
Version skew policykubelet/kube-proxy up to 3 minor versions behind. kcm/scheduler/CCM up to 1 minor version behind. kubectl ±1. Upgrade in order, and don't skip minor versions.Version Skew Policy
HPAFormula, 15-second period. Default tolerance 0.1. behavior.scaleUp/scaleDown.tolerance is stable in 1.37. Scale-to-zero requires Object or External metrics, HPAScaleToZero is Beta in 1.37 and on by default, and the ScaledToZero condition applies. Default behavior: scale-down uses a 300s window; scale-up adds 100% or 4 Pods every 15s, with selectPolicy Max.Horizontal Pod Autoscaling
kubectl debug / events--profile defaults to general; options are general, baseline, restricted, netadmin, and sysadmin. --share-processes defaults to true. --custom and --keep-labels. kubectl events supports --for, --types, -w, and -o kyaml.kubectl debug · kubectl events
Node pressure eviction (M4)Signals: memory.available, nodefs/imagefs/containerfs (available, inodesFree), pid.available. Linux default hard thresholds: memory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5%, imagefs.inodesFree<5%. housekeeping runs every 10s. The default pressure transition period is 5m. evictionMinimumReclaim defaults to 0. Hard eviction grace period is 0s. Soft eviction is limited by evictionMaxPodGracePeriod. PDBs and terminationGracePeriodSeconds are not respected. Ranking: usage above requests → Priority → amount over. oom_score_adj: Guaranteed −997, BestEffort 1000. HugepageAwareEviction is Beta in 1.37.Node-pressure Eviction
API eviction and disruption conditions (M4)The Eviction API returns 200 (allowed), 429 (disallowed by a PDB or rate-limited), or 500 (misconfiguration, such as multiple PDBs). It respects PDBs and terminationGracePeriodSeconds. The DisruptionTarget condition has been GA since 1.31. Reasons: PreemptionByScheduler, DeletionByTaintManager, EvictionByEvictionAPI, DeletionByPodGC, TerminationByKubelet.API-initiated Eviction · Disruptions
Node shutdown (M4)Linux graceful shutdown is Beta (on by default since 1.21, uses a systemd inhibitor lock). shutdownGracePeriod and shutdownGracePeriodCriticalPods default to 0 (disabled). Shutdown by priority, shutdownGracePeriodByPodPriority, is Beta. Windows graceful shutdown is Beta in 1.34. The out-of-service taint for non-graceful shutdown is GA in 1.28. Volumes are force-detached after 6 minutes.Node Shutdowns
etcd operations (M6)etcdctl snapshot save (with TLS parameters). etcdutl snapshot status / restore. The etcdctl equivalents were deprecated in 3.5 and are planned for removal in 3.6. Stop all apiservers before a restore, and afterward restart scheduler, kcm, and kubelet. With kubeadm, sync etcd.local.dataDir. Use an odd number of members, and 5 members for production. Encrypt snapshots.Operating etcd clusters for Kubernetes
kubeadm certificates (M6)Leaf certificates last 1 year (certificateValidityPeriod 8760h). The CA lasts 10 years (87600h). Control plane upgrades renew certificates automatically (you can disable this with --certificate-renewal=false). After kubeadm certs renew all, restart the static pods (moving them out of the manifest directory takes about 20 seconds). kubelet client certificates rotate automatically. CSRs for serverTLSBootstrap must be approved manually. super-admin.conf belongs to system:masters.Certificate Management with kubeadm
AKS certificates (M6)Cluster CAs for clusters created after 2019-05 are valid for 30 years. Node kubelet client and server certificates rotate automatically (this requires Kubernetes RBAC). az aks rotate-certs rebuilds all nodes, VMSSes, and disks, with up to about 30 minutes of downtime. Run get-credentials again afterward.Certificate rotation overview (2026-10-13) · Rotate certificates (2026-07-13)
GKE (M7)Release channels: Rapid, Regular (default), Stable, and Extended. Extended lets a cluster stay on one minor version for up to 24 months, and extended-period charges are based on usage. All clusters are upgraded automatically. Maintenance windows and maintenance exclusions (No upgrades for up to 90 days, No minor upgrades, and so on).Release channels
EKS (M7)Carries over the verified results from Hour 7: 14 months of standard support plus 12 months of extended support. Standard support costs 0.10 USD per cluster per hour. Auto Mode, access entries, Pod Identity, and VPC CNI.Hour 7 · Sources and versions
Helm 4Latest v4.3.2 (2026-11-13), v4.3.1 (2026-10-15), v4.3.0 (2026-09-09). New installs default to SSA. --atomic→--rollback-on-failure, --force→--force-replace (old names show deprecation warnings). --wait defaults to hookOnly; used alone, it acts as a watcher, and a legacy mode also exists. --server-side defaults to auto. --take-ownership. Post-renderers must be plugins. Registry login works by domain only. Chart v3 is experimental. Install script: get-helm-4.Helm 4 Overview · helm upgrade · Install · Releases
Helm 3 support3.22 is the last feature release (2026-09). Security fixes continue until 2027-02-10.Course standard (verified) · Helm 3 EOL
KustomizecommonLabels is deprecated since v5.0.0; use labels. kustomize edit fix migrates automatically.commonLabels reference
Argo CD / FluxArgo CD v3.6.1 (2026-11-04; v3.3 reached EOL on 2026-11-03). Flux v2.10.0 (2026-10-26).Argo CD releases · Flux releases
KEDA / VPA / kube-prometheus-stackKEDA v2.21.0 (2026-09-23). VPA 1.8.1 / 1.7.3 (2026-10-21): InPlaceOrRecreate became GA in VPA 1.6.0, and InPlace is Alpha in 1.7.0. kube-prometheus-stack 93.3.0 (2026-11-13).KEDA · VPA features · prometheus-community charts
AKS version calendar1.37: preview 2026-09, GA 2026-10, EOL 2027-10, LTS EOL 2028-10. 1.38 preview 2026-11. Platform-initiated upgrades start 2027-06. AKS 1.37 components: containerd 2.3.3 (Ubuntu 24.04), KEDA 2.20.2, VPA 1.7.1, metrics-server 0.8.0, Cilium 1.19.6. 1.37 changes to managed Prometheus basicAuth.Supported Kubernetes versions (2026-09-15, updated 2026-10-21)
AKS networking--network-plugin azure --network-plugin-mode overlay. Default pod CIDR is 10.244.0.0/16. If you specify azure without a mode, you get VNet mode.Azure CNI Overlay (2026-07-31)
AKS tiersFree (no SLA, ≤1,000 nodes). Standard (99.95% with availability zones / 99.9% without, ≤5,000 nodes). Premium (adds LTS; requires --k8s-support-plan AKSLongTermSupport).Pricing tiers (2026-07-06)
AKS AutomaticStandard tier, uptime SLA, and pod readiness SLA. NAP, managed system node pools, CNI Overlay + Cilium, Azure RBAC, Workload Identity, Deployment safeguards, stable and NodeImage channels. Gateway API is on by default in 1.36 and later.Intro to AKS Automatic (2026-07-07)
AKS upgradesget-upgrades and control-plane-only (not available when auto-upgrade is on). max-surge defaults to 1; 33% is recommended for production. max-unavailable defaults to 0. drain-timeout defaults to 30 minutes. soak: 0–30 minutes. Upgrade events: Drain, Surge, Upgrade.Control plane upgrade (2026-07-30) · Rolling upgrades (2026-05-29)
AKS auto-upgradeCluster channels: none, patch, stable, rapid, node-image (legacy). Node OS channels: None, Unmanaged, SecurityPatch, NodeImage (the new Standard default is NodeImage). Maintenance configurations: aksManagedAutoUpgradeSchedule and aksManagedNodeOSUpgradeSchedule.Auto-upgrade (2026-06-26) · Node OS auto-upgrade (2026-06-26)
AKS NAPBased on Karpenter. --node-provisioning-mode Auto + overlay + cilium. NodePool and AKSNodeClass (karpenter.sh/v1). Windows and IPv6 are not supported. The cluster can't be stopped.NAP overview · Enable NAP
AKS monitoring / GitOps--enable-azure-monitor-metrics, --azure-monitor-workspace-resource-id, --grafana-resource-id, --enable-control-plane-metrics. az aks enable-addons --addon monitoring. az k8s-configuration flux create -t managedClusters.Enable monitoring (2026-08-18) · GitOps Flux v2 (2026-08-24)

Video verification notes

All videos below were checked for title and channel through the YouTube oEmbed endpoint (verified 2026-11-15, re-checked 2026-11-17): TechWorld with Nana, “What is Helm in Kubernetes? Helm and Helm Charts explained | Kubernetes Tutorial 23” (-ykwb1d0DXU); “How Prometheus Monitoring works | Prometheus Architecture explained” (h4Sl21AKiDg); “Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1” (QoDqxm7ybLc); “What is GitOps, How GitOps works and Why it's so useful” (f5EpcWp0THw); “ArgoCD Tutorial for Beginners | GitOps CD for Kubernetes” (MeU5_k9ssrs); and “Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]” (X48VuDVv0do). No videos with verifiable IDs were found for Kustomize, autoscaling, kubectl debug, node pressure eviction and node shutdown, cluster upgrades, etcd and certificates, or the AKS/EKS/GKE comparison, so those topics only have storyboard scripts. All videos are in English. Most were recorded before Helm 4, Argo CD v3, and K8s 1.37, so this hour's content takes precedence on version details.

Voice narration notes

The Voice tab reads the narration aloud with the browser's Web Speech API (en-US). English technical terms are pronounced in en-US. Results depend on the speech voice packs installed on your operating system. This course build can't call a TTS service, so there is no embedded MP3. You can pass the narration script to Azure AI Speech or a similar tool to generate audio.

Known limitations

  • IPs, UIDs, hashes, node names, patch version numbers, and durations in the “expected output” are sample values. The column names and JMESPath structure of az aks get-versions may change with the Azure CLI version.
  • Azure costs are order-of-magnitude estimates. Use the Azure pricing calculator as the source of truth.
  • The timings in the animations (HPA cycles, node provisioning time) are illustrative values that explain the mechanism. They are not benchmarks.
  • This verification couldn't read GKE's control plane SLA percentage or management fee from the official pages. Archived versions gave inconsistent figures. The course therefore gives only a qualitative description. Refer to the GKE SLA and pricing pages. The default-enabled scope of Config Sync and Managed Service for Prometheus is also defined by the GKE docs.
  • The kubelet eviction thresholds for kind in the Module 4 lab (disk threshold 0%), the trigger time for emptyDir overflow eviction, and whether the etcd image in the Module 6 lab includes etcdutl all depend on the specific image version. The outputs are examples.
  • The following were written from the official docs but could not be tested in this environment, so they are handled conservatively and marked “refer to the official docs”: the force-handling parameter for Helm 4 SSA conflicts, the full creation parameters for AKS Automatic, the Gateway API usage for the application routing add-on, the AKS --undrainable-node-behavior parameter, the Workload Identity approach for Argo CD to access ACR OCI charts, whether HPAScaleToZero is available on AKS-managed control planes, and the specific switches for 1.37 native histograms.
  • Hours 1–5 were written in parallel with this hour, so cross-hour references follow the final content of each hour.