Narration: copying YAML and running kubectl apply from CI is where most teams start, and it is also where the problems start.
Kubernetes Hour 6: Production Operations: Scaling, Upgrades and Troubleshooting
- 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 debugmodes 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
| # | Time | Module | Core content | Animation / interactive | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Warm-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 |
| 1 | 00–06 | Production delivery toolchain overview | The roles of Helm vs Kustomize vs GitOps and how they combine, a minimal overlay, a minimal helm install, pull-based reconciliation, where to go deeper | Path comparison of the three delivery methods | Deploy the same api once with apply -k and once with Helm
|
| 2 | 06–14 | Autoscaling | HPA v2 algorithm and behavior, tolerance (1.37 GA), scale-to-zero (1.37 Beta), VPA, KEDA, CA / Karpenter / NAP | HPA control loop calculator (adjustable load) | podinfo load test + kubectl get hpa -w
|
| 3 | 14–22 | Observability and kubectl debug | Metrics / logs / events, kube-prometheus-stack, SLIs and PromQL, the three kubectl debug modes and profiles | Animation of the troubleshooting path for “one alert” | Ephemeral containers + Pod copies + node debugging |
| 4 | 22–29 | Reliability: node-pressure eviction and node shutdown | Eviction signals and thresholds, soft/hard eviction, ordering rules, graceful/non-graceful shutdown, the six termination paths and DisruptionTarget | Node memory pressure → eviction ordering simulator | emptyDir over-limit eviction + Eviction API 429 vs delete |
| 5 | 29–37 | Cluster upgrades and maintenance | Version skew, deprecated APIs, the kubeadm process, drain + PDB, AKS upgrade channels and maintenance windows | Node pool surge rolling upgrade | AKS 1.36 → 1.37 zero-downtime upgrade |
| 6 | 37–43 | Control plane operations overview | etcd roles and quorum, etcdctl snapshot save / etcdutl verification and restore, kubeadm certificate validity and renewal, AKS rotate-certs | Backup → accidental deletion → restore / certificate expiry | kind snapshot + temporary cluster restore rehearsal |
| 7 | 43–51 | Managed clusters compared: AKS / EKS / GKE | Responsibility boundaries, fully managed modes, support windows and upgrades, Pod IP sources, identity, node scaling, managed observability | Three-platform comparison, switchable by dimension | Read-only health check of aks-lab + selection exercise |
| 8 | 51–60 | Production troubleshooting: master decision tree | Summary of 6 hours of troubleshooting by symptom, nodes NotReady, eviction, certificates, runbooks and postmortems | Large interactive troubleshooting tree (40+ nodes) | Fault injection drills (A–F) |
| — | After class | Full cheat sheet · 6-hour capstone lab | Deliver shop: ACR → Kustomize/Helm → GitOps → Gateway+TLS → security → backup → HPA → eviction protection → upgrade → failures → cleanup | 12-question final quiz | 12-item acceptance checklist |
Knowledge Coverage Matrix
| Target skill | Module | Key commands | Lab | Production case |
|---|---|---|---|---|
| Delivery tool selection (Helm / Kustomize / GitOps) | M1 | kubectl apply -k, helm upgrade --install, argocd app sync | ✓ | ✓ |
| Workload autoscaling | M2 | kubectl autoscale, kubectl get hpa -w, kubectl top | ✓ | ✓ |
| Node autoscaling (CA / NAP / Karpenter) | M2 · M7 | az aks update --enable-cluster-autoscaler, --node-provisioning-mode Auto | Reading | ✓ |
| Metrics / logs / events troubleshooting | M3 · M8 | kubectl logs --previous, kubectl events --for, PromQL | ✓ | ✓ |
| Live debugging | M3 | kubectl debug --target / --copy-to / node/ | ✓ | ✓ |
| Node-pressure eviction and node shutdown | M4 | kubectl get --raw …/proxy/configz, kubectl create --raw …/eviction | ✓ | ✓ |
| Cluster upgrades and deprecated APIs | M5 | az aks get-upgrades, az aks nodepool upgrade --max-surge, kubeadm upgrade plan | ✓ | ✓ |
| etcd backup and restore, and certificates | M6 | etcdctl snapshot save, etcdutl snapshot restore, kubeadm certs check-expiration | ✓ | ✓ |
| Managed platform selection and differences | M7 | az aks show, aws eks describe-cluster, gcloud container clusters describe | ✓ | ✓ |
| Systematic troubleshooting | M8 | kubectl describe, kubectl get events, crictl, journalctl -u kubelet | ✓ | ✓ |
| Integration of 6 hours of knowledge | Capstone lab | All | ✓ | ✓ |
Topics excluded from this hour (and where to learn them)
| Topic | Reason | Where to learn |
|---|---|---|
| Helm chart development, template functions, hooks, OCI publishing, Helm 3→4 migration | Has a dedicated 8-hour course; module 1 here is only an overview | Helm 8-hour course |
| Kustomize in depth, Argo CD installation and Application, sync waves, ApplicationSet, multi-tenancy, Flux | Has 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/Mimir | The observability stack itself is a course | Prometheus & Grafana 8 + 1-hour course |
| Full AKS reference architecture (hub-spoke, private clusters, egress, Defender, cost) | Module 7 here only compares the three platforms | AKS 8-hour course · Hour 7 (EKS) |
| PDB, PriorityClass preemption, QoS, ResourceQuota | Covered in earlier hours; module 4 only ties together the disruption overview | Hour 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 it | kubernetes.io "Operating etcd clusters" · etcd official Disaster recovery |
| Argo Rollouts / Flagger progressive delivery | Canary principles were covered in hour 2 | Argo CD Hour 6 · Argo Rollouts |
| Multi-cluster (Fleet Manager, Cluster API), service mesh, operator development | Beyond 1 hour | See capstone page · next learning path |
How to use this courseware
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.
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).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).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)
- Completed hours 1–5: the kind cluster
lab(1 control plane + 2 workers, node imagekindest/node:v1.37.0), with the namespaceshopcontaining 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 grouprg-k8s-lab, regioncanadacentral. 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). Theaws/gcloudcommands 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,...
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
| Parameter | Purpose | Reason for this value |
|---|---|---|
--tier free|standard|premium | Control 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 overlay | Azure CNI Overlay: Pod IPs come from a separate CIDR (default 10.244.0.0/16) and do not use VNet address space | Note: if you write only --network-plugin azure without a mode, AKS uses the legacy VNet mode for compatibility
|
--network-dataplane cilium | Azure CNI powered by Cilium (eBPF dataplane, built-in NetworkPolicy engine) | Consistent with NAP and AKS Automatic |
--enable-oidc-issuer --enable-workload-identity | Provides the OIDC issuer and webhook for the Workload Identity in hour 5 | Always enable in production |
--enable-aad --enable-azure-rbac | Entra ID authentication + Azure RBAC for Kubernetes authorization | You need to assign yourself an AKS RBAC role (see below) |
--attach-acr | Assign AcrPull to the kubelet managed identity | No imagePullSecret needed |
--auto-upgrade-channel none | Turn off automatic cluster upgrades | With automatic upgrades on, you cannot run a --control-plane-only upgrade, and module 5 demonstrates it
|
--node-os-upgrade-channel NodeImage | Node images refresh weekly (default for new Standard clusters) | Recommended in production together with a maintenance window |
--zones 1 2 3 | Spread nodes across 3 availability zones | canadacentral 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 …
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)
| Resource | Estimate | Notes |
|---|---|---|
| 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 tier | 0 | Standard 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 day | Container Insights is billed by data ingestion |
| Total | About 0.7 USD per hour, roughly 15–20 USD for a full day | When 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
Module 1 · Production delivery toolchain overview: Helm, Kustomize and GitOps
- 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 singlehelm upgrade --install. - Understand the GitOps “pull + continuous reconciliation” model: why CI no longer needs cluster write credentials, and why a manual
kubectl editgets 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).
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).
| Tool | Essence | Problem it solves | How to roll back | Learn more |
|---|---|---|---|---|
| Helm 4 | Package 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 |
| Kustomize | No 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 output | No 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 them | Who can change production, change auditing, drift detection and automatic correction, and the ability to rebuild the cluster from Git | git revert → the controller syncs automatically | Argo 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 editat 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 applyhas no “versions”. Helm has revisions, and GitOps has Git history.
How: how the three combine (the most common production setup)
- 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. - 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.
- The controller submits to the apiserver with server-side apply (authentication → authorization → admission; hours 1 and 5), then keeps watching the actual state.
- 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
| Scenario | Recommended | Reason |
|---|---|---|
| Installing third-party components (monitoring stack, cert-manager, Gateway implementations) | Helm chart (pinned --version), brought under GitOps | Upstream ships as a chart, and values are the officially supported configuration surface |
| Your team's own microservices, with small differences between environments | Kustomize base + overlays | Plain YAML is easy to review, with no template language |
| Needs distribution to multiple teams or customers, with conditionals and loops in parameters | Helm chart (pushed to an OCI registry) | Versioned package + values schema validation |
| Multiple environments or clusters, requiring auditing and drift correction | GitOps (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 |
--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.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
Comparison diagram: three ways to write the same api
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.
Core commands (minimal set)
| Command | Purpose | Notes |
|---|---|---|
kubectl kustomize DIR | Renders only the overlay, does not access the cluster | Equivalent to kustomize build DIR; look at the output before deploying
|
kubectl apply -k DIR / kubectl diff -k DIR / kubectl delete -k DIR | Deploy / preview differences / delete | Can add --server-side
|
helm repo add NAME URL, helm search repo | Add a chart repository, look up versions | OCI registries do not need repo add; use oci:// directly
|
helm upgrade --install REL CHART -n NS --create-namespace --version V -f values.yaml | Idempotent install/upgrade | Preferred 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 back | Release records are stored in a namespaced Secret |
helm template REL CHART -f v.yaml | Render only | Can pipe into | kubectl apply --dry-run=server -f - so the apiserver validates it
|
argocd app create|get|diff|sync|history | Argo CD CLI | You can also kubectl apply an Application object directly
|
flux get kustomizations, flux reconcile ks NAME --with-source | Flux CLI | AKS: 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)
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 }
EOFcat > 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 ...
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.
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
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)
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.helm -n shop-dev uninstall api-h; kubectl delete -k overlays/dev; kubectl delete ns shop-devCase 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.
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
No verified video with a usable video ID was found for the Kustomize topic.
Official docs and follow-up courses
- Declarative Management of Kubernetes Objects Using Kustomize
- Helm 4 Overview
- OpenGitOps principles
- Argo CD docs · Flux docs
- This series: Helm 8-hour course index · GitOps and Argo CD 8-hour course index
Video storyboard script
This courseware cannot generate a video or MP3 directly, so a storyboard and a narration script are provided instead.
Narration: copying YAML and running kubectl apply from CI is where most teams start, and it is also where the problems start.
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.
Narration: GitOps has a controller inside the cluster pull from Git, while CI only writes to Git. The controller keeps comparing and correcting drift.
Narration: rollback is just reverting a commit. To go deeper, continue with the two 8-hour courses on Helm and Argo CD.
Module 2 · Autoscaling: HPA · VPA · KEDA · node scaling
- 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.
What: three levels of autoscaling
| Level | Component | What it adjusts | Trigger |
|---|---|---|---|
| Pod count | HPA (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 size | VPA (standalone project: recommender / updater / admission-controller) | Container requests/limits | Historical usage; the InPlaceOrRecreate mode uses in-place resize (in-place resize went GA in K8s 1.35) |
| Node count | Cluster Autoscaler, Karpenter, AKS NAP (managed Karpenter) | Node | Pending (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
- kube-controller-manager processes each HPA every 15 seconds (
--horizontal-pod-autoscaler-sync-period). - Reads metrics from
metrics.k8s.io(Resource, served by metrics-server, GA in 1.37),custom.metrics.k8s.io(Pods/Object), orexternal.metrics.k8s.io(External, served by KEDA / Prometheus Adapter). - Resource utilization = usage ÷ requests. If any container has no matching requests, that metric cannot be computed (the HPA event shows
missing request for cpu). - 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). - 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).
- 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).
- Changes the Deployment's replicas through the scale subresource; the Deployment controller then rolls out the Pods.
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
| Scenario | Recommended |
|---|---|
| Stateless web/API, load-related CPU | HPA (CPU utilization 50–70%) + node scaling |
| Queue consumers, scheduled batch jobs, need to scale to zero | KEDA (ScaledObject / ScaledJob, 60+ scalers); or, in 1.37, an HPA External metric + minReplicas 0 |
| You don't know what requests to set; single-replica service | VPA (start in Off mode to look at recommendations only)
|
| Nodes: a fixed set of VM sizes | Cluster Autoscaler (scales per node pool) |
| Nodes: you want the right sizes picked automatically and fragmentation consolidated | Karpenter; on AKS use NAP (--node-provisioning-mode Auto)
|
Node scaling comparison
| Cluster Autoscaler | Karpenter / AKS NAP | |
|---|---|---|
| Model | Scales existing node groups (AKS node pools = VMSS) | Chooses VM sizes directly for Pending Pods and creates nodes (NodePool / AKSNodeClass CRDs, karpenter.sh/v1) |
| Consolidation | Removes under-utilized nodes | Active consolidation, replacement with cheaper sizes, drift replacement |
| Enabled on AKS | az aks nodepool update --enable-cluster-autoscaler --min-count 1 --max-count 5 | az aks create … --node-provisioning-mode Auto --network-plugin azure --network-plugin-mode overlay --network-dataplane cilium
|
| Limits | Limited by fixed node pool sizes | NAP does not support Windows node pools or IPv6. Once enabled, the cluster cannot use az aks stop. AKS Automatic enables it by default.
|
Diagram: metrics pipeline and three levels of scaling
Data flow: the timeline of one scale-up
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
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl autoscale deploy api --cpu-percent=60 --min=2 --max=10 | Quickly create an HPA | Generates an autoscaling/v2 object; manage it with YAML in production |
kubectl get hpa -w | Watch TARGETS and REPLICAS | TARGETS shows cpu: 45%/60%; <unknown> means the metric cannot be retrieved
|
kubectl describe hpa api | Check Conditions and Events | AbleToScale / ScalingActive / ScalingLimited / ScaledToZero |
kubectl top pods --containers | Current usage | From metrics.k8s.io |
kubectl get --raw /apis/metrics.k8s.io/v1/namespaces/shop/pods | Query the metrics API directly | Stable 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 5 | Enable CA on the AKS node pool | az aks update --cluster-autoscaler-profile scale-down-unneeded-time=5m
|
az aks update --enable-keda / --enable-vpa | AKS managed KEDA / VPA add-ons | AKS 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)
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.
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
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).
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
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)
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.
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"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
- Horizontal Pod Autoscaling (tolerance, scale to zero, default behavior)
- KEDA docs
- Vertical Pod Autoscaler
- AKS Node Auto-Provisioning
- AKS Cluster Autoscaler
- This series: AKS hour 4 · Cluster Autoscaler · NAP / Karpenter · hour 7 · Karpenter and Auto Mode
Video storyboard script
This courseware cannot generate video or MP3 files directly, so the storyboard and narration script are provided instead.
Narration: Traffic changes, and the replica count should change with it.
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.
Narration: Scale-down has a default 300-second stabilization window. It takes the highest recommendation in that period, which prevents flapping.
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.
Module 3 · Observability and kubectl debug
- 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 withkubectl logsandkubectl events. - Master the three
kubectl debugmodes (ephemeral container with--target,--copy-to, andnode/) and the profiles (default: general). - Understand the AKS managed options: Azure Monitor managed service for Prometheus, Azure Managed Grafana, and Container insights.
What: three pillars + events
| Signal | Question it answers | Source in K8s | Typical backend |
|---|---|---|---|
| Metrics | How 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 |
| Logs | What 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 logs | Loki, Elasticsearch, Azure Monitor Logs (Container insights) |
| Traces | Which service is slow for a request? | Applications report through the OpenTelemetry SDK | Tempo, Jaeger, Application Insights |
| Events | What 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
| SLI | PromQL (kube-prometheus-stack metric names) | Meaning |
|---|---|---|
| Container restarts | increase(kube_pod_container_status_restarts_total{namespace="shop"}[15m]) > 2 | CrashLoop early warning |
| Pending Pod | sum by (namespace) (kube_pod_status_phase{phase="Pending"}) > 0 | Capacity or scheduling problem |
| CPU throttling | sum 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) |
| OOMKilled | kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1 | Memory limit too low, or a leak |
| Memory near the limit | container_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 latency | histogram_quantile(0.99, sum by (le, verb) (rate(apiserver_request_duration_seconds_bucket{verb!~"WATCH|CONNECT"}[5m]))) | Control plane health |
| apiserver 5xx ratio | sum(rate(apiserver_request_total{code=~"5.."}[5m])) / sum(rate(apiserver_request_total[5m])) | — |
| Node not ready | kube_node_status_condition{condition="Ready",status="true"} == 0 | See 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 |
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
| Mode | Command | Mechanism | Use case |
|---|---|---|---|
| Ephemeral container | kubectl debug -it POD --image=busybox:1.37 --target=api | Adds 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/root | distroless images have no shell; use it for situations that cannot be restarted |
| Copy Pod | kubectl 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 debugging | kubectl debug node/NODE -it --image=busybox:1.37 | Creates 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 crictl | kubelet/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.
--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)
| Need | Self-managed | Azure managed |
|---|---|---|
| Metrics | kube-prometheus-stack | Azure Monitor managed service for Prometheus (az aks update --enable-azure-monitor-metrics; optionally --enable-control-plane-metrics)
|
| Visualization | Grafana | Azure Managed Grafana (linked with --grafana-resource-id), or the built-in Azure Monitor dashboards with Grafana in the portal
|
| Logs | Fluent Bit + Loki / ES | Container insights (az aks enable-addons --addon monitoring); data goes to Log Analytics
|
Architecture diagram: metrics and logs pipelines
Workflow for an ephemeral container with kubectl debug
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.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl logs POD -c CTR | Get container logs | --all-containers, -f, --tail=100, --since=10m, --timestamps
|
kubectl logs POD --previous | Logs from the previous (crashed) container instance | Required for CrashLoopBackOff |
kubectl logs -l app=api --prefix | Aggregate logs across multiple Pods by label | --max-log-requests=10
|
kubectl logs deploy/api | Pick one Pod from a Deployment | Only one Pod |
kubectl events | Events (sorted by time; easier to read than get events) | --for pod/NAME, --types=Warning, -w, -A, -o kyaml
|
kubectl top pod/node | Current resource usage | --containers, --sort-by=memory
|
kubectl debug | Debugging | --target, --copy-to, --set-image, --share-processes (default true), --profile (default general), --custom
|
kubectl get --raw /metrics | apiserver's own metrics | For 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)
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 -wP=$(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",...}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-dbgAPI=$(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"}'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.
kubectl -n shop delete deploy crashy; kubectl get pods -A | grep node-debugger | awk '{print $2}' | xargs -r kubectl delete podCase 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}' | jqkubectl 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.
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
No kubectl debug tutorial with a verifiable video ID was found. Please follow the official docs.
Official docs
- Debug Running Pods
- kubectl debug reference
- Logging Architecture
- kube-prometheus-stack
- Enable monitoring on AKS
Later courses in this series
- Prometheus hour 1 · PromQL basics · hour 2 · Alerting rules · Dashboard design: USE / RED / Four Golden Signals
- Prometheus hour 3 · Azure Monitor managed Prometheus and AKS integration · hour 6 · SLOs and error budgets
- AKS hour 6 · Container Insights and managed Prometheus
Video storyboard script
This courseware cannot generate video or MP3 files directly, so the storyboard and narration script are provided instead.
Narration: Metrics tell you that something went wrong, but not why.
Narration: Events tell you what the control plane saw. Logs from the previous container instance tell you why the app exited.
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.
Narration: On AKS, you can build the same capabilities with managed Prometheus, Grafana, and Container insights.
Module 4 · Reliability: node-pressure eviction, node shutdown, and the disruption landscape
- 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-basedshutdownGracePeriodByPodPriority), 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 theDisruptionTargetcondition.
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.
| Signal | Meaning | Linux default hard threshold | Corresponding node condition / taint |
|---|---|---|---|
memory.available | Capacity − 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.inodesFree | Filesystem holding the kubelet root directory (emptyDir, logs, Pod directories) | <10% / <5% | DiskPressure · node.kubernetes.io/disk-pressure:NoSchedule
|
imagefs.available / imagefs.inodesFree | Filesystem where the container runtime stores images (and writable layers), if separate | <15% / <5%
| |
containerfs.available / containerfs.inodesFree | Used when the writable layer is on its own disk (split image filesystem) | Follows nodefs or imagefs | |
pid.available | Maximum PIDs − current process count | None by default | PIDPressure · node.kubernetes.io/pid-pressure:NoSchedule
|
| KubeletConfiguration field | Purpose | Default |
|---|---|---|
evictionHard | Hard threshold: evicts immediately once crossed, with a grace period of 0 seconds (does not wait for terminationGracePeriodSeconds) | See the table above |
evictionSoft + evictionSoftGracePeriod | Soft threshold: evicts only after the threshold has been crossed for a set duration, for example memory.available<1.5Gi for 1m30s | None |
evictionMaxPodGracePeriod | Maximum graceful termination time given to a Pod during a soft eviction (the smaller of this value and the Pod's own grace period) | 0 |
evictionMinimumReclaim | The minimum amount to reclaim each time, to avoid repeated evictions when usage sits right at the threshold | All resources are 0 |
evictionPressureTransitionPeriod | How long the node condition must wait before it changes from True back to False (debounce) | 5m |
systemReserved / kubeReserved | Reserved 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
- 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.
- 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.
- 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
| Mechanism | Status | How it works | Key configuration |
|---|---|---|---|
| Graceful node shutdown (Linux) | Beta, on by default since 1.21 | The 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 shutdown | Beta (the 1.37 page marks it as on by default) | Terminates Pods in batches by PriorityClass, with a separate grace period for each batch | shutdownGracePeriodByPodPriority list
|
| Graceful node shutdown (Windows) | Beta, on by default since 1.34 | The kubelet registers preshutdown handling when it runs as a Windows service | Same fields as above |
| Non-graceful node shutdown | GA (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
| Method | Initiator | Respects PDB? | Respects terminationGracePeriodSeconds? | DisruptionTarget reason |
|---|---|---|---|---|
kubectl delete pod / controller scale-in / rolling update | User / controller | No | Yes | — |
API-initiated eviction (kubectl drain, upgrades, CA scale-in) | Eviction API | Yes (returns 429 if not allowed) | Yes | EvictionByEvictionAPI
|
| Scheduler preemption | kube-scheduler | Tries to, but not guaranteed | Yes | PreemptionByScheduler
|
| Taint-based eviction (NotReady/unreachable for longer than tolerationSeconds, default 300s) | Node lifecycle controller (taint manager) | No | Yes (but the kubelet cannot run it when the node is unreachable) | DeletionByTaintManager
|
| Node-pressure eviction / graceful node shutdown / critical Pod preemption | kubelet | No | Hard threshold 0s; soft threshold uses evictionMaxPodGracePeriod; shutdown follows the shutdown configuration | TerminationByKubelet
|
| OOM Kill (container exceeds its memory limit, or node memory is exhausted) | Linux kernel | No | No (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<500Mifor 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
sizeLimiton emptyDir, and set requests/limits forephemeral-storageon 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).
Decision flow: what the kubelet does every 10 seconds
Timeline: three termination paths on the same node
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl get --raw "/api/v1/nodes/NODE/proxy/configz" | jq .kubeletconfig | View the kubelet configuration actually in effect | Requires nodes/proxy permission. Look at evictionHard and shutdownGracePeriod
|
kubectl describe node NODE | sed -n '/Conditions/,/Addresses/p' | MemoryPressure / DiskPressure / PIDPressure | When the condition is True, the matching NoSchedule taint appears |
kubectl get pods -A --field-selector=status.phase=Failed | Find evicted (Failed) Pods | The STATUS column shows Evicted or Error |
kubectl get pod P -o jsonpath='{.status.reason}{" "}{.status.message}' | Eviction reason | For example, Evicted The node was low on resource: memory.
|
kubectl get pod P -o jsonpath='{.status.conditions[?(@.type=="DisruptionTarget")]}' | Disruption reason condition | For the reason, see the table in “How it works” |
kubectl create --raw /api/v1/namespaces/NS/pods/P/eviction -f eviction.json | Call the Eviction API directly | Returns 429 TooManyRequests if the PDB does not allow it |
kubectl events -A --types=Warning | grep -Ei "evict|pressure" | Eviction and pressure events | kubelet events: Evicted, EvictionThresholdMet
|
kubectl delete pods -A --field-selector=status.phase=Failed | Clean up leftover Failed Pods | First 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)
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.
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.
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
--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", …}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.kubectl -n shop delete pod filler --ignore-not-found; kubectl -n shop delete deploy rel; kubectl -n shop delete pdb rel; rm -f eviction.jsonCase 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.
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.json429 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
- Node-pressure Eviction (signals, thresholds, ordering, oom_score_adj)
- API-initiated Eviction (200 / 429 / 500)
- Node Shutdowns (graceful / non-graceful)
- Disruptions (Pod disruption conditions)
- Reserve Compute Resources for System Daemons
- Related course: AKS hour 4 · Availability: PDBs, topology spread, and zone redundancy
Video storyboard script
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: when a node is running low on memory, kubelet sacrifices some Pods to keep the node itself alive.
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.
Narration: a PDB only constrains the eviction API. Node-pressure eviction, taint-based eviction, and OOM do not check it.
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.
Module 5 · Cluster Upgrades and Maintenance
- 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_apismetric, 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.
What: Version Skew Policy
| Component | Relative to kube-apiserver | Allowed when apiserver = 1.37 |
|---|---|---|
| kubelet, kube-proxy | Cannot 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-manager | Cannot be newer. Can be up to 1 minor older. | 1.37 / 1.36 |
| kubectl | ±1 minor | 1.38 / 1.37 / 1.36 |
| HA with multiple apiservers | No more than 1 minor apart from each other | Briefly 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 item | Method | 1.37 notes |
|---|---|---|
| Deprecated / removed APIs | kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis; pluto detect-all-in-cluster; kubent; the AKS portal highlights them | The k8s.io/deprecated annotation in audit logs identifies the callers
|
| kube-proxy mode | kubectl -n kube-system get cm kube-proxy -o yaml | grep mode | ipvs 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 DNS | kubectl -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 version | stat -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 usage | Search scripts for kubectl run … -f | Deprecated in 1.37 |
| Webhook and operator compatibility | Check the version matrix for admission webhooks, CRD controllers, and Ingress/Gateway controllers | A 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 drain | A single replica with minAvailable: 1 is the most common blocker |
| Capacity and quota | Surge needs extra VM and subnet IP quota | In overlay mode, Pods do not use VNet IPs, but nodes still do |
| AKS-specific | az aks get-upgrades; the "breaking changes" section of the AKS versions page | 1.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. |
| Backup | Velero 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
| Method | Best for | Risk |
|---|---|---|
| In-place rolling (surge; AKS default max-surge 1, production recommended 33%) | Most stateless workloads with PDBs | Gets stuck if PDBs are not satisfied; needs surge quota |
| max-unavailable (no surge; cordon and drain in place) | Insufficient quota or capacity | With 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 change | Double the cost for a short time |
| Blue-green cluster | Crossing multiple minors, or architecture refactoring | Requires traffic cutover and data migration. GitOps makes rebuilding easier. |
--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
AKS node pool rolling upgrade (surge)
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.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
kubectl version | Client/server version (check ±1) | — |
kubectl get nodes -o wide | kubelet version on each node | You will see mixed versions during the upgrade |
kubectl drain NODE | cordon + evict through the Eviction API | --ignore-daemonsets --delete-emptydir-data --timeout=10m. --disable-eviction bypasses PDBs (dangerous).
|
kubectl cordon / uncordon NODE | Disable / re-enable scheduling | — |
kubeadm upgrade plan / apply vX.Y.Z / node | Upgrade the control plane on a self-managed cluster | First 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 table | Available versions | — |
az aks upgrade --kubernetes-version V --control-plane-only | Upgrade the control plane only | Not available while the automatic upgrade channel is enabled |
az aks nodepool upgrade --kubernetes-version V | Upgrade 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 settings | drain-timeout defaults to 30 minutes (5 minutes to 24 hours) |
az aks update --auto-upgrade-channel stable | Cluster auto-upgrade channel | none (Standard default) / patch / stable / rapid / node-image (legacy, not recommended) |
az aks update --node-os-upgrade-channel NodeImage | Node OS image channel | None / Unmanaged / SecurityPatch / NodeImage (default for new Standard clusters) |
az aks maintenanceconfiguration add -n aksManagedAutoUpgradeSchedule … | Scheduled maintenance window | Node 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)
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.
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
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.
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: …
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).
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).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
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.
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
- Version Skew Policy
- Upgrading kubeadm clusters
- Deprecated API Migration Guide
- AKS control plane upgrade · Node pool rolling upgrade · Automatic upgrades · Node OS automatic upgrades · Supported versions
- This series: AKS hour 6 · Control plane and node pool upgrades · AKS hour 7 · Troubleshooting upgrade failures · hour 7 · EKS upgrades and operations
Video storyboard script
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: each Kubernetes version is supported for only about a year, so upgrading is not optional.
Narration: upgrade the control plane first. Nodes can lag by up to three minors, then catch up in batches.
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.
Narration: before upgrading, check deprecated APIs and the 1.37 deprecations, and make sure you have a backup first.
Module 6 · Control Plane Operations Overview: etcd snapshots and restore, certificate rotation
- 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 saveto back up andetcdutl snapshot statusto 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 upgraderenews certificates automatically, and that afterkubeadm certs renew allyou 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).
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.
| Tool | Purpose | Notes |
|---|---|---|
etcdctl | Network client for etcd: snapshot save, endpoint status/health, member list, alarm list | Requires TLS: --cacert, --cert, --key (in kubeadm, under /etc/kubernetes/pki/etcd/)
|
etcdutl | Local tool that works directly on data files: snapshot status, snapshot restore, defrag | etcdctl 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 method | Restore granularity | Applies to | Managed clusters |
|---|---|---|---|
| etcd snapshot | The 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 snapshots | Application migration, accidental namespace deletion, cross-cluster restore | Users 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)
- 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. - Verify:
etcdutl --write-out=table snapshot status snap.dboutputs HASH, REVISION, TOTAL KEYS, and TOTAL SIZE. - 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 theetcd-datavolume in/etc/kubernetes/manifests/etcd.yamlto point to the new directory. On kubeadm clusters, also syncetcd.local.dataDirinkubeadm-config, or the nextkubeadm upgradewill write back the old directory. Then restart the apiservers. Restarting kube-scheduler, kube-controller-manager, and kubelet is recommended to avoid stale caches. - 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
| Certificate | kubeadm default validity | How to renew |
|---|---|---|
| Cluster CA, etcd CA, front-proxy CA | 10 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 others | 1 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 year | kubeadm configured for automatic rotation (rotateCertificates: true)
|
| kubelet serving certificate | Self-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
| Platform | etcd | Certificates | What you still need to watch |
|---|---|---|---|
| AKS | Managed by the platform, not accessible | Cluster 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 |
| EKS | Managed by the platform | Control plane certificates are managed by AWS. Users access the cluster through IAM (access entries, hour 7). | Node AMI updates, backups |
| GKE | Managed by the platform | Control plane certificates are managed by Google. Credential rotation is supported, but it triggers a rebuild. | Maintenance windows, backups (Backup for GKE) |
Architecture diagram: etcd and control plane certificates
Flowchart: single control plane etcd restore
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
etcdctl … snapshot save FILE | Online snapshot | Low impact on members. Requires TLS parameters. |
etcdutl --write-out=table snapshot status FILE | Verify snapshot | Replaces the deprecated etcdctl snapshot status
|
etcdutl --data-dir DIR snapshot restore FILE | Restore to a new data directory | DIR is created. Replaces the deprecated etcdctl snapshot restore
|
etcdctl … endpoint status -w table / endpoint health / member list | Member status, DB size, leader | When the DB nears its quota, it triggers a NOSPACE alert (hour 8 has a full case study) |
kubeadm certs check-expiration | Check the expiry of all certificates | Columns: CERTIFICATE, EXPIRES, RESIDUAL TIME, CERTIFICATE AUTHORITY, EXTERNALLY MANAGED |
kubeadm certs renew all | Manually renew all leaf certificates | On multi-control-plane clusters, run this on each node. Then restart the static Pods. |
kubectl get csr, kubectl certificate approve CSR | Approve kubelet serving CSRs | signer kubernetes.io/kubelet-serving
|
openssl x509 -in CERT -noout -enddate | Expiry of any certificate | kubelet: /var/lib/kubelet/pki/kubelet-client-current.pem
|
az aks rotate-certs -g RG -n AKS | AKS rotates the CA and all child certificates | Rebuilds 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)
ops. Do not restore on lab. kind nodes are Docker containers, and the control plane runs as kubeadm static Pods, which suits a demo.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.
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
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
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.
kind delete cluster --name ops; kubectl config use-context kind-lab; docker exec lab-control-plane rm -f /var/lib/etcd/snap-lab.dbCase 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 -enddateAfter 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.
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
- Operating etcd clusters for Kubernetes (snapshots, etcdutl, restore steps)
- etcd Disaster recovery
- Certificate Management with kubeadm
- Manual Rotation of CA Certificates
- AKS certificate management and rotation overview · rotate-certs operation
Video storyboard script
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: all cluster state lives in etcd. If you can read etcd, you can read every Secret.
Narration: back up with etcdctl. Verify and restore with etcdutl. Encrypt snapshots and store them off-site.
Narration: before restoring, stop all API servers. Restore to a new directory, then point etcd to it.
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.
Module 7 · Production Differences on Managed Clusters: AKS / EKS / GKE Comparison
- 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.
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 management | AKS | EKS | GKE |
|---|---|---|---|
| Control plane managed; nodes self-managed or semi-managed | AKS Standard: you choose the node pool (VMSS) specs, scaling, and upgrade timing | Managed node groups / self-managed nodes / Fargate | GKE Standard: you configure the node pools |
| "Fully managed" modes | AKS Automatic: managed system node pool + NAP (Karpenter) + security baseline + upgrade channels, with the Standard tier and a Pod readiness SLA | EKS Auto Mode: AWS manages core components such as Karpenter, VPC CNI, load balancing, and EBS CSI, plus the node lifecycle | GKE Autopilot: Google manages the nodes, bills by Pod resource requests, and enforces a security baseline |
| Always your responsibility | Workload 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?
| Dimension | AKS | EKS (see hour 7 for details) | GKE |
|---|---|---|---|
| Control plane cost and SLA | Free (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 support | About 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 upgrades | Cluster 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 method | Rolling surge (max-surge / max-unavailable / soak), blue-green node pools | Rolling replacement of managed node groups; Karpenter / Auto Mode drift-based replacement | Surge rolling upgrades and blue-green node pool upgrades |
| Pod networking | Azure CNI Overlay (Pod IPs do not use the VNet) + Cilium dataplane; VNet mode is also available | VPC 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 access | Entra ID + Azure RBAC for Kubernetes (kubelogin); local accounts can be disabled | IAM + access entries (replacing the aws-auth ConfigMap) | Google Cloud IAM + Kubernetes RBAC |
| Pod access to cloud resources | Workload Identity (OIDC federation, hour 5) | EKS Pod Identity or IRSA | Workload Identity Federation for GKE |
| Node autoscaling | Cluster Autoscaler (node pools) or NAP (managed Karpenter) | Karpenter (self-installed) or Auto Mode (managed Karpenter); Cluster Autoscaler is also possible | Cluster autoscaler + node auto-provisioning; Autopilot does this automatically |
| Managed observability | Azure Monitor managed Prometheus + Managed Grafana + Container insights | Amazon Managed Prometheus / Grafana + CloudWatch Container Insights | Google Cloud Managed Service for Prometheus + Cloud Logging/Monitoring |
| Managed GitOps | Flux 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 module | AKS | EKS | GKE |
|---|---|---|---|
| M2 Node scaling | az aks nodepool update --enable-cluster-autoscaler / --node-provisioning-mode Auto | Karpenter NodePool + EC2NodeClass / Auto Mode | gcloud container clusters update --enable-autoscaling / Autopilot
|
| M3 Observability | --enable-azure-monitor-metrics | AMP managed collector / ADOT | Managed Service for Prometheus (managed collection is enabled by default; check the docs) |
| M4 Node pressure / shutdown | Custom node configuration (subset of kubelet parameters); Spot eviction | Node template / launch template; Spot interruption handling | Node system configuration; Spot VMs |
| M5 Upgrades | az aks upgrade, az aks nodepool upgrade --max-surge | eksctl upgrade cluster + node group update | Release channels + maintenance windows / exclusions |
| M6 Control plane | Managed by the platform; az aks rotate-certs | Managed by the platform | Managed 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.
Responsibility boundary comparison
Where Pod IPs come from
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.
Core command comparison (mostly read-only checks)
| Purpose | AKS (az) | EKS (aws / eksctl) | GKE (gcloud) |
|---|---|---|---|
| Available versions | az aks get-versions -l LOC -o table | aws eks describe-cluster-versions | gcloud container get-server-config --region R
|
| Get credentials | az aks get-credentials -g RG -n C + kubelogin convert-kubeconfig -l azurecli | aws eks update-kubeconfig --name C | gcloud container clusters get-credentials C --region R
|
| Cluster overview | az aks show -g RG -n C -o yaml | aws eks describe-cluster --name C | gcloud container clusters describe C --region R
|
| Upgradable versions | az aks get-upgrades -g RG -n C | eksctl upgrade cluster --name C (preview without --approve); cluster insights: aws eks list-insights | gcloud container get-server-config (view default and available versions by channel)
|
| 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
|
| Maintenance window | az 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)
| Check item | Production baseline | Current state |
|---|---|---|
| Control plane tier | Standard / Premium | (fill in) |
| Nodes spread across availability zones + system and user pools separated | Yes | |
| Pod networking | Overlay + Cilium (or VNet mode after IP planning) | |
| Human identity | Entra ID + Azure RBAC, local accounts disabled | |
| Workload identity | Workload Identity (no long-lived keys) | |
| API access | Private cluster / VNet integration / authorized IP ranges | |
| Upgrades | Channel + maintenance window + surge 33% (module 5) | |
| Observability | Managed Prometheus + alerts (module 3) | |
| Backup | Velero / AKS Backup (hour 4) |
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).
- A five-person startup team, all stateless services, already on Microsoft 365 / Entra ID.
- 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.
- 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.
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.
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 table2. 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
- AKS: Pricing tiers · AKS Automatic · Supported versions · AKS baseline reference architecture
- EKS: Version lifecycle · EKS Auto Mode · Pricing
- GKE: Release channels · Autopilot overview · Pricing · SLA
- This series: AKS 8-hour course · Hour 7 EKS
Video storyboard
This course page cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: All three manage the control plane, but the foundation, meaning your workload specs, is always your responsibility.
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.
Narration: Every platform has support windows and forced upgrades, and extended support always costs extra.
Narration: Fully managed modes reduce node operations, but nodes still get replaced. PDBs, probes, and requests still decide whether there is downtime.
Module 8 · Master Troubleshooting Decision Tree for Production Incidents
- 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.
What: six triage questions
- What is the blast radius? One Pod / one Deployment / one namespace / one node / one availability zone / the whole cluster / external access only?
- 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). - What do the signals say? Events (
kubectl events), status (describe), logs (logs --previous), metrics (Prometheus /top). - Which layer? Work from the outside in: DNS / certificates / load balancer → Gateway / Service → EndpointSlice → Pod → container → node → control plane → cloud resources.
- How do you mitigate? Roll back (
rollout undo/helm rollback/git revert), scale out, cordon the node, shift traffic, or pause GitOps auto-sync. - 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)
| Symptom | First command to run | Most common cause | See |
|---|---|---|---|
| kubectl can't connect / 401 / 403 | kubectl config current-context, kubectl cluster-info, kubectl auth can-i --list, kubectl get --raw /readyz?verbose | Wrong context, expired token (kubelogin), authorized IP ranges, missing RBAC | Hours 1 and 5; M7 (per-platform identity) |
| Pending | kubectl describe pod and check Events (FailedScheduling) | Insufficient resources, taints or affinity, unbound PVC, quota | Hours 2 and 4; M2 (node scaling) |
| ImagePullBackOff / ErrImagePull | kubectl describe pod | Tag does not exist, no permission on the private registry (AcrPull), Docker Hub rate limits, architecture mismatch | Hour 1; Docker course |
| CrashLoopBackOff | kubectl logs --previous, lastState.terminated | Configuration error, unreachable dependency, overly aggressive liveness probe, OOMKilled (137) | Hours 1 and 2; M3 |
| Running but not Ready | kubectl describe pod (Readiness probe failed) | Wrong probe path or port, dependency not ready | Hour 2 |
| CreateContainerConfigError | kubectl describe pod | Referenced ConfigMap, Secret, or key does not exist | Hour 2 |
| FailedCreate (ReplicaSet event) | kubectl describe rs, kubectl events --types=Warning | PSS rejection, quota exceeded, admission webhook rejection or timeout | Hour 5 |
| Service unreachable | kubectl get endpointslices -l kubernetes.io/service-name=X, netshoot to test DNS and ports | Selector mismatch, wrong targetPort, NetworkPolicy deny, DNS (ndots) | Hours 1 and 3 |
| External access fails | kubectl get gateway,httproute -A, describe to check the Accepted / ResolvedRefs conditions | parentRefs or hostname mismatch, missing certificate Secret, LB has no IP assigned, ReferenceGrant | Hour 3 |
| PVC Pending / FailedMount / Multi-Attach | kubectl describe pvc/pod, kubectl get volumeattachment | Wrong StorageClass, availability zone mismatch, RWO volume held by another node | Hour 4 |
| Forbidden | kubectl auth can-i VERB RES --as=… -n … | Missing Role or Binding, Azure RBAC scope, wrong SA | Hour 5 |
| HPA not scaling out | kubectl describe hpa | Missing requests, metrics-server failure, maxReplicas reached | M2 |
| Upgrade stuck | kubectl get pdb -A, AKS upgrade events | PDB cannot be satisfied, deprecated API, quota | M5 |
| Pod shows Evicted / Failed | kubectl get pod -o jsonpath='{.status.reason} {.status.message}', describe node Conditions | Node memory or disk pressure, emptyDir or ephemeral-storage limit exceeded, usage far above requests | M4 |
| Helm release failed / GitOps OutOfSync | helm history, argocd app diff | pending-* 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 status | Certificates expired because the cluster was not upgraded for a year, etcd space quota, member failure | M6 |
| Node NotReady | kubectl describe node (Conditions); on the node, journalctl -u kubelet, crictl ps | kubelet or containerd stopped, disk pressure, CNI not ready, expired certificates, VM failure | This 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).
| Condition | What True means | Common root causes | First check |
|---|---|---|---|
| Ready=False/Unknown | kubelet unhealthy or unreachable | kubelet crashed, containerd stopped, certificate expired, network partition, VM stopped | systemctl status kubelet containerd, journalctl -u kubelet
|
| DiskPressure | Free space on nodefs / imagefs below the eviction threshold | Container logs, accumulated images, emptyDir full | df -h /var/lib/containerd /var/log, crictl rmi --prune
|
| MemoryPressure | Available memory below threshold | Pods without limits, overcommitted node | kubectl top pods -A --sort-by=memory
|
| PIDPressure | PID count near the limit | Fork bomb, thread leak | ps -eLf | wc -l
|
| NetworkUnavailable | Node network not configured | CNI 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 minutes | Container runtime stuck or overloaded, node I/O saturation, too many containers | Is 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.
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
Incident response process
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.
“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
| Category | Command | Purpose |
|---|---|---|
| Cluster | kubectl get --raw '/readyz?verbose', kubectl get --raw '/livez?verbose' | Individual apiserver checks |
| Cluster | kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail -30 | Cluster-wide alert events |
| Nodes | kubectl describe node N | sed -n '/Conditions/,/Addresses/p' | Pressure and Ready reason |
| Nodes | kubectl get lease -n kube-node-lease | Whether heartbeats are updating |
| Nodes (AKS) | az aks nodepool show … --query provisioningState, az vmss list-instances | VM-level status |
| Inside the node | kubectl debug node/N -it --image=busybox:1.37 --profile=sysadmin → chroot /host | systemctl status kubelet containerd, journalctl -u kubelet -n 200, crictl ps -a, df -h
|
| Network | kubectl run tmp --rm -it --image=nicolaka/netshoot -- bash | dig, curl, nc, tcpdump (mind PSS) |
| Permissions | kubectl auth can-i --list --as=system:serviceaccount:shop:api -n shop | What the SA can do |
| Mitigate | kubectl rollout undo deploy/api, helm rollback, argocd app rollback, kubectl cordon N | Roll back / isolate |
| AKS diagnostics | Portal: “Diagnose and solve problems”; az aks command invoke; az aks show --query powerState | Platform-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.
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"}}}'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
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/apidocker 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 kubeletkubectl -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
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=FailedSignal: 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.
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
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:
Official docs
- Monitoring, Logging, and Debugging
- Troubleshooting Clusters
- Node status and heartbeats
- AKS troubleshooting docs
- Google SRE: Postmortem Culture
Video storyboard
This course page cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: When something fails, what matters most is not memorizing every command. It is having a fixed process.
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.
Narration: When a node isn't ready, check its status conditions first. Then go onto the node and read the kubelet and containerd logs.
Narration: Mitigate first, then find the root cause, and finally use a blameless review to turn what you learned into alerts, tests, and policies.
Hours 1–6 Command Cheat Sheet
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 shopPod 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=1Workloads 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=Failedetcd 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)
| Symptom | First action | Common causes |
|---|---|---|
| Pending | kubectl describe pod → FailedScheduling | Insufficient resources, taints, affinity, PVC, quota |
| ImagePullBackOff | describe pod events | Wrong tag, no AcrPull, rate limits, architecture |
| CrashLoopBackOff | logs --previous, exit code | Configuration, dependencies, OOM (137), liveness |
| Running but 0/1 Ready | describe pod probe events | readinessProbe path or port |
| Service unreachable | get endpointslices | selector, targetPort, NetworkPolicy |
| Gateway 404/503 | describe httproute conditions | parentRefs, hostname, backend port, ReferenceGrant |
| PVC Pending | describe pvc | StorageClass, WaitForFirstConsumer, availability zone |
| Forbidden | auth can-i … --as | RoleBinding, Azure RBAC scope |
| PodSecurity rejection | RS event FailedCreate | securityContext does not meet restricted |
| HPA <unknown> | describe hpa | Missing requests, metrics-server |
| GitOps stuck OutOfSync | argocd app diff | Controller modifies fields → ignoreDifferences |
| Upgrade stuck | get pdb -A | ALLOWED DISRUPTIONS = 0 |
| Pod Evicted | get pod -o jsonpath='{.status.message}' | Node memory or disk pressure, emptyDir or ephemeral storage limit exceeded |
| Node NotReady | describe node Conditions | kubelet / containerd, disk pressure, CNI, PLEG |
| x509 certificate expired (self-managed) | kubeadm certs check-expiration | Not 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
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).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.
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.
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.
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.
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 PSSkubectl -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)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).
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.
# 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 0kubectl -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
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
| Hour | One-line summary | Links |
|---|---|---|
| Hour 1 · Architecture and Core Objects | Kubernetes 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 Scheduling | requests 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 · Networking | Each 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 Applications | PVCs 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-Tenancy | Authentication → 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 Troubleshooting | Choose 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
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.
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.
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.
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.
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.
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).
Sources and versions
| Topic | Findings | Source (page date) |
|---|---|---|
| Kubernetes versions | Supports 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 changes | metrics.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 policy | kubelet/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 |
| HPA | Formula, 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 4 | Latest 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 support | 3.22 is the last feature release (2026-09). Security fixes continue until 2027-02-10. | Course standard (verified) · Helm 3 EOL |
| Kustomize | commonLabels is deprecated since v5.0.0; use labels. kustomize edit fix migrates automatically. | commonLabels reference |
| Argo CD / Flux | Argo 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-stack | KEDA 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 calendar | 1.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 tiers | Free (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 Automatic | Standard 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 upgrades | get-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-upgrade | Cluster 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 NAP | Based 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-versionsmay 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
etcdutlall 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-behaviorparameter, 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.