AKS Hour 7: Deep Troubleshooting and Advanced Topics

From "something broke" to finding the root cause: a layered troubleshooting methodology, AKS diagnostic tools, nodes, IPs, SNAT, ingress and DNS, upgrades, and identity, ending with a live mystery-box exercise
AKS · az CLI 2.7x+/2.8xkubectl debug nodeaz aks command invokeDiagnose and solve problemsVerified against Microsoft Learn troubleshooting docs · 2026-11-15
Overall learning goals
  • Master AKS layered troubleshooting: first identify the failing layer (ARM operations / control plane / node / Pod / network / identity), then choose the tool. Be fluent with Diagnose and solve problems, az aks show, the activity log, kubectl debug node, az aks command invoke (private clusters), and az vmss run-command invoke.
  • Read node heartbeats (the Lease renews every 10 seconds) and the cause chain behind NotReady. Know what AKS node auto-repair does, and when to reimage a node or replace a node pool.
  • Use the formula to work out subnet IP requirements: Azure CNI (flat) uses 1 + maxPods addresses per node, while Overlay uses only the node address. Be able to interpret InsufficientSubnetSize / SubnetIsFull and propose a migration plan.
  • Explain the real mechanics of SNAT port exhaustion (ports pre-allocated per node, the 5-tuple to the same destination IP:port, the 30-minute idle timeout). Use load balancer metrics to locate it, and fix it with connection reuse, more outbound IPs, explicit port allocation, or a NAT Gateway. Recognize outbound failures caused by UDRs or firewalls (OutboundConnFailVMExtensionError, exit code 50).
  • Trace failures along the request path through LoadBalancer Services, ingress, and DNS (EXTERNAL-IP pending, health probes, externalTrafficPolicy, CoreDNS, custom DNS, LocalDNS).
  • Handle upgrade failures: PDBs blocking eviction (Too Many Requests), QuotaExceeded, and SubnetIsFull. Use --undrainable-node-behavior Cordon, --drain-timeout, and --max-surge / --max-unavailable, and recover a failed state with a "same-version retry".
  • Troubleshoot identity failures: Entra authentication and Azure RBAC 403s, disabled local accounts, Workload Identity AADSTS70021, ACR pull 401 Unauthorized / 403 Forbidden, and use az aks check-acr.
  • Use a fault-injection script to reproduce 8 classes of faults in a lab cluster, then diagnose them under a time limit in the "mixed-fault mystery box".

1-hour timetable

#TimeModuleCore contentAnimation / interactiveLab (aks-lab)
0Before classEnvironment setup: fault-injection labReuse aks-lab, deploy myapp, download fault-inject.shEnvironment self-check listScript list / inject / restore
100–06Troubleshooting methodology and AKS diagnostic toolsLayer model, Diagnose and solve problems, activity log, kubectl debug node, command invoke, vmss run-command, Agentic CLI (preview)"Symptom → failing layer → tool" router (the real call chain of command invoke)Three ways into a node / private cluster
206–13Nodes NotReady and node pool failuresLease heartbeats, node-monitor-grace-period, the unreachable taint and 300-second eviction, node auto-repair, CSE error codes, PID / disk pressureNode heartbeat timeline simulatorStop kubelet to reproduce NotReady, then recover
313–21IP addresses and subnet exhaustionIP consumption under CNI flat vs Overlay vs dynamic Pod subnet, Azure reserves 5, surge and max-count are counted, InsufficientSubnetSize, migrating to a new subnetCore animation: subnet IP exhaustion calculatorCalculate and reproduce a failed scale-out (drill)
421–28Outbound connectivity: SNAT port exhaustion and UDR issuesPre-allocated port table, 5-tuple reuse, idle timeout, LB metrics, tcptracer to locate the Pod, NAT Gateway, UDR / firewall, exit code 50Core animation: SNAT port exhaustion simulatorCheck outbound rules and metrics, adjust ports
528–35Load balancers, ingress, and DNS failuresEXTERNAL-IP pending, health probes, externalTrafficPolicy, NSG, retirement of the application routing NGINX, CoreDNS / LocalDNS / custom DNSRequest path hop-by-hop tracer (can inject 6 kinds of faults)Selector errors, DNS failure reproduction
635–42Upgrade failures: PDB blocking, quotas, and evictionPre-upgrade checks, reading UpgradeFailed messages, Cordon isolation, force upgrade, quotas, same-version retrySurge upgrade + PDB eviction simulatorBlock a drain with a PDB, then recover
742–50Identity and permission failures: Entra, Workload Identity, ACR pullskubelogin / Azure RBAC 403, local accounts, AADSTS70021 / 90061, webhook labels, ACR 401/403, check-acrToken exchange failure injectorReproduce and fix ACR 401 and a Workload Identity subject mismatch
850–60Mixed-fault mystery boxRandom faults + timed diagnosis + root-cause selection + interactive troubleshooting treeFault mystery-box game + troubleshooting decision treeScript randomly injects 3 faults
—After classCheat sheet · Capstone lab"Monday 9 a.m." multi-fault drillFinal quiz, 12 questionsCapstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Identify the failing layer and choose the tool✓······✓az aks show, az monitor activity-log listM1 / mystery box
Access nodes and private clusters✓✓·✓···✓kubectl debug node, az aks command invokeM1 / M2
Node NotReady and CSE failures·✓·✓···✓describe node, journalctl -u kubeletM2
Subnet IP planning and exhaustion fixes··✓··✓·✓az network vnet subnet show, nodepool add --vnet-subnet-idM3
SNAT ports and the outbound path·✓·✓···✓az network lb outbound-rule list, --load-balancer-outbound-portsM4
LB / ingress / DNS failures····✓··✓get endpointslices, nslookup, CoreDNS logsM5
Upgrade failure recovery··✓··✓·✓get pdb, --undrainable-node-behavior, az vm list-usageM6
Identity and image pull failures······✓✓az aks check-acr, az identity federated-credential listM7

What this hour does not cover (and where to learn it)

TopicReasonWhere to learn it
General Pod-level troubleshooting (CrashLoopBackOff, OOMKilled, probes, Pending scheduling)This is general Kubernetes knowledge; this hour covers only the AKS-specific layersKubernetes 8 + 1 hour crash course (Hour 2 scheduling/resources; Hour 6 includes an AKS introduction: part6)
Network selection, outbound types, private cluster designThis hour only covers "how to troubleshoot when something breaks"AKS Hour 2: Networking
Setting up Entra integration, Workload Identity, and Key Vault CSISame as aboveAKS Hour 3: Identity and Security
Configuring upgrade policy, maintenance windows, Container Insights, and Managed PrometheusSame as aboveAKS Hour 6; for Prometheus details see Prometheus & Grafana Hour 3
Helm release failures, pipeline deployment failuresThese belong to delivery toolsHelm Hour 3 · GitHub Hour 3 · Azure DevOps Hour 3
50 production problems and interview questionsLength: too much for one hourAKS Hour 8 (optional)

How to use this course material

10 pages per module
Principles · diagrams · animation · commands · lab · production case · Troubleshooting · quiz · voice · video. For a troubleshooting hour, the suggested order is: first watch the "animation" to understand the mechanism, then do the "lab" and break the cluster by hand, then fix it.
Learning progress
A module counts toward progress when you score ≥ 70% on the quiz or click "Mark this module complete." Progress is saved in this browser (if local storage is disabled, refreshing clears it).
English voice
The "Voice" tab reads the narration aloud with the browser's built-in Web Speech API (en-US). If no English voice pack is installed, read the narration directly or pass it to a TTS tool.
Version and verification notes The error codes and error messages in this hour are taken verbatim from Microsoft Learn's AKS troubleshooting articles (verified 2026-11-15; see the sources page): SubnetIsFull, InsufficientSubnetSize, QuotaExceeded, UpgradeFailed caused by PDBs, OutboundConnFailVMExtensionError (50), ACR 401/403, and Workload Identity AADSTS70021/AADSTS90061. Azure keeps adjusting its wording. Messages marked "check against actual output" are examples compiled from the structure of the official docs and may differ slightly from what you see. Unless noted otherwise, all "expected output" is sample output and was not actually run when this course material was written.
Prerequisites We recommend completing ← Hour 6: Upgrades, Observability, and Day-to-Day Operations first. For Kubernetes basics, see Kubernetes 8 + 1 hour crash course.

Module 0 · Environment setup: fault-injection lab (complete before class)

Reuse aks-lab, deploy myapp, and download a fault script that can "inject / restore" faults. Troubleshooting labs have to run on a cluster you can break freely.
Before class ≈ 15 minutesrg-aks-lab · canadacentral · aks-labIncurs Azure costs
Prerequisites
  • An Azure subscription. You need access on the subscription or on rg-aks-lab, with the Owner role (or Contributor + User Access Administrator, for ACR role assignments and managed identities). The Module 7 Entra lab requires permission to read users and groups in the tenant.
  • On your machine: Azure CLI (2.79 or later recommended; --enable-force-upgrade requires 2.79+; if --undrainable-node-behavior reports an unknown parameter, upgrade or install aks-preview, check against actual output), kubectl, and kubelogin (az aks install-cli).
  • You have finished the first six hours: cluster aks-lab (Standard tier, Azure CNI Overlay, a 2-node system pool and a user pool userpool), ACR acraks<suffix> attached, and myapp (Flask + gunicorn, port 5000, /healthz) and Redis running in the myapp namespace.

Step 1: environment variables and cluster state

RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab
ACR=$(az acr list -g $RG --query "[0].name" -o tsv)   # acraks<suffix> created in Hour 1
az aks show -g $RG -n $CLUSTER --query "{state:provisioningState, power:powerState.code, k8s:currentKubernetesVersion, net:networkProfile.networkPlugin, mode:networkProfile.networkPluginMode, outbound:networkProfile.outboundType, nodeRG:nodeResourceGroup}" -o table
az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing
kubectl get nodes -o wide
kubectl -n myapp get deploy,svc,pod
State      Power    K8s     Net    Mode     Outbound      NodeRG
---------  -------  ------  -----  -------  ------------  ---------------------------------
Succeeded  Running  1.3x.y  azure  overlay  loadBalancer  MC_rg-aks-lab_aks-lab_canadacentral

NAME                                 STATUS   ROLES    AGE   VERSION
aks-nodepool1-12345678-vmss000000    Ready    <none>   3d    v1.3x.y
aks-nodepool1-12345678-vmss000001    Ready    <none>   3d    v1.3x.y
aks-userpool-87654321-vmss000000     Ready    <none>   2d    v1.3x.y

Step 2 (only if the cluster was deleted): rebuild a minimal lab cluster

If you deleted the resource group at the end of Hour 6, use the commands below to rebuild in about 10 minutes. Leaving the version empty uses the default version for the region (see az aks get-versions -l $LOC -o table).

az group create -n $RG -l $LOC
ACR=acraks$RANDOM
az acr create -g $RG -n $ACR --sku Basic
az aks create -g $RG -n $CLUSTER -l $LOC \
  --tier standard --node-count 2 --node-vm-size Standard_D4ds_v5 \
  --network-plugin azure --network-plugin-mode overlay --pod-cidr 192.168.0.0/16 \
  --enable-oidc-issuer --enable-workload-identity \
  --attach-acr $ACR --generate-ssh-keys
az aks nodepool add -g $RG --cluster-name $CLUSTER -n userpool --node-count 1 --node-vm-size Standard_D4ds_v5 --mode User
az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing

# myapp: build in ACR (the Dockerfile from the Docker course is in ./myapp)
az acr build -r $ACR -t myapp:1.0 ./myapp
kubectl create namespace myapp
kubectl -n myapp create deployment redis --image=redis:7-alpine --port=6379
kubectl -n myapp expose deployment redis --port=6379
kubectl -n myapp create deployment myapp --image=$ACR.azurecr.io/myapp:1.0 --replicas=3 --port=5000
kubectl -n myapp set env deploy/myapp REDIS_HOST=redis
kubectl -n myapp expose deployment myapp --port=80 --target-port=5000 --type=LoadBalancer
kubectl -n myapp rollout status deploy/myapp

Step 3: save the fault-injection script fault-inject.sh

The script only touches the myapp and fault-lab namespaces and a disposable lab node pool, and every fault has a matching restore. Run it only on the lab cluster: the script checks at startup that the current context name is aks-lab.

#!/usr/bin/env bash
# AKS Hour 7 fault-injection script. For the aks-lab lab cluster only.
# Usage: ./fault-inject.sh list | inject <id> | restore <id> | random [n] | restore-all
set -euo pipefail
RG=${RG:-rg-aks-lab}; CLUSTER=${CLUSTER:-aks-lab}; NS=myapp
STATE=${STATE:-$HOME/.aks-fault-state}
ctx=$(kubectl config current-context)
[[ "$ctx" == "$CLUSTER" ]] || { echo "Refusing to run: current context=$ctx, not $CLUSTER"; exit 1; }

declare -A DESC=(
  [f1]="Node NotReady: stop the kubelet on a userpool node"
  [f2]="Upgrade/drain blocked by PDB: minAvailable equals the replica count"
  [f3]="ACR pull 401: image points to an unauthorized repository name / wrong login server"
  [f4]="Service has no endpoints: wrong selector"
  [f5]="DNS failure: NetworkPolicy denies myapp egress on port 53"
  [f6]="Workload Identity: service account is missing the azure.workload.identity/use label"
  [f7]="Pending: requests exceed any node's allocatable"
  [f8]="CoreDNS custom config forwards contoso.internal to a server that doesn't exist"
)

inject() {
  case "$1" in
  f1) N=$(kubectl get nodes -l agentpool=userpool -o jsonpath='{.items[0].metadata.name}')
      echo "$N" > "$STATE.f1"
      kubectl debug node/$N -q --image=mcr.microsoft.com/azurelinux/busybox:1.36 --profile=sysadmin -- \
        chroot /host systemctl stop kubelet ;;
  f2) kubectl -n $NS apply -f - <<'EOF'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: myapp-pdb-strict }
spec:
  minAvailable: 3
  selector: { matchLabels: { app: myapp } }
EOF
  ;;
  f3) kubectl -n $NS set image deploy/myapp myapp=acrdoesnotexist$RANDOM.azurecr.io/myapp:1.0 ;;
  f4) kubectl -n $NS patch svc myapp -p '{"spec":{"selector":{"app":"my-app"}}}' ;;
  f5) kubectl -n $NS apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: deny-egress }
spec:
  podSelector: { matchLabels: { app: myapp } }
  policyTypes: [Egress]
  egress:
  - to: [ { podSelector: { matchLabels: { app: redis } } } ]
EOF
  ;;
  f6) kubectl create ns fault-lab --dry-run=client -o yaml | kubectl apply -f -
      kubectl -n fault-lab create sa wi-sa --dry-run=client -o yaml | kubectl apply -f -
      kubectl -n fault-lab annotate sa wi-sa azure.workload.identity/client-id=00000000-0000-0000-0000-000000000000 --overwrite
      kubectl -n fault-lab run wi-test --image=mcr.microsoft.com/azure-cli --overrides='{"spec":{"serviceAccountName":"wi-sa"}}' -- sleep 3600 ;;
  f7) kubectl -n $NS create deployment hog --image=mcr.microsoft.com/azurelinux/busybox:1.36 -- sleep 3600
      kubectl -n $NS set resources deploy/hog --requests=cpu=64,memory=256Gi ;;
  f8) kubectl -n kube-system apply -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata: { name: coredns-custom, namespace: kube-system }
data:
  contoso.server: |
    contoso.internal:53 {
      forward . 10.10.255.254
    }
EOF
      kubectl -n kube-system rollout restart deploy/coredns ;;
  *) echo "Unknown fault $1"; exit 1 ;;
  esac
  echo "Injected $1: ${DESC[$1]}"
}

restore() {
  case "$1" in
  f1) N=$(cat "$STATE.f1" 2>/dev/null || true)
      [[ -n "$N" ]] && kubectl debug node/$N -q --image=mcr.microsoft.com/azurelinux/busybox:1.36 --profile=sysadmin -- \
        chroot /host systemctl start kubelet || echo "If the node is unreachable: use az aks machine list to find the instance, then reimage or delete it" ;;
  f2) kubectl -n $NS delete pdb myapp-pdb-strict --ignore-not-found ;;
  f3) kubectl -n $NS rollout undo deploy/myapp ;;
  f4) kubectl -n $NS patch svc myapp -p '{"spec":{"selector":{"app":"myapp"}}}' ;;
  f5) kubectl -n $NS delete networkpolicy deny-egress --ignore-not-found ;;
  f6) kubectl delete ns fault-lab --ignore-not-found ;;
  f7) kubectl -n $NS delete deploy hog --ignore-not-found ;;
  f8) kubectl -n kube-system delete cm coredns-custom --ignore-not-found; kubectl -n kube-system rollout restart deploy/coredns ;;
  esac
  kubectl get pods -A --field-selector=status.phase=Succeeded -o name | grep node-debugger | xargs -r kubectl delete --wait=false
  echo "Restored $1"
}

case "${1:-list}" in
  list) for k in $(printf '%s\n' "${!DESC[@]}" | sort); do echo "$k  ${DESC[$k]}"; done ;;
  inject) inject "$2" ;;
  restore) restore "$2" ;;
  random) n=${2:-3}; picks=$(printf '%s\n' f2 f3 f4 f5 f6 f7 f8 | shuf -n "$n"); echo "$picks" > "$STATE.random"
          for p in $picks; do inject "$p" >/dev/null; done; echo "Randomly injected $n faults (the answers are in $STATE.random, so don't look yet)" ;;
  restore-all) for p in f1 f2 f3 f4 f5 f6 f7 f8; do restore "$p" || true; done ;;
  *) echo "Usage: $0 list|inject <id>|restore <id>|random [n]|restore-all" ;;
esac
chmod +x fault-inject.sh
./fault-inject.sh list
f1  Node NotReady: stop the kubelet on a userpool node
f2  Upgrade/drain blocked by PDB: minAvailable equals the replica count
f3  ACR pull 401: image points to an unauthorized repository name / wrong login server
f4  Service has no endpoints: wrong selector
f5  DNS failure: NetworkPolicy denies myapp egress on port 53
f6  Workload Identity: service account is missing the azure.workload.identity/use label
f7  Pending: requests exceed any node's allocatable
f8  CoreDNS custom config forwards contoso.internal to a server that doesn't exist
Note: f3 uses a registry name that does not exist. The real error is usually no such host or 401 (AKS first tries an anonymous pull for any name). It is there to practice "read the Events to identify the stage". The Module 7 lab reproduces the standard 401 Unauthorized with a real unauthorized ACR. f5 requires the cluster to have a network policy engine enabled (Azure / Cilium / Calico, Hour 2); if none is enabled, NetworkPolicy has no effect, which is itself a common "fault". SNAT exhaustion and subnet exhaustion are hard to reproduce safely in a lab cluster, so this hour uses animated simulators to explain the mechanism, and read-only commands to inspect the real configuration.
Cost and risk 2–3 Standard_D4ds_v5 nodes + the Standard-tier control plane + 1 Standard public IP, roughly US$0.5–0.8 per hour (canadacentral; check the official pricing page). kubectl debug node --profile=sysadmin creates a privileged Pod that can fully control the node. In production, restrict who can create such Pods with Azure RBAC / Kubernetes RBAC, and delete the node-debugger-* Pods when you are done. Cleanup after class: ./fault-inject.sh restore-all, then either az aks stop -g $RG -n $CLUSTER (keeps the cluster) or az group delete -n $RG --yes --no-wait (deletes everything).
Environment self-check list

Module 1 · Troubleshooting methodology and AKS diagnostic tools

00:00 – 06:00 · First decide "which layer is broken", then pick the right tool: ARM operations, control plane, nodes, Pods, network, identity
6 minutesDiagnose and solve problems · GAAgentic CLI for AKS · preview★★★★★
Learning goals
  • Use the "six-layer model" to map any symptom to one failing layer, and name the preferred tool for that layer.
  • Tell apart ARM / AKS RP operation failures (provisioningState: Failed, error codes in the activity log) from failures inside the cluster (Events, kubelet logs).
  • Know three ways to "get inside": kubectl debug node (needs the API to be reachable), az aks command invoke (private clusters, via ARM), and az vmss run-command invoke (when the API is unreachable or the node is NotReady).
Prerequisites: kubectl describe / events; in Hour 1, the ARM → AKS RP → MC_ resource group chain. Importance: ★★★★★

What: the six-layer model for AKS troubleshooting

AKS is "a managed control plane + nodes (VMSS) in your subscription". A fault can come from the Azure resource management layer or from inside Kubernetes. Decide the layer first, then gather evidence:

LayerTypical symptomWhere the evidence isPreferred tool
① ARM / AKS RP operationsaz aks upgrade/scale fails, and the cluster is FailedThe Code: returned by the operation, the activity logaz aks show --query provisioningState, az monitor activity-log list, Diagnose and solve problems
② Control planekubectl timeouts, 429s, webhook rejectionsControl plane diagnostic logs (kube-apiserver, kube-audit)Diagnostic settings → Log Analytics (Hour 6), Diagnose and solve problems "Cluster and Control Plane Availability"-type checks
③ NodesNotReady, CSE failures, disk/PID pressureNode conditions, kubelet / containerd logs, VMSS instance statekubectl describe node, kubectl debug node, az vmss run-command invoke
④ Pods / workloadsPending, CrashLoop, ImagePullBackOffEvents, container logskubectl describe pod, kubectl logs --previous
⑤ NetworkTimeouts, DNS failures, EXTERNAL-IP pending, SNATEndpointSlices, CoreDNS logs, LB metrics, NSG/UDRkubectl get endpointslices, Network Watcher, LB Metrics
⑥ Identity401/403, AADSTS errorsAADSTS codes in Pod logs, role assignmentsaz role assignment list, az aks check-acr

Why: why decide the layer first

The same symptom can come from different layers. For example, "the Pod can't pull an image" may be identity (401), network (i/o timeout, 403 from a firewall), or the image name (not found). Without deciding the layer, you waste time in the wrong place. Another AKS trait is the managed boundary: you can't log in to the control plane, and you shouldn't change resources in the MC_ resource group directly (AKS overwrites them on the next reconcile, or leaves the cluster in an unsupported state), so the toolchain is different from a self-managed Kubernetes cluster.

How: the toolbox and the call chains

  • Diagnose and solve problems (portal → cluster → Diagnose and solve problems): built-in self-diagnosis with no extra configuration and no extra charge. Each category tile (such as Connectivity Issues, Best Practices) runs a set of detectors, and results include a problem summary, error details, recommended actions, documentation links, and related metrics and logs. It proactively finds issues such as undersized subnets (InsufficientSubnetSize), SNAT failures, and node IOPS throttling.
  • kubectl debug node/NODE -it --image=mcr.microsoft.com/azurelinux/busybox:1.36: creates a privileged debug Pod on the node (node-debugger-*). The node's root filesystem is mounted at /host, and after chroot /host you can run journalctl -u kubelet and crictl. Prerequisites: the API server is reachable, and the node can schedule the Pod and pull images.
  • az aks command invoke: runs kubectl/helm inside the cluster through the Azure API, so you don't need a VPN to reach a private cluster. Permissions: Microsoft.ContainerService/managedClusters/runcommand/action and .../commandResults/read. It starts a command Pod in the cluster (requests 200m/500Mi, limits 500m/1Gi). The ARM timeout is 60 seconds, and the output limit is 512 kB. The "Run command" option in the portal is the same feature, and it can be turned off with apiServerAccessProfile.disableRunCommand=true.
  • az vmss run-command invoke --command-id RunShellScript: goes through the VM agent (the Azure platform channel) and does not depend on the Kubernetes API. Most reliable when the node is NotReady, the API is unreachable, or kubelet is down.
  • az aks machine list: gets node private IPs from the AKS agent pool API (no Kubernetes API needed), used together with Bastion SSH.
  • Agentic CLI for AKS (az extension add --name aks-agent, command az aks agent, preview): natural-language troubleshooting using your own LLM deployment, with an optional client mode (Docker) or cluster mode (requires Workload Identity). Useful as an assistant, but verify the conclusions with the commands in this hour.

When: which tool to use when

SituationAPI reachable?Preferred
Public cluster, node Ready, need to look inside the nodeYeskubectl debug node
Private cluster, you are not inside the VNetNo (for you)az aks command invoke
Node NotReady / kubelet stopped / outbound blockedNot applicable to that nodeaz vmss run-command invoke
Operation failed (upgrade, scale, create)Not relevantError code → matching Microsoft Learn article → Diagnose and solve problems
Common misconceptions ① "Just change the LB / VMSS in the MC_ resource group." This is not supported: changes such as outbound rules are overwritten by reconciliation when the cluster is stopped, started, upgraded, or scaled. ② "If the cluster is Failed, rebuild it." In most cases, after you fix the root cause, run az aks upgrade to the same version again, or an empty az aks update, to trigger reconciliation and return to Succeeded. ③ "command invoke can replace a VPN for automation." The docs explicitly say it is not meant for programmatic access, and it has a 60-second scheduling timeout and a 512 kB output limit.

Architecture diagram: the three "entry" paths use different channels

Your terminalaz / kubectl ARMmanagement.azure.com AKS RPruncommand/action kube-apiserver(managed control plane) Node VMSS instances node-debugger Pod command-* Pod VM Agent (waagent) ① kubectl debug node (requires API reachability) ② ② command invoke ③ az vmss run-command (Compute RP → VM agent, bypasses Kubernetes)
Figure 1-1: ① depends on the Kubernetes API; ② runs a Pod in the cluster via ARM / AKS RP (works for private clusters); ③ reaches the VM directly through the Compute platform, and still works when the node is NotReady

Flowchart: layered troubleshooting decision flow

SymptomWho, when, scope Operation error / Failed?→ Layer ①: error code Does kubectl work?No → Layer ② / network / identity Affects all or some?All → most recent change Nodes Ready?No → Layer ③ (Module 2) What do the Pod Events say?Layer ④ / 401 → ⑥ / timeout → ⑤ Trace the request path hop by hopLayer ⑤ (Modules 4, 5) Fix → verify → preventFix the root cause, don't just restartReconcile with a same-version upgrade or az aks updateAdd alerts, write a runbook
Figure 1-2: first ask three questions: Did an Azure operation fail? Does kubectl still work? Does it affect all nodes or some?

Interactive router: from symptom to tool (with real call chains)

Select a symptom, then step through it. Each step shows the basis for that layer's judgment, the real command you should run, and the components inside Azure / Kubernetes that the command actually passes through.

Select a symptom above first.
$ # waiting for symptom selection

Core commands and parameters

CommandPurposeKey parameters / notes
az aks showprovisioningState / powerState of the cluster and node pools--query "{s:provisioningState,p:powerState.code}"
az aks nodepool listState, version, and count for each pool-o table
az monitor activity-log listWho did what and when, and the failure code--resource-group, --offset 24h, --status Failed
kubectl get events -A --sort-by=.lastTimestampCluster event timeline--field-selector type=Warning
kubectl debug node/NPrivileged debug Pod on a node-it --image=mcr.microsoft.com/azurelinux/busybox:1.36, --profile=sysadmin
az aks command invokeRun kubectl / helm on a private cluster--command, --file (can be repeated)
az vmss run-command invokeRun a script on a node without going through Kubernetes--command-id RunShellScript --instance-id N --scripts
az aks machine listGet node private IPs from the AKS API--nodepool-name
# 1) Layer ①: cluster and node pool state, and recent failed operations
az aks show -g $RG -n $CLUSTER --query "{state:provisioningState, power:powerState.code}" -o table
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{pool:name,state:provisioningState,ver:currentOrchestratorVersion,count:count}" -o table
az monitor activity-log list -g $RG --offset 24h --status Failed \
  --query "[].{time:eventTimestamp, op:operationName.localizedValue, status:status.value, msg:properties.statusMessage}" -o table
State      Power
---------  -------
Succeeded  Running
Pool       State      Ver     Count
---------  ---------  ------  -------
nodepool1  Succeeded  1.3x.y  2
userpool   Succeeded  1.3x.y  1

How to verify: if both show Succeeded / Running, the ARM layer is healthy and the problem is inside the cluster. Common mistake: the statusMessage in the activity log is a JSON string. For complex cases, add -o json and parse it with jq. Production use: connect alerts on failed AKS operations in the activity log to your on-call system.

# 2) Layer ③: get into a node
kubectl debug node/aks-nodepool1-12345678-vmss000000 -it --image=mcr.microsoft.com/azurelinux/busybox:1.36
# Once inside:
chroot /host
journalctl -u kubelet --since "15 min ago" --no-pager | tail -50
crictl ps -a | head
exit; exit
kubectl get pod -o name | grep node-debugger | xargs kubectl delete
Creating debugging pod node-debugger-aks-nodepool1-12345678-vmss000000-bkmmx with container debugger on node aks-nodepool1-12345678-vmss000000.
If you don't see a command prompt, try pressing enter.
root@aks-nodepool1-12345678-vmss000000:/#
# 3) Private cluster: command invoke (single command / with files)
az aks command invoke -g $RG -n $CLUSTER --command "kubectl get pods -n kube-system"
az aks command invoke -g $RG -n $CLUSTER --command "kubectl apply -f pdb.yaml -n myapp" --file pdb.yaml
command started at 2026-11-15 09:12:03+00:00, finished at 2026-11-15 09:12:05+00:00 with exitcode=0
NAME                                  READY   STATUS    RESTARTS   AGE
coredns-6f8b9c7d4-2kq8w               1/1     Running   0          3d
...
# 4) API unreachable / node NotReady: go directly through the VMSS platform channel
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
VMSS=$(az vmss list -g $NODE_RG --query "[?contains(name,'userpool')].name" -o tsv)
az vmss list-instances -g $NODE_RG -n $VMSS --query "[].{id:instanceId,name:osProfile.computerName,state:provisioningState}" -o table
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript \
  --scripts "systemctl is-active kubelet containerd; journalctl -u kubelet -n 30 --no-pager" --query "value[0].message" -o tsv

Common mistake: run-command can run only one command per instance at a time; if the previous one has not finished, you get a conflict error (check against actual output). It does not work on instances that are Deallocated. Production use: when outbound access is blocked by a firewall, you can still run curl -v https://mcr.microsoft.com/v2/ on the node.

Lab 1: three ways into the same node (about 6 minutes)

Portal diagnosis: open the portal → aks-lab → Diagnose and solve problems, type "node" in the search box, run a node health detector, and note the recommended actions it gives. (Read-only, no charge)
kubectl debug node:
N=$(kubectl get nodes -l agentpool=userpool -o jsonpath='{.items[0].metadata.name}')
kubectl debug node/$N -it --image=mcr.microsoft.com/azurelinux/busybox:1.36 -- chroot /host sh -c 'hostname; systemctl is-active kubelet; cat /etc/os-release | head -2'
aks-userpool-87654321-vmss000000
active
NAME="Ubuntu"
VERSION="24.04 LTS (Noble Numbat)"

The node OS depends on your --os-sku (Ubuntu / AzureLinux); check against actual output.

command invoke: you can use it even on a public cluster, to experience the ARM channel:
az aks command invoke -g $RG -n $CLUSTER --command "kubectl get nodes -o wide && kubectl get pods -A | grep command"

Check the namespace where the command Pod runs in the output (usually aks-command; check against actual output).

vmss run-command:
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
VMSS=$(az vmss list -g $NODE_RG --query "[?contains(name,'userpool')].name" -o tsv)
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript \
  --scripts "curl -sS -o /dev/null -w '%{http_code}\n' https://mcr.microsoft.com/v2/" --query "value[0].message" -o tsv
Enable succeeded:
[stdout]
200
[stderr]
Cleanup:
kubectl get pod -o name | grep node-debugger | xargs -r kubectl delete

Cost: read-only operations have no extra charge; nodes are billed by the hour. Permissions: command invoke needs the two RBAC actions above (whether the Azure Kubernetes Service Cluster User/Admin role includes them, check the role definition).

Case 1: all nodes NotReady on Monday morning

Problem: all nodes went NotReady at the same time, but kubectl could still reach the API. Approach: when "everything breaks at once", first suspect a recent platform change. The activity log showed the network team had changed the route table associated with the node subnet on Sunday night. curl to the API server FQDN from a node via az vmss run-command timed out. Configuration: restore the UDR route to the firewall, and allow AKS's required FQDNs on the firewall. Limitation: after the network is fixed, nodes usually recover automatically; if they do not, restart or reimage the nodes.

Case 2: on-call engineer at home cannot run kubectl on a private cluster

Problem: an alert at night, and the on-call person is not on the company network. Approach: grant the on-call group a custom role containing only runcommand/action and commandResults/read, and run read-only diagnostics with az aks command invoke. Limitation: the command Pod must be schedulable (if all nodes are full, it times out after 60 seconds); output is capped at 512 kB, so pipe large logs through | tail; not suitable for automation.

Case 3: the cluster stuck in Failed after an upgrade

Problem: az aks upgrade failed, and the portal shows Failed. Approach: read the error code (PDB → Module 6; SubnetIsFull → Module 3; QuotaExceeded → Module 6), fix the root cause, then run az aks upgrade again to the same version. The CLI prints "Cluster currently in failed state. Proceeding with upgrade to existing version … to attempt resolution of failed cluster state." Limitation: do not delete the VMSS in the MC_ resource group to "reset" it.

Common errors and fixes

error: unable to upgrade connection: container not found / kubectl debug stuck in Pending

Cause: the debug Pod was not scheduled, or its image cannot be pulled (restricted node outbound, node NotReady, or node taints).

kubectl get pod -o wide | grep node-debugger
kubectl describe pod node-debugger-...

Fix: if outbound is restricted, use an image already cached on the node or one you can get from your ACR; if the node is NotReady, go directly to az vmss run-command invoke.

(AuthorizationFailed) The client '...' does not have authorization to perform action 'Microsoft.ContainerService/managedClusters/runcommand/action'

Cause: the caller lacks the RBAC actions required by command invoke (the exact message format, check against actual output).

az role assignment list --assignee $(az ad signed-in-user show --query id -o tsv) --scope $(az aks show -g $RG -n $CLUSTER --query id -o tsv) -o table

Fix: assign a role that includes runcommand/action and commandResults/read. Note that command invoke still accesses the cluster as your identity, so Kubernetes and Azure RBAC authorization still apply.

command invoke returns a timeout; the command Pod cannot be scheduled within 60 seconds

Cause: insufficient node resources (the command Pod requests 200m CPU / 500Mi memory), or all nodes have taints.

Fix: temporarily scale the node pool (az aks nodepool scale) or free up resources; if the system pool allows only CriticalAddonsOnly, confirm there is a user pool with schedulable capacity.

Diagnose and solve problems finds nothing, but the problem persists

Cause: the detectors cover common platform issues; application-level problems (misconfiguration, code bugs) are out of scope.

Fix: go back to the layered method: Events → logs → hop-by-hop network tests. Also check recent deployment and configuration changes (GitOps commits, Helm history).

Command-line exercises
1. List all failed Azure operations in rg-aks-lab in the past 24 hours.
az monitor activity-log list -g rg-aks-lab --offset 24h --status Failed -o table
2. Run kubectl get nodes against the private cluster aks-lab, but you are not inside the VNet.
az aks command invoke -g rg-aks-lab -n aks-lab --command "kubectl get nodes"
Scenario analysis
Node aks-userpool-…000000 is NotReady, and the Pod created by kubectl debug node stays Pending. What do you do next?

A NotReady node does not accept new Pods, so kubectl debug node will not work. Switch to az vmss run-command invoke (the Compute platform channel) to check systemctl is-active kubelet containerd, the kubelet logs, and connectivity to the API server and MCR. Also check the node-related detectors in Diagnose and solve problems, and whether the activity log shows platform maintenance events.

Verified teaching videos

▶
Diagnose & Solve with Andrew Scobie: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
AKS official channel · English · one of the AKS Troubleshooting Series, explaining how to use Diagnose and solve problems
▶
How to troubleshoot common issues with AKS Diagnostics — Microsoft Azure
English · about 7 minutes · recorded earlier; the portal UI may have changed
▶
AKS MCP Server with Julia Yin: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · AI-assisted troubleshooting (MCP Server / Agentic CLI direction; for preview features, follow the docs)

Official documentation

Video storyboard (about 90 seconds)

This course material cannot generate video or MP3 directly. A storyboard and narration script are provided so you can hand them to a video tool.

Shot 1 · 0–20s
Visual: stacked building blocks labeled ARM, control plane, nodes, Pods, network, identity; a red alert bubble drops onto them.
Narration: the first step in troubleshooting is not to restart. It is to work out which layer is broken.
Shot 2 · 20–45s
Visual: three colored channels leave the terminal: one goes straight to the API server, one goes through ARM and the AKS resource provider, and one goes through the Compute platform directly to the VM.
Narration: kubectl debug depends on the Kubernetes API. command invoke goes through the Azure management channel and suits private clusters. vmss run-command goes straight to the VM, so it still works when the node is down.
Shot 3 · 45–70s
Visual: the portal's Diagnose and solve problems page; a click on the Connectivity tile shows result cards for SNAT and DNS.
Narration: the portal's diagnose and solve problems feature has no extra charge, and it proactively finds platform issues such as undersized subnets and SNAT failures.
Shot 4 · 70–90s
Visual: the error code UpgradeFailed is enlarged, with the same-version retry command beside it.
Narration: when an operation fails, read the error code, fix the root cause, then retry with the same version so AKS reconciles back to a successful state.
or score ≥ 70% on the quiz

Module 2 · Nodes NotReady and node pool failures

06:00 – 13:00 · kubelet stops renewing the Lease → controller marks the node Unknown → taint → eviction → AKS auto-repair: every step has a time constant
7 minutesNode auto-repair · on by default★★★★★
Learning goals
  • Explain the two kinds of node heartbeat (.status and the Lease in kube-node-lease) and the timeline from heartbeat loss to Pod eviction.
  • Know the trigger conditions for AKS node auto-repair (NotReady on consecutive checks within a 10-minute window, or no status reports for 10 minutes; unhealthy for at least 5 minutes) and the action order (reboot → reimage → redeploy for Linux nodes only; up to 3 rounds, lasting up to 1 hour).
  • Tell apart the four root-cause groups of NotReady: network/outbound changes, kubelet/containerd processes, resource pressure (disk, PID, memory, IOPS), and VM platform events; read CSE exit codes (50/51/52).
Prerequisites: the three ways into a node from Module 1. Importance: ★★★★★

What: what NotReady really means

Ready is a node condition written by the kubelet. The kubelet maintains two heartbeats: ① it updates the .status of the Node object (when the status changes, or by default once every 5 minutes); ② it renews, every 10 seconds, the Lease with the same name in the kube-node-lease namespace (on failure, it backs off exponentially, starting at 200 milliseconds and capped at 7 seconds). The node lifecycle controller in the control plane notices when a Lease has not been updated for longer than node-monitor-grace-period (the Microsoft docs give 40 seconds as the default; newer upstream versions changed it to 50 seconds; check against actual output for the value AKS's managed control plane uses), and sets Ready to Unknown. When the kubelet reports a problem itself (such as the container runtime being unavailable, PLEG being unhealthy, or the network plugin not being ready), Ready is False.

Why: the chain of consequences

  • The controller adds the taint node.kubernetes.io/unreachable:NoExecute (Unknown) or node.kubernetes.io/not-ready:NoExecute (False), so new Pods are no longer scheduled to the node.
  • The DefaultTolerationSeconds admission plugin adds a default toleration of 300 seconds for both taints to every Pod, so after about 5 minutes the Pods are evicted and recreated on other nodes (StatefulSet Pods are not recreated elsewhere automatically until the old Pod is confirmed deleted).
  • The Pods on this node are marked not ready in the Endpoints, and Service traffic shifts away. If all replicas were on this node, the service goes down.

How: AKS node auto-repair

AKS marks a node unhealthy when every check in a 10-minute window is NotReady, or when no status is reported for 10 minutes. After the node has been unhealthy for at least 5 minutes, the user aks-remediator runs these in order: reboot → reimage → redeploy (Linux only), retrying up to 3 rounds; the whole process can take up to 1 hour. Events from aks-auto-repair appear on the node: NodeRebootStart/End, NodeReimageStart/End, NodeRedeployStart/End, and on failure NodeRebootError and similar.

Cases where auto-repair does not run: a network misconfiguration prevents the node from reporting status; the node never registered successfully; the node has the node.cloudprovider.kubernetes.io/shutdown or ToBeDeletedByClusterAutoscaler taint; the node is being upgraded (has the scale-down-disabled annotation). In other words, auto-repair cannot fix a global network problem such as outbound traffic blocked by a firewall.

When: the four root-cause groups and the first command

Root-cause groupTypical evidenceFirst command
Network / outbound change (all nodes break at once)kubelet logs show API server timeouts; recent changes to UDR, NSG, DNS, or the firewallaz monitor activity-log list + curl -v https://<API FQDN>:443 via vmss run-command
kubelet / containerd processcontainer runtime is down, PLEG is not healthy (check against actual output)journalctl -u kubelet -u containerd
Resource pressureDiskPressure, PIDPressure, MemoryPressure; pthread_create failed: Resource temporarily unavailable; OS disk IOPS throttlingkubectl describe node, the node performance detectors in Diagnose and solve problems
VM platform eventsVMSS instance Stopped/Deallocated, platform maintenance, Spot evictionaz vmss list-instances, the activity log, Resource Health

CSE (Custom Script Extension) errors when a node is created or joins

New nodes (scale-out, surge upgrade, automatic repair via redeploy) run the bootstrap script through CSE at startup. If it fails, the operation reports a VMExtensionProvisioningError-type error with an exit code. The most common one is exit code 50 = OutboundConnFailVMExtensionError: the CSE run of curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/ fails because outbound access is blocked (see Module 4). Other codes include 51 (cannot connect to the API server) and 52 (API server domain name resolution failure). For exact names and meanings, refer to the error code page on Microsoft Learn.

Comparison with similar technologies

AKSEKSSelf-managed kubeadm
Node auto-repairOn by default: reboot → reimage → redeployManaged node group node auto repair (must be enabled)None. You must build it yourself (for example, Node Problem Detector plus custom remediation)
Enter the nodekubectl debug / vmss run-command / BastionSSM Session ManagerSSH
Common misconceptions ① “Pods move away immediately when a node goes NotReady.” By default, they wait about 5 minutes (a 300-second toleration). ② “Auto-repair fixes everything.” It does not fix cluster-wide network problems, registration failures, or nodes that are being upgraded. Auto-repair is best effort. ③ “SSH in and change the configuration.” AKS does not support customizing nodes directly (such as updating packages or changing network settings). Those changes are lost on the next reimage or upgrade. Use node pool settings (--kubelet-config, --linux-os-config) or a new node pool instead.

Timeline: from kubelet stopping to Pod recreation

0skubelet stops ~40–50sReady=Unknownunreachable taint ~5 minutestolerationSeconds 300 expiresPod evicted → recreated elsewhere Unhealthy for ≥5 minutesaks-remediatorNodeRebootStart Up to ~1 hourreimage → redeployUp to 3 rounds kubelet → Lease renewed every 10skube-node-lease/<node> node lifecycle controller (control plane)Compare renewTime with the grace period AKS node auto-repair (platform)Event source aks-auto-repair Note: the actual grace period value is determined by AKS. A StatefulSet Pod is recreated only after the old Pod is confirmed deleted.
Figure 2-1: The cascade after heartbeats stop. Kubernetes eviction and AKS platform repair run as two parallel timelines.

Structure diagram: four root-cause categories for NotReady

Node NotReady Network / outboundUDR, NSG, firewall, custom DNSOften breaks all nodes at once Processkubelet / containerd stopped or crashedCertificates, configuration, OOM Resource pressureDisk, PIDs (threads), memory, IOPSOften affects individual nodes and can recur VM platformStop/deallocate, maintenance, Spot evictionCheck VMSS instances and Resource Health
Figure 2-2: Check the impact scope first. All nodes → network or platform change. Individual nodes → process or resource problem.

Node heartbeat timeline simulator

Choose a failure and press play. Time advances in accelerated seconds. Watch how the Lease renewTime, Ready condition, taints, Pod status, and AKS auto-repair events change in sequence. The log on the right shows the command output you would see on a real cluster.

Node aks-userpool-…000000
Lease renewTime: just now
Ready: True
Taints: <none>
Other nodes
auto-repair: idle
t = 0s
Ready: the node is healthy, and 2 of the 3 myapp Pods are running on it.
$ kubectl get nodes

Core commands and parameters

CommandPurposeKey parameters / notes
kubectl describe node NConditions, Taints, Allocated, EventsCheck the reason/message of Ready
kubectl get lease -n kube-node-leaseHeartbeat renewal time-o custom-columns=NAME:.metadata.name,RENEW:.spec.renewTime
kubectl get events --field-selector source=aks-auto-repairAuto-repair eventsor --field-selector involvedObject.kind=Node
journalctl -u kubelet -u containerdNode process logs (on the node)--since, -n
az vmss list-instances / get-instance-viewVM-level status--instance-id
az vmss restart / reimageManually restart / reimage the node--instance-ids
az aks nodepool delete-machinesDelete a specific node (the pool refills or scales in to match its count)--machine-names
kubectl get nodes
kubectl describe node aks-userpool-87654321-vmss000000 | sed -n '/Conditions:/,/Addresses:/p'
kubectl get lease -n kube-node-lease -o custom-columns=NAME:.metadata.name,RENEW:.spec.renewTime
NAME                                STATUS     ROLES    AGE   VERSION
aks-nodepool1-12345678-vmss000000   Ready      <none>   3d    v1.3x.y
aks-userpool-87654321-vmss000000    NotReady   <none>   2d    v1.3x.y
Conditions:
  Type             Status    Reason              Message
  ----             ------    ------              -------
  MemoryPressure   Unknown   NodeStatusUnknown   Kubelet stopped posting node status.
  DiskPressure     Unknown   NodeStatusUnknown   Kubelet stopped posting node status.
  PIDPressure      Unknown   NodeStatusUnknown   Kubelet stopped posting node status.
  Ready            Unknown   NodeStatusUnknown   Kubelet stopped posting node status.
NAME                                RENEW
aks-userpool-87654321-vmss000000    2026-11-15T09:20:11.123456Z   ← no longer updating

How to verify: “Kubelet stopped posting node status.” means the controller marks the status as Unknown because the kubelet has stopped reporting. Status=False with a specific message means the kubelet itself reported a problem. Common mistakes: checking only get nodes and not the conditions, or reading an Unknown MemoryPressure as a memory problem.

# When the node is unreachable: check processes and connectivity through the platform channel
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
VMSS=$(az vmss list -g $NODE_RG --query "[?contains(name,'userpool')].name" -o tsv)
FQDN=$(az aks show -g $RG -n $CLUSTER --query fqdn -o tsv)
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript --scripts \
 "systemctl is-active kubelet containerd; df -h / /var/lib/containerd | tail -2; cat /proc/sys/kernel/pid_max; ps -eLf | wc -l; curl -sk -o /dev/null -w 'api:%{http_code}\n' https://$FQDN:443/healthz" \
 --query "value[0].message" -o tsv
# Auto-repair events
kubectl get events -A --field-selector involvedObject.kind=Node --sort-by=.lastTimestamp | grep -Ei 'reboot|reimage|redeploy'
[stdout]
inactive
active
/dev/sda1   124G   38G   86G  31% /
...
api:401        ← The API is reachable (401 without authentication is expected). The problem is in the kubelet process.
NodeRebootStart  Node auto-repair is initiating a reboot action due to NotReady status persisting for more than five minutes.
# Manual actions (outside auto-repair)
az vmss restart -g $NODE_RG -n $VMSS --instance-ids 0
az vmss reimage -g $NODE_RG -n $VMSS --instance-ids 0
az aks nodepool delete-machines -g $RG --cluster-name $CLUSTER --name userpool --machine-names aks-userpool-87654321-vmss000000

Production use: Restart and reimage are mitigation steps. Record evidence first (logs and timestamps), then run them. For node pools that keep failing, replace them with a new node pool (az aks nodepool add + cordon/drain the old pool).

Lab 2: Stop kubelet, observe NotReady and recovery (about 8 minutes)

Get myapp scheduled onto userpool:
kubectl -n myapp scale deploy/myapp --replicas=4
kubectl -n myapp get pod -o wide
Inject fault f1:
./fault-inject.sh inject f1
watch -n5 'kubectl get nodes; kubectl get lease -n kube-node-lease -o custom-columns=N:.metadata.name,R:.spec.renewTime | grep userpool'
aks-userpool-87654321-vmss000000    NotReady   <none>   2d    v1.3x.y
Check taints and Pod tolerations:
kubectl get node -l agentpool=userpool -o jsonpath='{.items[0].spec.taints}{"\n"}'
kubectl -n myapp get pod -o jsonpath='{.items[0].spec.tolerations}{"\n"}'
[{"effect":"NoSchedule","key":"node.kubernetes.io/unreachable","timeAdded":"…"},{"effect":"NoExecute","key":"node.kubernetes.io/unreachable","timeAdded":"…"}]
[{"effect":"NoExecute","key":"node.kubernetes.io/not-ready","operator":"Exists","tolerationSeconds":300},{"effect":"NoExecute","key":"node.kubernetes.io/unreachable","operator":"Exists","tolerationSeconds":300}]
Diagnose through the platform channel (kubectl debug does not work on a NotReady node): Run az vmss run-command invoke from the Command tab, and confirm kubelet inactive.
Choose one recovery option: run ./fault-inject.sh restore f1 manually (if the debug Pod cannot be scheduled, use az vmss run-command invoke ... --scripts "systemctl start kubelet" instead), or do nothing and wait 5–10 minutes to see the NodeRebootStart auto-repair event.
Cleanup:
kubectl -n myapp scale deploy/myapp --replicas=3
kubectl get pod -o name | grep node-debugger | xargs -r kubectl delete

Risk: affects only the lab node pool. Cost: no additional resources.

Case 1: A log collection DaemonSet causes PID exhaustion

Problem: Nodes went NotReady every few days and recovered after auto-repair rebooted them. Approach: Container Insights Syslog repeatedly showed pthread_create failed: Resource temporarily unavailable. Counting threads per cgroup with ps -e -w -o "thcount,cgname" revealed a leaking thread pool in a Java collection agent. Configuration: Upgrade the agent to a fixed version and set limits on it. As a temporary mitigation, move the node pool to a larger VM size. Limitation: AKS node configuration cannot currently set --pod-max-pids or PID-based eviction (as the official docs state), so this must be handled in the application.

Case 2: OS disk IOPS throttling causes intermittent NotReady

Problem: During peak hours, nodes went NotReady intermittently, and the kubelet logs had many timeouts. Approach: The node performance check in Diagnose and solve problems showed the OS disk hitting its IOPS limit (the managed OS disk was small). Configuration: Create a node pool with an Ephemeral OS disk (or a larger managed disk) and migrate the workloads. Limitation: You cannot change the disk of an existing VMSS directly, so a new node pool is required.

Case 3: A firewall rule change breaks scale-out and existing nodes go NotReady

Problem: Cluster autoscaling failed with OutboundConnFailVMExtensionError, and existing nodes gradually went NotReady. Approach: Running curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/ on an existing node through run-command returned connection resets, meaning the firewall application rules had removed MCR. Configuration: Restore the AKS-required FQDN rules (see Module 4). Limitation: Auto-repair does not handle this kind of cluster-wide network problem.

Common errors and fixes

Ready Unknown NodeStatusUnknown Kubelet stopped posting node status.

Cause: kubelet stopped, the node is down, or the network between the node and the API server is broken.

az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript --scripts "systemctl status kubelet --no-pager | head -20; journalctl -u kubelet -n 50 --no-pager"

Fix: Process problem → restart kubelet or the node. Network problem → roll back the most recent UDR, NSG, or DNS change. VM stopped → check the activity log to see who stopped it.

pthread_create failed: Resource temporarily unavailable (repeated in /var/log/syslog, followed by NotReady)

Cause: Thread or PID exhaustion. containerd and kubelet cannot create threads.

ps -e -w -o "thcount,cgname" --no-headers | awk '{a[$2] += $1} END{for (i in a) print a[i], i}' | sort --numeric-sort --reverse | head --lines=8

Fix: Find the process using the most threads and fix the application. As a temporary measure, increase the VM size.

Code: OutboundConnFailVMExtensionError ... command terminated with exit status=50

Cause: During new node bootstrap, CSE cannot reach https://mcr.microsoft.com/v2/.

Fix: See Module 4. Check UDR, firewall, NSG, proxy, and custom DNS, allow the required AKS outbound endpoints, then retry the operation.

NodeRebootError: Node auto-repair reboot action failed due to an operation failure. See error details here: ...

Cause: The auto-repair action itself failed (for example, quota, a VM platform error, or a resource lock).

kubectl get events -A --field-selector involvedObject.kind=Node | grep -i Error

Fix: Act on the error code in the event (see the Microsoft Learn article “node auto-repair errors”). If needed, reimage manually or use delete-machines.

Node is Ready but NetworkUnavailable=True / Pods stay in ContainerCreating (network plugin is not ready)

Cause: CNI is not ready (azure-cns or cilium Pods are unhealthy, or Overlay routes have not been programmed). Check the exact message in your cluster.

kubectl -n kube-system get pod -o wide | grep -Ei 'cns|cilium|azure-ip-masq|cni'
kubectl -n kube-system logs -l k8s-app=azure-cns --tail=50

Fix: Check the system component logs. Do not manually delete managed component DaemonSets. If needed, reimage the node or open a support ticket.

Command-line exercises
1. Show the last renewal time of every node's Lease.
kubectl get lease -n kube-node-lease -o custom-columns=NAME:.metadata.name,RENEW:.spec.renewTime
2. Without going through the Kubernetes API, check whether kubelet is running on instance 0 of userpool.
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript --scripts "systemctl is-active kubelet"
Scenario analysis
On Sunday at 22:05, all nodes went NotReady at the same time. The network team had a change window at 22:00. Why did auto-repair not take effect? How would you handle it?

“All at once” points to a cluster-wide network or platform change. When a network misconfiguration stops nodes from reporting their status, AKS auto-repair does not run, and rebooting does not fix the outbound problem. Handling: check the activity log for the 22:00 change (UDR, NSG, firewall, or DNS). Use run-command on a node to test connectivity to the API server FQDN and MCR. Roll back or correct the rule. Nodes usually recover on their own afterward; otherwise, reboot them. Afterward: run a connectivity checklist before each change, and set an alert on the number of NotReady nodes.

Verified teaching videos

▶
Troubleshooting Disk Latency with Burak Ok: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · Disk latency / IOPS and node instability
▶
Troubleshooting OOM failures with Claudio Godoy: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · Memory pressure and OOM (node resource pressure root causes)
▶
Troubleshooting AKS Scaling Issues with Jameson Hearn: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · Scale-out / node join failures

Official documentation

Video storyboard (about 90 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a heart above the node icon beats every ten seconds, labeled Lease.
Narration: The kubelet renews its lease every ten seconds. That is the node's heartbeat.
Shot 2 · 20–45s
Visual: The heartbeat stops. The timer reaches forty seconds, the node turns gray, and an unreachable taint appears.
Narration: The controller notices the missed heartbeat, changes the Ready status to Unknown, and adds the unreachable taint.
Shot 3 · 45–65s
Visual: The five-minute timer ends, and the Pod blocks fly to other nodes.
Narration: By default, each Pod tolerates the taint for only three hundred seconds. After that, it is evicted and recreated on another node.
Shot 4 · 65–90s
Visual: Wrench icons appear in turn for reboot, reimage, and redeploy.
Narration: AKS auto-repair works through reboot, reimage, and redeploy, in that order. It cannot fix cluster-wide network problems.
or score ≥ 70% on the quiz

Module 3 · IP addresses and subnet exhaustion

13:00 – 21:00 · A subnet that looks big enough may not be. Azure reserves 5 addresses, each node pre-allocates 1 + maxPods, and surge and max-count are both counted at their theoretical maximum.
8 minutesInsufficientSubnetSize · SubnetIsFullCore animation★★★★★
Learning goals
  • Calculate node subnet and Pod address requirements for three modes: Azure CNI (flat, where the node subnet assigns Pod IPs), Azure CNI with dynamic Pod subnet, and Azure CNI Overlay.
  • Read the InsufficientSubnetSize message (“Pre-allocated IPs … exceeds IPs available …”). Understand why autoscaling uses max-count in the calculation and why surge nodes also need addresses.
  • Know the only reliable fix: create a larger subnet → new node pool → migrate → delete the old pool. Also know the emergency options: lower maxSurge, use maxUnavailable instead, or temporarily lower max-count.
Prerequisites: the networking model from Hour 2. Importance: ★★★★★ (subnet size cannot be changed after the fact, so this is a design-time mistake)

What: What consumes addresses in the node subnet

ModeNode subnet consumption per nodePod addresses come fromCommon limit
Azure CNI (flat / traditional)1 + maxPods (pre-allocated for Pods when the node is created; default maxPods is 30)Node subnetSubnet size
Azure CNI dynamic IP allocation (Pod subnet)1 (node)A separate Pod subnet. Addresses are allocated to nodes in batches (the official docs say 16 per batch; check the docs for the current value).Pod subnet size
Azure CNI Overlay1 (node)Private Pod CIDR (this course uses 192.168.0.0/16). Each node gets one /24.Number of /24s the Pod CIDR can be split into (a /16 gives 256 nodes)
kubenet (announced for retirement)1Pod CIDR + route tableRoute table with 400 routes

The node subnet can also hold other things: internal load balancer frontend IPs (from azure-load-balancer-internal Services), private endpoints, and VMs that other teams placed there. Every Azure subnet reserves 5 addresses (network address, default gateway, two Azure DNS mappings, and broadcast), so a /24 has only 251 usable addresses.

Why: why it fails even when free IPs appear to exist

  • Before scale-out, upgrade, or creating a node pool, AKS runs a pre-check that adds up the theoretical needs of all node pools, including pools in other subnets. For pools with autoscaling enabled, AKS uses max-count rather than the current node count.
  • Upgrades default to maxSurge=1 (or the percentage you set). Surge nodes also consume addresses at 1 + maxPods each. The official formula is required IPs = (node count + maxSurge) × (1 + maxPods) (Azure CNI flat mode).
  • So “only 60% used” does not mean you can upgrade or scale out.

How: two error codes

  • InsufficientSubnetSize (AKS pre-check failure): Code: InsufficientSubnetSize; Message: Pre-allocated IPs <number> exceeds IPs available <number> in Subnet Cidr <CIDR>, Subnet Name <subnet-name>. If Autoscaler is enabled, the max-count from each nodepool is counted towards this total, which means that pre-allocated IPs count represents a theoretical max value, not the actual number of IPs requested. ... Surge nodes also consume the subnet IP space. Consider using smaller maxSurge or use maxUnavailable (aka.ms/aks/maxUnavailable). The portal's Diagnose and solve problems also reports this issue proactively.
  • SubnetIsFull (the network layer's actual allocation fails during VMSS scale-out): Failed to scale node pool '<AGENT POOL NAME>' in Kubernetes service '<NAME>'. Error: VMSSAgentPoolReconciler retry failed: Code='SubnetIsFull' Message='<SUBNET NAME> with address prefix <PREFIX> doesn't have enough capacity for IP addresses.' Details=[]
  • Pod level (a single node has used up its pre-allocated addresses under flat CNI): Pods stick in ContainerCreating, with a FailedCreatePodSandBox event that mentions being unable to allocate an IP (check the exact wording in your cluster). This usually means maxPods is full. The scheduler would not normally place more Pods there, so this is most often caused by IP leaks.

When: fixes and prevention

OptionTimingNotes
Create a larger subnet + new node pool (--vnet-subnet-id) + drain the old pool + delete the old poolPermanent fixOfficial approach: the subnet CIDR of an existing node pool cannot be changed
Temporarily lower max-count on the autoscaling poolEmergencyReduces the pre-check's theoretical value. Set it back after the operation finishes.
Lower --max-surge or use --max-unavailableEmergency (upgrade)Rotate existing nodes. No extra addresses are used, but capacity drops.
Scale in the node pool to free addressesEmergencyThe official first recommendation for SubnetIsFull
Migrate to Azure CNI OverlayMedium to long termThe node subnet uses only node addresses. Pod addresses do not take up VNet space. (For migration steps, see Hour 2 and the official docs.)
Common misconceptions ① “When the subnet is full, just expand the subnet prefix.” AKS does not support changing the CIDR of the subnet used by an existing node pool. The correct approach is a new subnet and a new node pool. ② “Overlay never runs out.” The node subnet still has to hold the nodes and surge nodes, and the Pod CIDR also has a limit (a /16 can only be split into 256 /24s). ③ “Only the current node count matters.” When autoscaling is enabled, the pre-check uses max-count.

Address layout: how many nodes the same /24 can hold in each mode

Azure CNI flat (maxPods=30): 31 addresses per node 5 reserved Node 1 1+30 Node 2 1+30 Node 3 Node 4 Node 5 Node 6 Node 7 / surge 34 left 251 usable ÷ 31 = 8-node limit. Seven nodes plus one surge node reaches the limit. With autoscaler max-count=10, the pre-check fails outright. Azure CNI Overlay: 1 address per node. Pods use 192.168.x.0/24. About 245 addresses remain, enough for about 245 nodes (including surge). Internal LB frontend IPs also come from this pool. Pod CIDR 192.168.0.0/16 → 256 /24s → up to 256 nodes (a second limit)
Figure 3-1: With flat CNI, Pod pre-allocation limits a /24 to 8 nodes. Overlay moves Pod addresses out of the VNet.

Flow: address pre-check for one scale-out request

az aks nodepoolscale / upgrade / add AKS RP pre-checkΣ per pool: (count or max-count+ surge) × addresses per nodeCompare with usable addresses left in the subnetExceeds → InsufficientSubnetSize VMSS scale-out (Compute/network)Assign IP configurations to the NICFlat CNI: primary IP + maxPodsSecondary IP configurationsNot enough → SubnetIsFull Node joinsCSE → kubelet registration
Figure 3-2: Two checkpoints: AKS's theoretical pre-check (InsufficientSubnetSize) and the network layer's actual allocation (SubnetIsFull)

Core animation: subnet IP exhaustion calculator + scale-out/upgrade drill

Adjust the subnet prefix, CNI mode, maxPods, node count and max-count for each pool, and maxSurge. Then click “Scale +1 node” or “Start upgrade”. Each square represents 4 addresses (16 for /22 and bigger). The log below shows AKS's actual pre-check calculation and the error code it will return.

Azure reservedNodes + pre-allocated Podssurge / max-count theoretical usageOther usageFree

Core commands and parameters

CommandPurposeKey parameters / notes
az aks show --query networkProfileNetwork plugin, mode, Pod CIDRnetworkPlugin, networkPluginMode, podCidr
az aks nodepool listPer pool: maxPods, count, max-count, maxSurge, subnet--query "[].{n:name,c:count,max:maxCount,pods:maxPods,surge:upgradeSettings.maxSurge,subnet:vnetSubnetId}"
az network vnet subnet showSubnet prefix and number of IP configurations in use--query "{p:addressPrefix,used:length(ipConfigurations)}"
az aks nodepool add --vnet-subnet-idCreate a pool in the new subnet--max-pods, --mode
az aks nodepool updateAdjust max-count / maxSurge / maxUnavailable--update-cluster-autoscaler --min-count --max-count, --max-surge, --max-unavailable
# 1) Current cluster consumption model
az aks show -g $RG -n $CLUSTER --query "networkProfile.{plugin:networkPlugin,mode:networkPluginMode,podCidr:podCidr,svc:serviceCidr}" -o table
az aks nodepool list -g $RG --cluster-name $CLUSTER \
  --query "[].{pool:name,count:count,max:maxCount,maxPods:maxPods,surge:upgradeSettings.maxSurge,unavail:upgradeSettings.maxUnavailable,subnet:vnetSubnetId}" -o table
Plugin    Mode     PodCidr         Svc
--------  -------  --------------  -----------
azure     overlay  192.168.0.0/16  10.0.0.0/16
Pool       Count    Max    MaxPods    Surge    Unavail    Subnet
---------  -------  -----  ---------  -------  ---------  --------
nodepool1  2        None   250        10%      None       None    ← empty when using a managed VNet
userpool   1        None   250        10%      None       None
# 2) Subnet headroom (BYO VNet: vnet-aks-lab / snet-nodes)
SUBNET_ID=$(az network vnet subnet show -g $RG --vnet-name vnet-aks-lab -n snet-nodes --query id -o tsv)
az network vnet subnet show --ids $SUBNET_ID --query "{prefix:addressPrefix, used:length(ipConfigurations)}" -o table
# Available = 2^(32-prefix) - 5 - used
python3 -c "p=22; used=96; print('free =', 2**(32-p)-5-used)"
Prefix          Used
--------------  ------
10.10.0.0/22    96
free = 923

How to verify: With flat CNI, used should be roughly node count × (1 + maxPods) + other. Common mistakes: With a managed VNet (no --vnet-subnet-id specified), the VNet is in the MC_ resource group and named like aks-vnet-*. The query is slow when there are many ipConfigurations.

# 3) Permanent fix: new subnet + new node pool + migration
az network vnet subnet create -g $RG --vnet-name vnet-aks-lab -n snet-nodes2 --address-prefixes 10.10.4.0/22
SUBNET2=$(az network vnet subnet show -g $RG --vnet-name vnet-aks-lab -n snet-nodes2 --query id -o tsv)
az aks nodepool add -g $RG --cluster-name $CLUSTER -n userpool2 --vnet-subnet-id $SUBNET2 --node-count 2 --mode User
for n in $(kubectl get nodes -l agentpool=userpool -o name); do kubectl cordon $n; done
for n in $(kubectl get nodes -l agentpool=userpool -o name); do kubectl drain $n --ignore-daemonsets --delete-emptydir-data --timeout=10m; done
az aks nodepool delete -g $RG --cluster-name $CLUSTER -n userpool

# 4) Emergency: upgrade without taking new addresses / lower the theoretical value
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --max-surge 0 --max-unavailable 1
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --update-cluster-autoscaler --min-count 1 --max-count 3

Production use: Set an alert for when “subnet headroom < next upgrade requirement”. In IaC, calculate the subnet prefix with the formula and write it as an assertion. --max-unavailable requires a recent API/CLI version (check your version).

Lab 3: Reproduce InsufficientSubnetSize in a /26 subnet (about 12 minutes, optional)

You need a small, separate BYO VNet cluster named aks-lab-ip (Azure CNI flat mode). Cost: one Standard_D2ds_v5 VM and the Free-tier control plane, about US$0.1 per hour (check the official pricing). Delete it as soon as you finish. Permissions: Contributor on the resource group, plus Network Contributor on the subnet (Contributor is enough when the subnet is in the same resource group).

Create the VNet and /26 subnet:
az network vnet create -g $RG -n vnet-aks-lab --address-prefixes 10.10.0.0/16 \
  --subnet-name snet-nodes --subnet-prefixes 10.10.0.0/22 2>/dev/null || true
az network vnet subnet create -g $RG --vnet-name vnet-aks-lab -n snet-tiny --address-prefixes 10.10.8.0/26
TINY=$(az network vnet subnet show -g $RG --vnet-name vnet-aks-lab -n snet-tiny --query id -o tsv)
Calculation: /26 = 64 − 5 = 59 usable. Flat CNI, maxPods=30 → 31 per node. 1 node = 31 ✓. Scaling to 2 nodes = 62 > 59 ✗. Upgrading 1 node with 1 surge = 62 ✗.
Create the cluster (1 node):
az aks create -g $RG -n aks-lab-ip --tier free --node-count 1 --node-vm-size Standard_D2ds_v5 \
  --network-plugin azure --vnet-subnet-id $TINY --max-pods 30 \
  --service-cidr 10.0.0.0/16 --dns-service-ip 10.0.0.10 --generate-ssh-keys
az network vnet subnet show --ids $TINY --query "length(ipConfigurations)"
31
Scale to 2 nodes and watch the pre-check fail:
az aks scale -g $RG -n aks-lab-ip --node-count 2
(InsufficientSubnetSize) Pre-allocated IPs 62 exceeds IPs available 59 in Subnet Cidr 10.10.8.0/26, Subnet Name snet-tiny. If Autoscaler is enabled, the max-count from each nodepool is counted towards this total, ...
Code: InsufficientSubnetSize
Fix drill: create a /24 subnet and a new node pool (System mode, so the old pool can be deleted), then delete the old pool:
az network vnet subnet create -g $RG --vnet-name vnet-aks-lab -n snet-big --address-prefixes 10.10.9.0/24
BIG=$(az network vnet subnet show -g $RG --vnet-name vnet-aks-lab -n snet-big --query id -o tsv)
az aks nodepool add -g $RG --cluster-name aks-lab-ip -n sys2 --mode System --node-count 2 --vnet-subnet-id $BIG --max-pods 30
az aks nodepool delete -g $RG --cluster-name aks-lab-ip -n nodepool1
kubectl config use-context aks-lab   # back to the main cluster
Cleanup:
az aks delete -g $RG -n aks-lab-ip --yes --no-wait
# After the cluster deletion completes:
az network vnet subnet delete -g $RG --vnet-name vnet-aks-lab -n snet-tiny
az network vnet subnet delete -g $RG --vnet-name vnet-aks-lab -n snet-big

Case 1: The /24 is too small, discovered the night before an upgrade

Problem: Flat CNI, maxPods=30, and a /24 subnet with 7 nodes. The upgrade failed with InsufficientSubnetSize (it needs (7+1)×31=248, which is not enough after the internal LB is subtracted). Approach: That night, the upgrade was completed with --max-surge 0 --max-unavailable 1. Afterward, a node pool in a new /21 subnet was created and workloads were migrated. Limitation: During maxUnavailable, capacity drops by one node, so you need PDBs and enough replicas.

Case 2: autoscaler max-count makes add nodepool fail

Problem: The cluster had only 20 nodes, but adding a small node pool failed. Approach: The error message clearly states that the calculation uses each pool's max-count. The existing pool's max-count=100 pushed its theoretical usage far past the subnet's capacity. Configuration: Set max-count to a value that fits the subnet capacity (with platform team review), or give the new pool its own subnet. Limitation: A max-count that is too low limits burst scale-out.

Case 3: Migrating to Overlay frees VNet addresses

Problem: VNet address space was extremely tight in an enterprise hub-spoke network. Approach: All new clusters use Azure CNI Overlay. A /24 node subnet is enough for 200+ nodes. For the few cases where the local network must reach Pods directly, expose them through an internal LB or ingress. Limitation: Overlay Pod IPs are not routable outside the VNet. Plan the Pod CIDR in advance (a /16 → 256 nodes).

Common errors and fixes

Code: InsufficientSubnetSize; Message: Pre-allocated IPs <number> exceeds IPs available <number> in Subnet Cidr <CIDR>, Subnet Name <subnet-name>. ...

Cause: The AKS pre-check's theoretical need (including max-count, surge, and all pools) exceeds the subnet's remaining capacity.

az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{n:name,c:count,max:maxCount,pods:maxPods,surge:upgradeSettings.maxSurge}" -o table

Fix: New subnet + new node pool migration (permanent fix). Temporarily lower max-count / maxSurge, or use maxUnavailable.

Failed to scale node pool ... VMSSAgentPoolReconciler retry failed: Code='SubnetIsFull' Message='<SUBNET NAME> with address prefix <PREFIX> doesn't have enough capacity for IP addresses.'

Cause: During VMSS scale-out, the network layer has no addresses left to allocate (common with upgrade surge).

Fix: Scale in nodes to free addresses, then retry the upgrade. Or add a node pool in a separate subnet → switch the original pool to System or scale it in → migrate.

Adding nodes to an Overlay cluster fails because the Pod CIDR has no /24 left to allocate (check the exact message)

Cause: The Pod CIDR is too small (for example, a /20 has only 16 /24s).

Fix: During planning, choose a large enough Pod CIDR (such as 192.168.0.0/16). Whether an existing cluster's Pod CIDR can be expanded depends on the official docs. Otherwise, migrate to a new cluster.

Warning FailedCreatePodSandBox ... failed to allocate for range / no IP addresses available (flat CNI; check the exact wording)

Cause: The node's pre-allocated Pod IPs are used up or leaked (for example, IPs were not released when containers exited abnormally).

kubectl get pod -A -o wide --field-selector spec.nodeName=NODE | wc -l
kubectl -n kube-system logs -l k8s-app=azure-cns --tail=100 | grep -i -E 'ip|alloc'

Fix: Check whether the Pod count has reached maxPods. If IPs are leaking, reimage the node. Long term, migrate to Overlay or a dynamic Pod subnet.

Command-line exercises
1. List the count, max-count, maxPods, and maxSurge for every node pool.
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{n:name,c:count,max:maxCount,pods:maxPods,surge:upgradeSettings.maxSurge}" -o table
2. Set userpool so that upgrades create no surge nodes and rotate one existing node at a time.
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --max-surge 0 --max-unavailable 1
Scenario analysis
Flat CNI, maxPods=50, /23 subnet, two pools: Pool A currently has 4 nodes (autoscaler max-count 6), and Pool B currently has 3 nodes (autoscaler not enabled). Both have maxSurge set to 1. There are also 6 addresses used by internal LBs or private endpoints. Will upgrading B pass the pre-check?

/23 = 512 − 5 = 507, minus the other 6 → 501. 51 per node. Pool A counted at max-count: 6×51=306. Pool B upgrade: (3+1)×51=204. Total 510 > 501 → fails (InsufficientSubnetSize). Emergency options: temporarily set A's max-count to 5 (255+204=459 ✓), or use maxSurge 0 + maxUnavailable 1 for B (306+153=459 ✓). Permanent fix: create a node pool in a larger subnet, or migrate to Overlay.

Verified teaching videos

▶
Azure CNI Overlay networking in AKS (Preview) — Azure Power Lunch
English · Recorded during the Overlay preview (now GA). Useful for understanding why Overlay saves VNet addresses.
▶
Upgrade Issues 101 with Mosbah Majed: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · Common causes of upgrade failure (including subnets and surge)

No verified video specifically covering InsufficientSubnetSize was found. Use the storyboard below.

Official documentation

Video storyboard script (about 80 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a 256-cell address bar. The first 5 cells turn red and are labeled “Azure reserved”.
Narration: A /24 subnet has only 251 usable addresses.
Shot 2 · 20–45s
Visual: Each node takes up 31 cells (1 + 30), and they fill up. The ninth block does not fit, and an InsufficientSubnetSize error pops up.
Narration: With flat Azure CNI, each node pre-allocates one address plus the maximum number of Pods.
Shot 3 · 45–65s
Visual: Orange dashed blocks (surge, max-count) overlay the grid.
Narration: Temporary upgrade nodes and the autoscaler maximum both count toward the total. Many teams get caught by this.
Shot 4 · 65–80s
Visual: A new subnet and a new node pool appear, and the workloads move over.
Narration: A subnet cannot be expanded in place. The right approach is a new subnet, a new node pool, migration, and then deleting the old pool.
or score ≥ 70% on the quiz

Module 4 · Outbound connections: SNAT port exhaustion and UDR issues

21:00 – 28:00 · Each node gets a fixed number of SNAT ports. When there are too many concurrent connections to the same destination IP:port, new connections hit SYN timeouts.
7 minutesStandard LB outbound rule · NAT GatewayCore animation★★★★★
Learning goals
  • Explain how SNAT ports are allocated (when AllocatedOutboundPorts=0, they are pre-allocated automatically based on backend pool size: 50 or fewer nodes get 1024 ports each) and consumed (each concurrent flow to the same destination IP:port takes one port; ports are reclaimed only after a 30-minute idle timeout).
  • Use LB metrics (SNAT Connection Count Failed, Used / Allocated SNAT Ports) to locate the node, use tcptracer to locate the Pod, and then push the application to reuse connections.
  • Adjust --load-balancer-outbound-ports and outbound IPs using the formula 64,000 × outbound IPs ÷ ports per node = maximum node count. Know when to switch to NAT Gateway.
  • Recognize outbound failures caused by UDR or firewalls: OutboundConnFailVMExtensionError (50), and inbound failures caused by asymmetric routing.
Prerequisites: outbound types from Hour 2. Importance: ★★★★★

What: What SNAT ports are

Nodes (and Pods behind node SNAT under Overlay) have only private IPs. When they reach the public internet, the load balancer's outbound rule replaces the source address with an outbound public IP, and picks a source port for each flow. That source port is a SNAT port. Each public IP has about 64,000 usable ports, and AKS pre-allocates them to each node in the backend pool. A flow is identified by its five-tuple: every concurrent connection from the same node and the same outbound IP to the same destination IP + port needs a different SNAT port. Ports can be reused when the destination differs.

Backend pool node count (automatic AllocatedOutboundPorts=0 mode)Pre-allocated ports per node
1–501024
51–100512
101–200256
201–400128
401–80064
801–100032

The table comes from the default Azure Load Balancer port allocation rules. The AKS docs confirm that with 50 or fewer nodes, each node gets 1024 ports. When scaling from 48 to 52 nodes, the ports per node drop from 1024 to 512. Crossing the boundary reduces the ports on existing nodes and causes connection instability. That is why the official docs recommend setting AllocatedOutboundPorts explicitly.

Why: why exhaustion happens

  • Connections are not reused: Each request opens a new TCP connection (no keep-alive, an HTTP client created on every call, or an oversized database connection pool). Concurrent connections to the same SaaS or API endpoint spike.
  • Ports are reclaimed slowly: The AKS outbound rule idle timeout is 30 minutes. It can be changed with --load-balancer-idle-timeout (for example, set it to 4 minutes when there are many short-lived connections; check the CLI help for the allowed range). Connections that close normally release their ports quickly, but abandoned idle connections wait for the timeout.
  • Crossing a node count boundary: Scaling to 51 nodes changes the ports per node from 1024 to 512.
  • Symptoms: intermittent outbound timeouts (SYN gets no response), concentrated on the same destination while other destinations work normally. Nodes may even go NotReady (if the API server is reached over the public internet and ports are exhausted).

How: locating and fixing

  1. The SNAT detection in Diagnose and solve problems in the portal, or the metrics of the load balancer kubernetes in the MC_ resource group: SNAT Connection Count (split by connection state; check Failed), and Used SNAT Ports / Allocated SNAT Ports (split by backend IP to get the node IPs).
  2. kubectl get nodes -o wide | grep <node IP> finds the node. Use kubectl node-shell to get onto the node and run the BCC tool tcptracer -t4v. Filter public destinations, count by source address or network namespace, and map back to Pods (official docs steps).
  3. Fix the application first: connection pooling, HTTP keep-alive, reuse client objects, and reduce concurrency to the same endpoint.
  4. Scale the platform: add outbound IPs (--load-balancer-managed-outbound-ip-count, up to 100) and set ports per node explicitly (--load-balancer-outbound-ports, must be a multiple of 8). Or switch to NAT Gateway (64,512 ports per public IP, allocated dynamically on demand instead of pre-allocated per node, up to 16 IPs).

UDR and firewalls: another kind of “outbound failure”

The userDefinedRouting outbound type requires the node subnet's route table to send 0.0.0.0/0 to the firewall or NVA, and the firewall must allow the required AKS outbound endpoints (such as mcr.microsoft.com, *.data.mcr.microsoft.com, management.azure.com, login.microsoftonline.com, and port 443 for the API server FQDN; Azure Firewall can use the FQDN tag AzureKubernetesService). Failure symptoms:

  • New node CSE fails: OutboundConnFailVMExtensionError, exit status=50. The output shows curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/. If curl reports Could not resolve host, it is a DNS problem. If it reports Connection timed out/refused, it is a Layer 4 problem (NSG, routes, firewall network rules). If TCP connects but the TLS handshake fails or is reset, it is a Layer 7 problem (firewall application rules, proxy).
  • Image layer download fails: mcr.microsoft.com is allowed, but the data endpoint *.data.mcr.microsoft.com is not (for ACR, *.blob.core.windows.net or <registry>.<region>.data.azurecr.io).
  • Asymmetric routing: On a UDR cluster, when you create a public LoadBalancer Service directly, inbound packets arrive through the LB, but the return packets follow 0.0.0.0/0 to the firewall and are dropped. The correct approach is to have inbound traffic also go through the firewall (DNAT), or to use an internal LB with an application gateway or firewall.

Comparison with similar technologies

LB outbound rule (loadBalancer)NAT Gateway (managed/userAssigned)UDR + firewall
Port allocationStatically pre-allocated per nodeDynamically allocated on demand, 64,512 per IPDetermined by the firewall's SNAT capacity (Azure Firewall: 2,496 ports per public IP per instance; check the docs)
Default idle timeoutAKS sets it to 30 minutes4 minutes (TCP, adjustable)Depends on the device
Suitable forSmall clusters, simple outboundHigh volume of outbound connections, fixed egress IPEnterprise egress control and auditing
Common misconceptions ① “Adding outbound IPs gives each node more ports.” It does not. The official docs say that adding IPs does not add ports to any node. It only allows more nodes. To increase ports per node, you must also set --load-balancer-outbound-ports. ② “Edit the LB outbound rule in the portal.” Changes are overwritten during the next reconciliation (stop/start, upgrade, scale), so use az aks update. ③ “Access to Azure internal services does not use SNAT.” Access to the public endpoints of Storage, SQL, and similar services does use SNAT. Use private endpoints or service endpoints to avoid it.

Data path: address translation when a Pod calls a public API

Pod192.168.1.23:41012(Overlay Pod IP) Nodeiptables MASQUERADE→ 10.224.0.5:41012 LB outbound ruleSNAT → 20.x.x.10:1088Port taken from this node's 1024Idle timeout 30 minutes api.partner.com52.x.x.7:443 Five-tuple constraint: same outbound IP + same destination 52.x.x.7:443 → each concurrent connection needs a different SNAT port Node A already has 1024 active or not-yet-timed-out flows to 52.x.x.7:443 → the 1025th SYN has no port available → client timeout (SNAT Connection Count: Failed) Accessing 13.y.y.9:443 at the same time still succeeds. This is the pattern of “intermittent timeouts to only one destination.”
Figure 4-1: Two address translations from Pod → node → LB outbound rule. Ports are pre-allocated per node and reused per destination.

UDR outbound and asymmetric routing

Node subnetRoute table 0.0.0.0/0 → FW Azure Firewall / NVAAllow required AKS FQDNs Internet / MCR Public LB (Service)Inbound comes in directly Client request Return traffic goes via FW → state mismatch, dropped
Figure 4-2: With UDR outbound, if inbound traffic bypasses the firewall and reaches the public LB directly, the return packets are sent to the firewall by the default route and dropped (asymmetric routing).

Core animation: SNAT port exhaustion simulator

Pods on one node keep sending requests to the same SaaS endpoint 52.x.x.7:443 (simulated time: 1 step = 1 minute). Adjust new connections per minute, whether connections are reused, the number of outbound IPs, ports per node (0 = automatic), node count, and idle timeout, then play. Each square represents 16 SNAT ports on that node. Watch how Allocated / Used and Failed change, then try the “Fix” buttons.

Active connectionsAbandoned, waiting for idle timeoutFree portsFailed SYNs

Core commands and parameters

CommandPurposeKey parameters / notes
az network lb outbound-rule listCheck AllocatedOutboundPorts / IdleTimeout--lb-name kubernetes -g $NODE_RG
az monitor metrics listSNAT metrics--metric SnatConnectionCount --filter "ConnectionState eq 'failed'" (check the metric and dimension names in the portal)
az aks update --load-balancer-outbound-portsExplicit ports per node (multiple of 8)Used together with --load-balancer-managed-outbound-ip-count
az aks update --load-balancer-idle-timeoutOutbound idle timeout (minutes)Default 30; set to 4 if there are many short connections
az aks update --outbound-typeMigrate the outbound type (for example, managedNATGateway)Migration affects outbound traffic. Plan a maintenance window. Check the support matrix in the docs.
tcptracer -t4v (BCC tool on the node)Trace connect/accept/closeFilter public destinations by DADDR, count by SADDR/NETNS
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
az network lb outbound-rule list -g $NODE_RG --lb-name kubernetes -o table
LB_ID=$(az network lb show -g $NODE_RG -n kubernetes --query id -o tsv)
az monitor metrics list --resource $LB_ID --metric SnatConnectionCount --aggregation Total --interval PT5M \
  --filter "ConnectionState eq 'failed'" -o table
az monitor metrics list --resource $LB_ID --metric UsedSnatPorts AllocatedSnatPorts --aggregation Maximum --interval PT5M \
  --filter "BackendIPAddress eq '*'" -o table
AllocatedOutboundPorts    EnableTcpReset    IdleTimeoutInMinutes    Name             Protocol    ProvisioningState
------------------------  ----------------  ----------------------  ---------------  ----------  -------------------
0                         True              30                      aksOutboundRule  All         Succeeded
Timestamp             Name                    Total
--------------------  ----------------------  -------
2026-11-15 09:20:00   SNAT Connection Count   0
...

How to verify: AllocatedOutboundPorts 0 = automatic mode (based on pool size). If Failed stays above 0 and is concentrated on a few node IPs, SNAT is exhausted. Common mistakes: The metric ID (such as SnatConnectionCount) differs from the display name in the portal. If a command reports an unknown metric, use az monitor metrics list-definitions --resource $LB_ID -o table to see the names.

# Locate the Pod (official steps; must run as root on the node)
kubectl node-shell aks-userpool-87654321-vmss000000      # or kubectl debug node ... -- chroot /host
cd /usr/share/bcc/tools
python3 tcptracer -t4v > /tmp/log     # run for a while, then press Ctrl+C
awk '$7 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ &&
     $7 !~ /^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.|168\.63\.129\.16$)/ \
     {print $6,$7,$10}' /tmp/log | sort | uniq -c | sort -nrk 1 | column -t | head
Count  SADDR         DADDR          NETNS
4210   10.224.0.6    52.x.x.7       4026532293
12     10.224.0.6    13.89.174.133  4026531840

With Overlay, Pod outbound traffic is already MASQUERADEd on the node, so SADDR may show the node IP. In that case, map it to the Pod using NETNS + lsns -t net + pstree -aps PID + crictl ps.

# Platform scale-out: set using the formula (example: up to 100 nodes plus surge, 4000 ports per node, requires 7 IPs)
az aks update -g $RG -n $CLUSTER --load-balancer-managed-outbound-ip-count 7 --load-balancer-outbound-ports 4000
az aks update -g $RG -n $CLUSTER --load-balancer-idle-timeout 4
# Outbound connectivity (UDR / firewall): run the same checks as CSE on a node
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 --command-id RunShellScript \
  --scripts "curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/ 2>&1 | tail -5; dig +short mcr.microsoft.com; nc -vz mcr.microsoft.com 443" --query "value[0].message" -o tsv

Production use: Formula 64,000 / ports per node × IPs ≥ max node count + surge. Changing port allocation recreates outbound rules and may briefly affect outbound traffic, so schedule it in a maintenance window.

Lab 4: Read the outbound config, calculate capacity, and make a safe change (about 7 minutes)

Read the current outbound rules and outbound IPs:
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
az aks show -g $RG -n $CLUSTER --query "networkProfile.{type:outboundType, lb:loadBalancerProfile}" -o json
az network lb outbound-rule list -g $NODE_RG --lb-name kubernetes -o table
Calculation: Currently 3 nodes, automatic mode → 1024 per node. If the plan is 60 nodes + maxSurge 3, automatic mode drops to 512. Setting an explicit 2000 ports instead requires IPs = ceil(63 × 2000 / 64000) = 2.
Apply (lab cluster; will briefly affect outbound traffic):
az aks update -g $RG -n $CLUSTER --load-balancer-managed-outbound-ip-count 2 --load-balancer-outbound-ports 2000
az network lb outbound-rule list -g $NODE_RG --lb-name kubernetes -o table
AllocatedOutboundPorts    EnableTcpReset    IdleTimeoutInMinutes    Name
------------------------  ----------------  ----------------------  ---------------
2000                      True              30                      aksOutboundRule
Generate outbound connections and observe metrics (optional):
kubectl -n myapp run snat-burst --image=mcr.microsoft.com/azurelinux/busybox:1.36 --restart=Never -- \
  sh -c 'for i in $(seq 1 300); do wget -q -O /dev/null -T 3 https://mcr.microsoft.com/v2/ & done; wait'
kubectl -n myapp logs snat-burst | tail -3; kubectl -n myapp delete pod snat-burst

300 concurrent connections is far below 2000, so they will not exhaust ports. Check the peak Used SNAT Ports in the LB metrics in the portal after 5 minutes.

Restore (to avoid extra public IP costs):
az aks update -g $RG -n $CLUSTER --load-balancer-managed-outbound-ip-count 1 --load-balancer-outbound-ports 0

Cost: each Standard public IP costs about US$0.005 per hour (check the official pricing). Risk: outbound connections may be briefly interrupted while outbound rules change.

Case 1: Payment callbacks time out intermittently

Problem: Only calls to a third-party payment API timed out intermittently, while other outbound traffic was fine. Approach: LB metrics showed SNAT Failed concentrated on 2 node IPs. tcptracer showed one service creating a new HttpClient on every request. Configuration: Change to a singleton HttpClient with connection pooling and a limit of 50. Also move outbound to NAT Gateway. Limitation: NAT Gateway is a zonal resource, so high availability across zones must be designed per zone (check the docs).

Case 2: Outbound errors spike after scaling to 51 nodes

Problem: After the promotion scale-out, many Pods failed outbound. Approach: In automatic mode, crossing the 50-node boundary halves the ports per node from 1024. Nodes with many long-lived connections immediately ran short. Configuration: Set --load-balancer-outbound-ports explicitly and add outbound IPs, and include maxCount and surge in the formula. Limitation: More ports per IP means fewer nodes supported per IP.

Case 3: Public Service on a UDR cluster is unreachable

Problem: In a cluster with outbound through Azure Firewall, the dev team created a public type: LoadBalancer Service, and external access timed out. Approach: Identified as asymmetric routing. Configuration: Change to an internal LB Service, and publish externally through firewall DNAT or an application gateway. Limitation: Requires ongoing coordination with the network team to maintain the DNAT rules.

Common errors and fixes

dial tcp 52.x.x.7:443: i/o timeout (only some external destinations, at peak times)

Cause: The typical signature of SNAT port exhaustion.

az monitor metrics list --resource $LB_ID --metric SnatConnectionCount --filter "ConnectionState eq 'failed'" --aggregation Total -o table

Fix: Connection reuse → explicit ports + outbound IPs → NAT Gateway. Access Azure PaaS through private endpoints.

Code: OutboundConnFailVMExtensionError ... failed to execute command: command terminated with exit status=50 ... curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/

Cause: HTTPS outbound from the node to MCR fails (UDR, firewall, NSG, proxy, or custom DNS).

az vmss run-command invoke ... --scripts "curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/; dig mcr.microsoft.com; nc -vz mcr.microsoft.com 443"

Fix: Work through the layer where curl fails: forward DNS to 168.63.129.16; allow the NSG and route; add the required AKS FQDNs to firewall application rules. You can also use Connectivity analysis on the portal's node pool (preview, Azure Virtual Network Verifier).

failed to copy: httpReadSeeker: failed open: ... dial tcp <IP>:443: i/o timeout (pulling image layers)

Cause: The registry login endpoint is allowed, but the data endpoints are not (*.data.mcr.microsoft.com, *.blob.core.windows.net, or <registry>.<region>.data.azurecr.io).

Fix: Allow the data endpoints in the firewall. For private endpoint scenarios, check the corresponding private DNS zone.

Portal-edited LB outbound rules “disappeared” after an upgrade

Cause: Changes made directly to the LB resource are removed during cluster reconciliation (stop, start, upgrade, scale).

Fix: Make changes only through az aks update --load-balancer-*.

Command-line exercises
1. Check the current ports per node and idle timeout of aks-lab's outbound rules.
az network lb outbound-rule list -g $(az aks show -g rg-aks-lab -n aks-lab --query nodeResourceGroup -o tsv) --lb-name kubernetes -o table
2. With 4000 ports per node and up to 100 nodes plus maxSurge 2, how many outbound IPs are needed? Write the command.
# 102 × 4000 = 408,000 ÷ 64,000 = 6.4 → 7 IPs
az aks update -g rg-aks-lab -n aks-lab --load-balancer-managed-outbound-ip-count 7 --load-balancer-outbound-ports 4000
Scenario analysis
A service creates about 2000 new connections per minute to the same Redis cloud service (public endpoint 6380) without closing them. There are 3 nodes, in automatic port mode. What happens? Give a three-layer fix.

Each node has 1024 ports. Abandoned connections take a 30-minute idle timeout to be reclaimed, so within a few minutes the node's ports to the Redis endpoint run out. New SYNs time out (SNAT Failed rises), while other destinations are not affected. Fix: ① Application: connection pooling and reuse, and close connections properly. ② Platform: explicit ports plus more outbound IPs, or switch to NAT Gateway, and shorten the idle timeout. ③ Architecture: reach the service through a private endpoint so it no longer uses SNAT.

Verified teaching videos

▶
Troubleshoot Outbound connectivity Issues with Ping He: AKS Troubleshooting Series: Azure Kubernetes — Azure Kubernetes Service (AKS)
AKS official channel · English · Troubleshooting outbound connectivity (SNAT, UDR, firewall)
▶
AKS Egress Traffic and Outbound Types — Houssem Dellai
English · Outbound type comparison (loadBalancer / NAT Gateway / UDR)

Official documentation

Video storyboard (about 90 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: A node holds 1024 small cells (ports), and each connection takes one cell.
Narration: Each node is pre-allocated a fixed number of source network address translation ports. With fifty nodes or fewer, that is 1,024 per node.
Shot 2 · 20–45s
Visual: Many arrows point to the same destination. The cells fill up fast and turn orange, waiting thirty minutes.
Narration: Every concurrent connection to the same destination address and port needs one port. Abandoned connections give their ports back only after the idle timeout.
Shot 3 · 45–65s
Visual: New SYNs hit a wall and turn red. Next to them, arrows to another destination still get through.
Narration: So timeouts appear to only one destination at a time. That is the typical sign of port exhaustion.
Shot 4 · 65–90s
Visual: Three keys: connection pooling, explicit ports plus outbound IPs, and a NAT gateway.
Narration: First, have the application reuse connections. Then scale ports and outbound addresses using the formula, or switch to a NAT gateway.
or score ≥ 70% on the quiz

Module 5 · Load balancer, ingress, and DNS failures

28:00 – 35:00 · Troubleshoot hop by hop along the request path: DNS → public IP → Azure LB rules and health probes → NSG → node → ingress controller → Service → EndpointSlice → Pod
7 minutesApplication routing managed NGINX: security patch support until 2026-11-30LocalDNS: Preferred by default on AKS Standard from 1.37★★★★☆
Learning goals
  • Use the hop-by-hop method to troubleshoot LoadBalancer Services and ingress failures. Read the EXTERNAL-IP <pending> events, the default health probe behavior, and the effect of externalTrafficPolicy.
  • Understand how the retirement of the managed NGINX in the AKS application routing add-on (Microsoft security patches until 2026-11-30) affects troubleshooting and migration.
  • Troubleshoot cluster DNS: CoreDNS, coredns-custom, and VNet custom DNS must forward to 168.63.129.16. For LocalDNS in 1.37, both TCP and UDP port 53 must be allowed.
Prerequisites: the ingress and DNS module from Hour 2. Importance: ★★★★☆

What: each hop an external request passes through

  1. DNS: The client resolves the domain name to a public IP (Azure DNS zone or external DNS).
  2. Azure LB frontend IP + load balancing rules: cloud-provider-azure (cloud-controller-manager) creates rules and health probes from the Service. Nodes that fail the probe receive no traffic.
  3. NSG: AKS automatically adds inbound rules for Service ports in the node NSG. loadBalancerSourceRanges / azure-allowed-ip-ranges narrow the allowed sources.
  4. Node → kube-proxy / Cilium eBPF: NodePort → Service → pick one ready endpoint.
  5. Ingress controller (application routing NGINX, a Gateway API implementation, or Application Gateway for Containers): routes to the backend Service by Host/Path.
  6. EndpointSlice → Pod: Only Ready Pods are endpoints. If the selector is wrong, the endpoints are empty.
  7. In-cluster DNS: Pods reach dependencies (Redis, external APIs) through CoreDNS first (Service IP 10.0.0.10). Custom VNet DNS must be able to resolve public names and Azure private DNS zones (usually by forwarding to 168.63.129.16).

Why: AKS-specific pitfalls

  • Default health probe behavior: with externalTrafficPolicy: Local, the HTTP /healthz probe targets kube-proxy's healthCheckNodePort. Nodes with no local Pod are marked unhealthy; this is by design. With Cluster + TCP, only the port is probed. If appProtocol: http is set, the default probe path is /. If the app returns 404 for /, all backends are marked unhealthy. Fix it with the annotation service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path (myapp uses /healthz).
  • EXTERNAL-IP pending: the cluster identity lacks permission on the resource group that holds the BYO subnet or the pre-created public IP; or the public IP quota is exhausted; or Azure Policy blocks creating public IPs; or the static IP is in another resource group but the azure-load-balancer-resource-group annotation is missing.
  • Editing the LB outside Kubernetes: changes made directly to Azure LB rules are overwritten by cloud-controller-manager.
  • Application routing NGINX retirement: upstream ingress-nginx stopped being maintained in March 2026. Microsoft provides critical security patches for the managed NGINX in the application routing add-on until 2026-11-30, after which it is no longer supported (existing traffic keeps working, but without support). The official migration target is the Gateway API implementation of application routing (GA; check the release notes), or another supported implementation such as Application Gateway for Containers. When troubleshooting, first confirm which implementation you are using.
  • LocalDNS: starting with Kubernetes 1.37, AKS Standard node pools without an explicit LocalDNS setting default to Preferred mode, and it is enabled once the compatibility check passes. It changes the DNS path for workloads and can expose the problem of “custom DNS or firewall allows UDP 53 but not TCP 53.” Before upgrading, test custom DNS with dig +udp and dig +tcp, and set it explicitly to Disabled if needed.

How: hop by hop

The fastest approach is to verify from the inside out: ① the Pod itself (kubectl exec curl localhost:5000/healthz) → ② the Service ClusterIP (curl from another Pod) → ③ whether the EndpointSlice has addresses → ④ NodePort (curl on the node) → ⑤ LB health probe status (portal: LB → Insights / Metrics → Health Probe Status) → ⑥ effective NSG rules → ⑦ DNS. The problem lies between the first hop that fails and the hop before it.

When: symptom → first check

SymptomFirst check
EXTERNAL-IP <pending>Events from kubectl describe svc (SyncLoadBalancerFailed)
Has an IP but times outHealth probe status, NSG, externalTrafficPolicy, UDR asymmetric routing (Module 4)
Ingress returns 404ingressClassName, Host, Path; ingress controller logs
Ingress returns 502/503Backend Service has no endpoints, or the port is wrong
could not resolve host inside a PodCoreDNS Pods, whether NetworkPolicy allows port 53, coredns-custom, VNet DNS
Common misconceptions ① “If the EXTERNAL-IP is assigned, the path works.” The health probes may all be failing. ② “externalTrafficPolicy: Local marking some nodes unhealthy is a fault.” This is by design: only nodes running Pods receive traffic, which preserves the client IP. ③ “If CoreDNS is broken, restart it.” First check whether someone broke coredns-custom and whether the upstream DNS is reachable. A restart only hides the evidence.

Request path and evidence at each hop

ClientDNS Azure LBRules + probes NSG Nodekube-proxy/eBPF Ingress controllerHost/Path ServiceEndpointSlice Pod:5000 nslookup Health Probe Statusdescribe svc Events Effective security rules curl NodeIP:NodePort Controller logs404/502 get endpointslices exec curl /healthz Pod outbound dependency: Pod → CoreDNS (10.0.0.10) [→ LocalDNS node cache, which may be enabled by default from 1.37] → VNet DNS (Azure 168.63.129.16 or custom DNS; UDP and TCP 53 must be allowed)Evidence: kubectl -n kube-system logs -l k8s-app=kube-dns, the coredns-custom ConfigMap, dig +udp / +tcp
Figure 5-1 Verify hop by hop from the inside out; each hop has a matching evidence command

Default health probe behavior

externalTrafficPolicy: LocalHTTP /healthz → healthCheckNodePortNode with no local Pod → 503 → unhealthy(by design; preserves the client source IP) Cluster + TCP (appProtocol empty)TCP probe to NodePortPort open means healthyAn app returning 500 is not removed Cluster + appProtocol: httpHTTP probe path defaults to “/”App returns 404 for / → all unhealthyAnnotation health-probe-request-path=/healthz
Figure 5-2 Default probes in cloud-provider-azure (from the default behavior table in the AKS “Configure Standard LB” documentation)

Request path hop-by-hop tracer

Choose an injected fault, then click “Send request.” The animation moves along the real path hop by hop. Each hop shows what the component actually does (DNS query, LB rule matching, probing, NSG, iptables/eBPF, EndpointSlice selection), stops at the failing hop, and displays the real error you would see along with the evidence command.

Core commands and parameters

CommandPurposeKey parameters / notes
kubectl describe svcLB sync events, NodePort, healthCheckNodePortLook for EnsuringLoadBalancer / SyncLoadBalancerFailed
kubectl get endpointslices -l kubernetes.io/service-name=SWhether endpoints exist and are ready-o yaml to view conditions
az network lb probe list / rule listLB probes and rules--lb-name kubernetes
az network nic list-effective-nsgEffective NSG rules on the node NICVMSS instance NICs need the vmss nic command (check the actual syntax)
kubectl -n kube-system logs -l k8s-app=kube-dnsCoreDNS logs--tail
kubectl -n kube-system get cm coredns-custom -o yamlCustom CoreDNS configurationAKS treats coredns as read-only; put customizations in coredns-custom
# Inside out
POD=$(kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].metadata.name}')
kubectl -n myapp exec $POD -- python -c "import urllib.request;print(urllib.request.urlopen('http://localhost:5000/healthz').status)"
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp -o wide
kubectl -n myapp describe svc myapp | sed -n '/Type:/,$p'
200
NAME          ADDRESSTYPE   PORTS   ENDPOINTS                                 AGE
myapp-x7k2p   IPv4          5000    192.168.0.14,192.168.1.22,192.168.2.9    3d
Type:                     LoadBalancer
LoadBalancer Ingress:     20.x.x.45
Port:                     <unset>  80/TCP
TargetPort:               5000/TCP
NodePort:                 <unset>  31544/TCP
Endpoints:                192.168.0.14:5000,192.168.1.22:5000,192.168.2.9:5000
External Traffic Policy:  Cluster
Events:
  Normal  EnsuringLoadBalancer  ...  Ensuring load balancer
  Normal  EnsuredLoadBalancer   ...  Ensured load balancer
# Health probes: check them, then correct them to match the app's health endpoint
az network lb probe list -g $NODE_RG --lb-name kubernetes -o table
kubectl -n myapp annotate svc myapp service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path=/healthz --overwrite
# DNS: start a debug Pod in the myapp namespace
kubectl -n myapp run dnsdbg --rm -it --image=mcr.microsoft.com/azurelinux/busybox:1.36 --restart=Never -- \
  sh -c 'cat /etc/resolv.conf; nslookup redis.myapp.svc.cluster.local; nslookup mcr.microsoft.com'
kubectl -n kube-system get pod -l k8s-app=kube-dns -o wide
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=30
kubectl -n kube-system get cm coredns-custom -o yaml 2>/dev/null
search myapp.svc.cluster.local svc.cluster.local cluster.local ...
nameserver 10.0.0.10
options ndots:5
Server:    10.0.0.10
Name:      redis.myapp.svc.cluster.local
Address:   10.0.152.31

How to verify: nameserver should be 10.0.0.10 (the DNS Service IP used in this course). If LocalDNS is enabled, name resolution on the node goes through the local cache (check the actual configuration). Common mistakes: editing the coredns ConfigMap directly (AKS overwrites it); allowing only UDP 53 on custom DNS. Production use: set alerts on the CoreDNS error rate and latency (managed Prometheus metric coredns_dns_responses_total{rcode="SERVFAIL"}).

# DNS self-check before the 1.37 upgrade (official recommendation)
dig +udp @<custom-dns-ip> mcr.microsoft.com
dig +tcp @<custom-dns-ip> mcr.microsoft.com

Lab 5: Reproduce and fix three “cannot access” problems (about 8 minutes)

Baseline:
IP=$(kubectl -n myapp get svc myapp -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
curl -s -o /dev/null -w '%{http_code}\n' http://$IP/healthz
200
Fault f4 (wrong selector):
./fault-inject.sh inject f4
curl -s -m 5 -o /dev/null -w '%{http_code}\n' http://$IP/healthz || echo timeout
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp
timeout
NAME          ADDRESSTYPE   PORTS     ENDPOINTS   AGE
myapp-x7k2p   IPv4          <unset>   <unset>     3d

ENDPOINTS is empty → Service layer. Fix: ./fault-inject.sh restore f4.

Fault f5 (NetworkPolicy blocks DNS):
./fault-inject.sh inject f5
POD=$(kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].metadata.name}')
kubectl -n myapp exec $POD -- python -c "import socket;print(socket.gethostbyname('redis'))"
socket.gaierror: [Errno -3] Temporary failure in name resolution

Fix approach: allow UDP/TCP 53 to k8s-app=kube-dns in kube-system. Restore: ./fault-inject.sh restore f5.

Fault f8 (coredns-custom forwards to a server that does not exist):
./fault-inject.sh inject f8
kubectl -n myapp run dnsdbg --rm -it --image=mcr.microsoft.com/azurelinux/busybox:1.36 --restart=Never -- nslookup app.contoso.internal
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=10
;; connection timed out; no servers could be reached
[ERROR] plugin/errors: 2 app.contoso.internal. A: read udp 192.168.0.7:51234->10.10.255.254:53: i/o timeout

Restore: ./fault-inject.sh restore f8.

Cleanup: confirm all three faults are restored and curl http://$IP/healthz returns 200. Cost and risk: only the myapp namespace and CoreDNS are affected (brief restart).

Case 1: all backends “unhealthy” after upgrading the Service annotation

Problem: after adding appProtocol: http to a gRPC gateway, all external access timed out. What happened: the LB probe became HTTP /, and the app returns 404 for /. Configuration: add azure-load-balancer-health-probe-request-path: /healthz. Limitation: the probe path must be reachable from the LB source address (168.63.129.16) and must not require authentication.

Case 2: 404s during migration from application routing NGINX to Gateway API

Problem: after migrating to the application routing Gateway API implementation, some routes return 404. What happened: the HTTPRoute parentRefs points to the wrong Gateway or listener, and hostnames does not match. Configuration: go through each Ingress → HTTPRoute mapping using the official migration guide; run old and new in parallel during migration, and switch over with DNS. Limitation: NGINX-specific annotations (such as rewrite and snippet) need the matching Gateway API filters or policies.

Case 3: hybrid-cloud custom DNS allows only UDP 53

Problem: after upgrading the node pool to 1.37, name resolution fails for some domains with large responses. What happened: LocalDNS defaults to Preferred, which falls back to TCP, but the firewall allows only UDP 53. Configuration: allow TCP 53, or explicitly set LocalDNS to Disabled on the node pool before upgrading. Limitation: follow the “Configure LocalDNS in AKS” documentation for how LocalDNS is configured.

Common errors and fixes

EXTERNAL-IP <pending>; Events: Warning SyncLoadBalancerFailed ... AuthorizationFailed ... does not have authorization to perform action 'Microsoft.Network/publicIPAddresses/join/action' (check the actual message)

Cause: the cluster identity (the control plane managed identity) lacks permission on the resource group of the pre-created public IP or BYO subnet; or Azure Policy denies creating public IPs.

kubectl -n myapp describe svc myapp | sed -n '/Events/,$p'
az aks show -g $RG -n $CLUSTER --query identity.principalId -o tsv

Fix: assign Network Contributor (or a custom role with least privilege) to the cluster identity on the relevant resource group or subnet. If the static IP is in another resource group, add the annotation service.beta.kubernetes.io/azure-load-balancer-resource-group, and prefer azure-pip-name.

Has EXTERNAL-IP, curl times out; LB Health Probe Status is 0%

Cause: the health probe path or protocol does not match, or there is no local Pod under the Local policy.

az network lb probe list -g $NODE_RG --lb-name kubernetes -o table
kubectl -n myapp get svc myapp -o jsonpath='{.spec.externalTrafficPolicy} {.spec.ports[*].appProtocol}{"\n"}'

Fix: set the probe path with the annotation, and confirm the app returns 200 for the probe.

Ingress returns 404 Not Found (nginx)

Cause: the Ingress does not specify ingressClassName (application routing uses webapprouting.kubernetes.azure.com), the Host does not match, or the Path type is wrong.

kubectl get ingress -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,CLASS:.spec.ingressClassName,HOSTS:.spec.rules[*].host
kubectl -n app-routing-system logs deploy/nginx --tail=30

Fix: add the correct class and host; plan the migration to the Gateway API implementation (managed NGINX support ends 2026-11-30).

[ERROR] plugin/errors: 2 example.com. A: read udp 192.168.x.x:xxxxx-><dns-ip>:53: i/o timeout

Cause: the CoreDNS upstream is unreachable: VNet custom DNS is not working, coredns-custom forwards incorrectly, or the firewall blocks 53.

kubectl -n kube-system get cm coredns-custom -o yaml
az network vnet show -g $RG -n vnet-aks-lab --query dhcpOptions.dnsServers

Fix: forward custom DNS to 168.63.129.16; after correcting coredns-custom, run kubectl -n kube-system rollout restart deploy/coredns; allow UDP+TCP 53.

Command-line exercises
1. Check whether the myapp Service has empty endpoints.
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp
2. Change the LB health probe path of the myapp Service to /healthz.
kubectl -n myapp annotate svc myapp service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path=/healthz --overwrite
Scenario analysis
Services inside the cluster occasionally fail to reach db.corp.internal. nslookup works on the node but times out inside a Pod. List the troubleshooting order.

Node resolution works, so VNet DNS itself is available. The problem is in the cluster DNS path: ① the Pod's /etc/resolv.conf (nameserver 10.0.0.10, ndots); ② whether NetworkPolicy allows UDP/TCP 53 to kube-dns; ③ CoreDNS Pod status and logs (i/o timeout, SERVFAIL); ④ the forwarding target for corp.internal in coredns-custom; ⑤ whether the NSG or firewall blocks CoreDNS traffic to its upstream (CoreDNS Pod source addresses are SNAT'd through the node); ⑥ if LocalDNS is enabled in 1.37, check the node-local cache and TCP 53.

Verified teaching videos

▶
Troubleshooting DNS Issues with Qasim Sarfaraz: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
AKS official channel · English · CoreDNS and custom DNS troubleshooting
▶
Troubleshoot Outbound connectivity Issues with Ping He: AKS Troubleshooting Series: Azure Kubernetes — Azure Kubernetes Service (AKS)
English · partly related to this module's NSG and routing sections

No verified video was found that specifically covers LB health probes or the application routing Gateway API migration. Please use the storyboard below.

Official documentation

Video storyboard script (about 80 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a subway line with seven stations: DNS, LB, NSG, node, ingress, Service, Pod.
Narration: an external request has to pass through seven stations, and a failure at any one of them looks like “can't reach the app.”
Shot 2 · 20–45s
Visual: zoom in on the LB station. The probe knocks on “/”, gets a 404, and every node light turns red.
Narration: once the application protocol is set to http, the default probe path is the root path. If it returns 404, every backend is removed.
Shot 3 · 45–65s
Visual: the Service platform is empty, labeled Endpoints empty.
Narration: when the selector is wrong, the Service has no endpoints, and requests are lost inside the cluster.
Shot 4 · 65–80s
Visual: a Pod calls CoreDNS, and the phone line is cut by a NetworkPolicy.
Narration: don't forget DNS. The network policy must allow port 53 to CoreDNS, for both UDP and TCP.
or score ≥ 70% on the quiz

Module 6 · Upgrade failures: PDB blocking, quotas, and eviction

35:00 – 42:00 · Upgrade = pre-checks → surge new nodes → cordon → drain (Eviction API, subject to PDBs) → delete old nodes; each step has its own failure codes
7 minutesundrainable-node-behavior Cordonforce upgrade: CLI 2.79+ / API 2025-09-01+★★★★★
Learning goals
  • List the AKS pre-upgrade checks (breaking API changes, version path, PDB configuration, quota, subnet, certificates and service principal, managed resource group locks), and map each failure to the check it belongs to.
  • Read the original UpgradeFailed message caused by a PDB, and confirm it using ALLOWED DISRUPTIONS from kubectl get pdb and the Eviction blocked by Too Many Requests (usually a pdb) event.
  • Know three ways to handle it: fix the PDB and retry the upgrade to the same version; use --undrainable-node-behavior Cordon to quarantine the node (label kubernetes.azure.com/upgrade-status=Quarantined); and, as a last resort, --enable-force-upgrade.
  • Handle QuotaExceeded: read the Current Limit, Usage, and Additional Required values, lower maxSurge or request a quota increase, then reconcile with az aks update / az aks nodepool update.
Prerequisite: the surge upgrade process from Hour 6. Importance: ★★★★★

What: the upgrade pipeline and where it fails

StageWhat AKS doesTypical failure
Pre-checksBreaking API changes, upgrade path, PDBs (such as maxUnavailable=0), quota, subnet, expired credentials, managed resource group locksThe operation is rejected outright (for example UnsatisfiablePDB or InsufficientSubnetSize; check the exact error codes)
SurgeCreate new nodes per maxSurge (new version / new image)QuotaExceeded, SubnetIsFull, SKUNotAvailable / AllocationFailed / OverconstrainedAllocationRequest, CSE exit code 50
Cordon + DrainCall the Eviction API on old nodes and wait for Pods to terminate gracefully; the default drain timeout is 30 minutesPDB blocks → UpgradeFailed “Too Many Requests”; Pods terminate too slowly
Soak (optional)After draining each node, wait --node-soak-duration (default 0)—
Delete old nodesDelete VMSS instancesResource locks, platform errors

Why: why PDBs make upgrades fail

Drain does not “kill Pods.” It calls POST .../pods/NAME/eviction for each Pod. The API server checks the PDB that matches the Pod. If the eviction would drop available Pods below minAvailable (or exceed maxUnavailable), it returns HTTP 429 Too Many Requests. AKS keeps retrying; once the drain timeout is exceeded, the operation fails and the cluster or node pool enters Failed. The three most common “unsatisfiable” PDBs are: minAvailable equal to the replica count; maxUnavailable: 0; and Pods that are already not ready, which makes ALLOWED DISRUPTIONS 0.

Official error message (UpgradeFailed): Drain node aks-<nodepool-name>-xxxxxxxx-vmssxxxxxx failed when evicting pod <pod-name> failed with Too Many Requests error. This error is often caused by a restrictive Pod Disruption Budget (PDB) policy. See https://aka.ms/aks/debugdrainfailures. Original error: Cannot evict pod as it would violate the pod's disruption budget.. PDB debug info: <namespace>/<pod-name> blocked by pdb <pdb-name> with 0 unready pods.

How: handling options (from conservative to aggressive)

  1. Fix the PDB or add replicas so that ALLOWED DISRUPTIONS ≥ 1, then re-run az aks upgrade for the same target version (the CLI prints “Cluster currently in failed state. Proceeding with upgrade to existing version … to attempt resolution of failed cluster state.”).
  2. Back up → delete the PDB → upgrade → reapply (when the PDB cannot be modified).
  3. Undrainable node behavior: az aks nodepool update --undrainable-node-behavior Cordon --max-blocked-nodes 2 --drain-timeout 30. The default is Schedule (delete the blocked node and surge a replacement). Cordon (recommended) isolates the node and labels it kubernetes.azure.com/upgrade-status=Quarantined, and the upgrade continues. max-blocked-nodes defaults to the value of maxSurge. Afterwards: fix the PDB → remove the label → optionally az aks nodepool delete-machines → az aks update, or nodepool scale based on the number of upgraded nodes, to bring the state back to Succeeded.
  4. Automatic PDB management (preview extension): temporarily adds replicas when a PDB blocks the drain, then scales back once the drain completes.
  5. Force upgrade (last resort): az aks upgrade ... --enable-force-upgrade --upgrade-override-until <UTC time>. It bypasses PDBs and may drain all Pods at once, causing an outage; the undrainable settings do not apply when it is enabled. Requires CLI 2.79.0+ or API 2025-09-01+. If no deadline is given, the default is 3 days.

Quota: QuotaExceeded

Surge nodes need additional vCPUs. Official message: Create or update VMSS <AKS-VM/VMSS-resource-ID> failed. Operation couldn't be completed because it results in exceeding approved <SKU-family> Cores quota. Additional details - Deployment Model: Resource Manager, Location: <region>, Current Limit: A, Current Usage: B, Additional Required: C, (Minimum) New Limit Required: D. Quota is checked at two levels: regional total vCPUs and VM family vCPUs. To handle it: check with az vm list-usage -l <region> → lower maxSurge or request a quota increase → reconcile with az aks update (cluster level) or az aks nodepool update (node pool level).

When: platform-initiated upgrades (from 2027-06-01)

Official announcement: from June 1, 2027, clusters that remain on an unsupported version beyond the 60-day grace period will be upgraded automatically by AKS. Such upgrades do not respect maintenance windows, do not perform deprecated-API checks, and can override PDBs that block the drain. Conclusion: PDBs cannot replace staying on a supported version.

Comparison

SettingExtra nodesBehavior
maxSurge=5, maxUnavailable=05 surgeOfficial table: if all 5 surge nodes are obtained, the upgrade succeeds; if only 0–4 are obtained, the upgrade fails (insufficient capacity)
maxSurge=0, maxUnavailable=5NoneDrain the 5 existing nodes directly (suited to tight quota or subnets)
Official recommendation (production)—maxSurge=33%, maxUnavailable=1; dev/test 50% / 2
Common misconceptions ① “If an upgrade fails, you have to start over.” Fix the root cause, then retry the same version. ② “The stricter the PDB, the safer.” A PDB with maxUnavailable: 0 or minAvailable = replicas makes every voluntary disruption impossible, so upgrades, scale-downs, and node repairs all get stuck. ③ “Force upgrade is a normal option.” It bypasses PDB protection and can cause a complete outage.

How the Eviction API interacts with PDBs during drain

AKS upgrade orchestrationCordon old node → drain kube-apiserverPOST pods/x/evictionCheck matching PDBs ALLOWED ≥ 1 → 201 ALLOWED = 0 → 429 Pod terminates → next Retry until drain timeout(default 30 minutes) Schedule (default)Delete blocked node, surge replaces it Cordon (recommended)Quarantine + Quarantined label; upgrade continues Not set / exceeds max-blockedUpgradeFailed → Failed
Figure 6-1 Drain uses the Eviction API; a PDB that disallows disruption returns 429. What happens after the timeout is determined by undrainable-node-behavior

Failure triage: read the error code to find the direction

Upgrade failed Too Many Requests / PDB → this module QuotaExceeded → quota SubnetIsFull → Module 3 exit status=50 → Module 4 SKUNotAvailable / AllocationFailed Breaking API change → migrate APIs first Fix the root causeRetry the same version
Figure 6-2 Read the Code and Message first, then go to the matching module. Always finish with “fix → retry the same version / reconcile with az aks update.”

Surge upgrade + PDB eviction simulator

3 nodes, myapp with 3 replicas (one per node). Set the PDB, maxSurge, undrainable-node-behavior, and quota headroom, then play the upgrade. Each step shows the real calls between the AKS orchestrator and the API server (Eviction 201/429), plus the final operation result.

Core commands and parameters

CommandPurposeKey parameters / notes
kubectl get pdb -AFind PDBs with ALLOWED DISRUPTIONS = 0Check before every upgrade
kubectl get events -A | grep -i drainDrain events“Eviction blocked by Too Many Requests (usually a pdb)”
az aks nodepool updateUpgrade behavior--max-surge, --max-unavailable, --drain-timeout (minutes), --node-soak-duration, --undrainable-node-behavior, --max-blocked-nodes
az aks upgradeUpgrade / retry the same version--kubernetes-version, --control-plane-only, --enable-force-upgrade --upgrade-override-until
az vm list-usageRegional and VM family vCPU quota-l canadacentral -o table
az aks updateReconcile without parameters; restores SucceededUse after fixing the root cause
# Pre-upgrade self-check
az aks get-upgrades -g $RG -n $CLUSTER -o table
kubectl get pdb -A
az vm list-usage -l $LOC -o table | grep -Ei 'Total Regional|DDSv5|Name'
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{pool:name,surge:upgradeSettings.maxSurge,unavail:upgradeSettings.maxUnavailable,drain:upgradeSettings.drainTimeoutInMinutes,undrainable:upgradeSettings.undrainableNodeBehavior}" -o table
NAMESPACE   NAME               MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
myapp       myapp-pdb-strict   3               N/A               0                     2m
Name                                   CurrentValue    Limit
-------------------------------------  --------------  -------
Total Regional vCPUs                   12              20
Standard DDSv5 Family vCPUs            12              20

How to verify: a PDB with ALLOWED DISRUPTIONS of 0 will always block the drain. If the remaining quota is less than maxSurge × vCPUs per node, you get QuotaExceeded. Common mistakes: checking only the regional total and not the VM family; the field name undrainableNodeBehavior should match the actual output of az aks nodepool show -o json.

# Recovery path after a failure
kubectl get events -A | grep -i drain
kubectl -n myapp get pdb myapp-pdb-strict -o yaml > pdb-backup.yaml
kubectl -n myapp patch pdb myapp-pdb-strict --type merge -p '{"spec":{"minAvailable":2}}'
az aks upgrade -g $RG -n $CLUSTER --kubernetes-version <same target version> --yes

# Prevent it: isolate the blocked node instead of failing the upgrade
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool \
  --undrainable-node-behavior Cordon --max-blocked-nodes 1 --drain-timeout 15
kubectl get nodes -l kubernetes.azure.com/upgrade-status=Quarantined
kubectl label node <node> kubernetes.azure.com/upgrade-status-

# Quota insufficient
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --max-surge 1
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool     # reconcile without parameters (node pool level)

Production use: add a “pre-upgrade check” job to CI: kubectl get pdb -A -o json | jq '.items[] | select(.status.disruptionsAllowed==0)', and use the Upgrade readiness check in the portal.

Lab 6: Block a drain with a strict PDB and recover (about 10 minutes)

To avoid actually upgrading the cluster version, this lab uses a node image upgrade or a manual drain to demonstrate the same mechanism. A node image upgrade rolls through the userpool nodes (about 5–10 minutes).

Inject a strict PDB (f2):
./fault-inject.sh inject f2
kubectl -n myapp get pdb
Manual drain to observe 429:
N=$(kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].spec.nodeName}')
kubectl drain $N --ignore-daemonsets --delete-emptydir-data --timeout=60s
node/aks-userpool-87654321-vmss000000 cordoned
evicting pod myapp/myapp-6d9f7c8b5d-4kx2p
error when evicting pods/"myapp-6d9f7c8b5d-4kx2p" -n "myapp" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
...
error: unable to drain node "aks-userpool-87654321-vmss000000" due to error: global timeout reached: 1m0s
kubectl uncordon $N
Set the Cordon behavior, then run a node image upgrade (optional, time-consuming):
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --undrainable-node-behavior Cordon --max-blocked-nodes 1 --drain-timeout 5
az aks nodepool upgrade -g $RG --cluster-name $CLUSTER -n userpool --node-image-only --no-wait
kubectl get nodes -L kubernetes.azure.com/upgrade-status -w

If a myapp Pod is on that node, the node is labeled Quarantined after the 5-minute drain timeout instead of the operation failing (behavior may vary). If the parameter is not recognized, upgrade the Azure CLI or install aks-preview.

Recovery:
./fault-inject.sh restore f2
kubectl label nodes --all kubernetes.azure.com/upgrade-status- 2>/dev/null || true
az aks update -g $RG -n $CLUSTER
az aks show -g $RG -n $CLUSTER --query provisioningState -o tsv
Succeeded
Cleanup: keeping the Cordon setting has no extra cost; a node image upgrade adds the cost of one surge node while it runs.

Case 1: a third-party operator's PDB blocks every upgrade

Problem: a database operator created a PDB with minAvailable: 1 for a single-replica instance, and every upgrade failed with UpgradeFailed. What happened: the node pool was set to --undrainable-node-behavior Cordon --max-blocked-nodes 2; after the upgrade completed, the team coordinated with the DBA during the maintenance window to switch primaries manually and delete the quarantined nodes. Limitation: quarantined nodes still run the old version and must be handled soon, or they fall outside the support boundary.

Case 2: GPU pool QuotaExceeded during upgrade

Problem: the NC-series quota had only 0 left, so a surge of one node failed. What happened: the GPU pool was changed to --max-surge 0 --max-unavailable 1, and nodes were rotated one at a time during off-peak hours. Limitation: one GPU node is missing during rotation; alternatively, request more quota and then restore surge.

Case 3: a failed upgrade hidden by automatic repair

Problem: the overnight automatic upgrade failed. In the morning the cluster showed Succeeded, but some nodes were still on the old version. What happened: the activity log and the version column of az aks nodepool list showed that someone else had run az aks update to reconcile. Configuration: set up an activity log alert for “AKS upgrade failed,” and send maintenance window notifications outside the upgrade channel. Limitation: reconciliation only restores state; it does not complete the upgrade.

Common errors and fixes

(UpgradeFailed) Drain node aks-<nodepool>-xxxxxxxx-vmssxxxxxx failed when evicting pod <pod-name> failed with Too Many Requests error. ... PDB debug info: <namespace>/<pod-name> blocked by pdb <pdb-name> with 0 unready pods.

Cause: the PDB's ALLOWED DISRUPTIONS is 0.

kubectl get pdb -A
kubectl get events -A | grep -i drain

Fix: adjust the PDB or add replicas, then az aks upgrade to the same version; or back up and delete the PDB; or use the Cordon behavior. Force upgrade is the last resort.

Operation couldn't be completed because it results in exceeding approved <SKU-family> Cores quota. ... Current Limit: A, Current Usage: B, Additional Required: C, (Minimum) New Limit Required: D.

Cause: the vCPUs needed for the surge node exceed the regional or VM family quota (QuotaExceeded).

az vm list-usage -l $LOC -o table

Fix: lower maxSurge or use maxUnavailable; submit a “Service and subscription limits (quotas)” request in the portal; then reconcile with az aks update or az aks nodepool update.

Rejected before upgrade: a PDB with maxUnavailable 0 was detected (UnsatisfiablePDB; check the exact message)

Cause: the AKS pre-check found a PDB that will certainly block the drain.

Fix: change maxUnavailable to ≥ 1 (or make minAvailable less than the replica count), then retry.

SKUNotAvailable / AllocationFailed / OverconstrainedAllocationRequest (surge phase)

Cause: insufficient capacity in the region or availability zone (common with GPU and special SKUs), or maxSurge is set too high.

Fix: lower maxSurge and use maxUnavailable. For security patches, use the node OS security patch channel, which does not need surge. Or change the SKU or availability zone.

The node has the label kubernetes.azure.com/upgrade-status=Quarantined, so Pods cannot be scheduled onto it

Cause: the Cordon behavior quarantined a node that could not be drained.

kubectl get nodes --show-labels | grep Quarantined

Fix: resolve the PDB → kubectl label nodes <node> kubernetes.azure.com/upgrade-status- → optionally az aks nodepool delete-machines → az aks update or az aks nodepool scale to return to the desired size.

Command-line exercises
1. Find all PDBs with ALLOWED DISRUPTIONS of 0 (output namespace and name).
kubectl get pdb -A -o json | jq -r '.items[] | select(.status.disruptionsAllowed==0) | "\(.metadata.namespace)/\(.metadata.name)"'
2. Configure the userpool upgrade to isolate nodes that cannot be drained, tolerating up to 2, with a 20-minute drain timeout.
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool --undrainable-node-behavior Cordon --max-blocked-nodes 2 --drain-timeout 20
Scenario analysis
An upgrade to a new version failed. The cluster is Failed, and the error is a PDB block. The business team refuses to change the PDB and does not accept any interruption. Propose a plan.

Force upgrade is not an option, because it would bypass the PDB and cause an outage. Plan: temporarily increase the replica count of that workload so ALLOWED DISRUPTIONS ≥ 1 (the PDB rule stays the same), or enable automatic PDB management (preview) to achieve the same effect. Also set the Cordon behavior on the node pool as a fallback, then retry az aks upgrade to the same target version. Afterwards, review the PDB with the business team: a single replica with minAvailable 1 can never be satisfied under any maintenance, so it should be changed to multiple replicas.

Verified teaching videos

▶
Upgrade Issues 101 with Mosbah Majed: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
AKS official channel · English · Classifying and handling upgrade failures
▶
Troubleshooting AKS Scaling Issues with Jameson Hearn: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · quota and capacity issues in the surge and scale-out phase

Official documentation

Video storyboard (about 90 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: three old nodes, and a new surge node lights up.
Narration: the upgrade creates new nodes first, then drains the old nodes one at a time.
Shot 2 · 20–45s
Visual: an eviction request hits the API server, and the PDB gatekeeper raises a 429 sign.
Narration: draining uses the Eviction API. When the PDB does not allow disruption, it returns 429, and AKS keeps retrying until the timeout.
Shot 3 · 45–70s
Visual: three branches: Schedule, Cordon, and Failed. On the Cordon branch, the node gets labeled Quarantined.
Narration: with Cordon set, a blocked node is quarantined, the upgrade keeps going, and you deal with the node afterwards.
Shot 4 · 70–90s
Visual: the quota table highlights Current Limit, Usage, and Additional Required in turn.
Narration: surge nodes also need quota. Read the four numbers in the error, lower surge or request a quota increase, then retry the same version.
or score ≥ 70% on the quiz

Module 7 · Identity and permission failures: Entra, Workload Identity, ACR pulls

42:00 – 50:00 · Three identity types, three token paths: people (kubelogin → Entra → Azure RBAC), workloads (SA token → federated credential → access token), and nodes (kubelet identity → ACR)
8 minutesAADSTS70021 · 401 · 403ABAC repository permissions: attach-acr does not assign Repository Reader★★★★★
Learning goals
  • Tell the three identity paths apart. When you see a 401, 403, or AADSTS error, know which path and which step is involved.
  • Troubleshoot access to clusters integrated with Entra: kubelogin, Azure RBAC Forbidden errors, and admin credentials being unavailable under --disable-local-accounts.
  • Troubleshoot Workload Identity: the azure.workload.identity/use: "true" label, the service account annotation, and the issuer, subject, and audience of the federated credential; AADSTS70021 and AADSTS90061.
  • Troubleshoot ACR pulls: 401 Unauthorized (missing AcrPull or, on ABAC registries, Container Registry Repository Reader; kubelet identity removed; cached credentials), 403 Forbidden (private DNS link, firewall allow list), and i/o timeout (private link peering). Use az aks check-acr.
Prerequisite: identity and security in Hour 3. Importance: ★★★★★

What: the three identity paths

PathWhoWhere the token comes fromWhere authorization happensCommon errors
People → API serverEngineers / pipelineskubelogin gets a token from Entra (audience is the AKS server application)Kubernetes RBAC or Azure RBAC for KubernetesForbidden ... User does not have access to the resource in Azure (check the exact message), kubelogin not installed
Workload → Azure resourcesPod (service account)Projected SA token (issued by the cluster OIDC issuer) → exchanged with Entra (client assertion) → access tokenRole of the managed identity or application on the target resourceAADSTS70021, AADSTS90061, 403 from the target resource
Node → ACRkubelet identity (managed identity)The acr-credential-provider on the node gets a token from IMDS → ACR token exchangeAcrPull on ACR (non-ABAC) or Container Registry Repository Reader (ABAC)401 Unauthorized, 403 Forbidden, i/o timeout

Why: the four checkpoints of Workload Identity

  1. Webhook injection: the Pod must carry the label azure.workload.identity/use: "true" (since v1.0.0 the webhook only handles Pods with this label). Otherwise AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_AUTHORITY_HOST, and the projected token volume are not injected. The service account needs the annotation azure.workload.identity/client-id.
  2. Issuer: the federated credential's issuer must match the cluster's oidcIssuerProfile.issuerUrl exactly. The official troubleshooting guide says the most common cause is a missing trailing /. A mismatch gives AADSTS70021: No matching federated identity record found for presented assertion.
  3. Subject: must be system:serviceaccount:<namespace>:<service-account>. A single wrong character also causes AADSTS70021. If you rename the namespace or service account, the old federated credential stops working. The audience defaults to api://AzureADTokenExchange.
  4. Authorization: the token exchange succeeded, but the managed identity has no role on Key Vault or Storage, so the target service returns 403 (ForbiddenByRbac in Key Vault RBAC mode; check the exact message). Also, if the OIDC issuer endpoint is unreachable, you get AADSTS90061: Request to External OIDC endpoint failed.; on AKS, first try az aks update to reconcile. A newly created federated credential has a propagation delay, so wait a few minutes before retrying.

How: the three stages of an ACR pull

Every pull goes through: ① authentication and authorization (failures appear as 401 Unauthorized, 403 Forbidden, or failed to fetch anonymous token); ② the registry login endpoint <registry>.azurecr.io (DNS, private endpoint, or firewall problems appear as i/o timeout or a TLS handshake timeout); ③ data endpoints (*.blob.core.windows.net or <registry>.<region>.data.azurecr.io) for downloading image layers. Note: an unauthenticated curl https://<registry>.azurecr.io/v2/ returning 401 is normal; it means the login endpoint is reachable.

  • Causes of 401: the kubelet identity has no AcrPull. Registries with ABAC enabled need Container Registry Repository Reader, and az aks update --attach-acr does not assign this role, so you must assign it manually. The kubelet identity was removed from the VMSS (fixed by reconciling with az aks update). The service principal secret has expired. The image name is wrong (AKS always tries an anonymous pull first, so a wrong name can also appear as 401). The architecture does not match (ARM64 vs. AMD64). The node cache was not refreshed after a credential change (perform a node image upgrade if needed).
  • Causes of 403 (network access): the private DNS zone privatelink.azurecr.io for the ACR private endpoint is not linked to the AKS VNet; or ACR public access is restricted to “selected networks” and the AKS outbound public IP is not in the allow list.

When: which tool to use

SymptomTool
ImagePullBackOffRaw Events from kubectl describe pod → az aks check-acr -g RG -n CLUSTER --acr <acr>.azurecr.io → az acr check-health
SDK authentication fails inside the PodAADSTS code in the Pod logs → az identity federated-credential list → compare with az aks show --query oidcIssuerProfile.issuerUrl
kubectl Forbiddenkubectl auth can-i → az role assignment list --scope <cluster or namespace ID>
Common misconceptions ① “401 means no permission.” It can also be a wrong image name or an architecture mismatch. ② “403 means the wrong role.” A 403 from ACR is usually a network access issue (private DNS, firewall). ③ “attach-acr is always enough.” ABAC registries need Repository Reader, which attach-acr does not assign. ④ “If the Workload Identity environment variables are missing, it's an SDK problem.” First check whether the Pod has the azure.workload.identity/use label.

Workload Identity token exchange and failure points

Pod + SA wi-saLabel use: "true"① Webhook injection Projected SA tokeniss = cluster OIDC issuersub = system:serviceaccount:… Microsoft Entra ID② Match federated credential iss/sub/aud③ Fetch OIDC public keys to verify the signature Access tokenid-myapp Key Vault④ RBAC ① failed: no AZURE_* environment variablesSDK falls back to other credentials→ add the label, recreate the Pod ② failed: AADSTS70021Trailing / in the issuer, or subject mismatch ③ failed: AADSTS90061OIDC endpoint unreachable→ az aks update ④ failed: 403Identity lacks a Key Vault role
Figure 7-1 Each of the four checkpoints produces its own distinctive error. The error tells you which step failed.

Three ACR pull stages mapped to errors

kubeletacr-credential-provider→ IMDS (kubelet identity) ① Authentication and authorizationAcrPull / Repository Reader ② Login endpoint<acr>.azurecr.io ③ Data endpoints*.data.azurecr.io 401 Unauthorizedfailed to fetch oauth token 403 Forbidden (private DNS / firewall)i/o timeout (private link peering) Layer download i/o timeoutconnection reset context deadline exceeded(IMDS unreachable / cache) az aks check-acr runs a canipull check inside the cluster, covering both stages ① and ②
Figure 7-2 ACR pull: authenticate first, then the login endpoint, and finally the data endpoints. The error type indicates the stage.

Token exchange failure injector

Choose a path and an injected fault, then play. Step by step, it shows what each component actually does (the webhook modifies the Pod spec, the kubelet writes the projected token, the SDK calls /oauth2/v2.0/token with client_assertion, Entra validates, the target service authorizes, …). It stops at the failure and shows the raw error and the fix command.

Core commands and parameters

CommandPurposeKey parameters / notes
az aks check-acrVerify from the cluster whether images can be pulled from ACR--acr <acr>.azurecr.io; can add --node-name
az aks show --query identityProfile.kubeletidentitykubelet identityCompare with az vmss identity show
az role assignment list --scope <ACR ID>Roles on ACRAcrPull / Container Registry Repository Reader
az aks show --query oidcIssuerProfile.issuerUrlCluster OIDC issuerCompare character by character with the federated credential
az identity federated-credential listFederated credential--identity-name id-myapp -g $RG
kubectl auth can-iCheck the caller's permissions--list -n NS, --as
kubelogin convert-kubeconfig -l azurecliNon-interactive login modePipelines commonly use -l workloadidentity / spn
# ACR
az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
KUBELET_ID=$(az aks show -g $RG -n $CLUSTER --query identityProfile.kubeletidentity.objectId -o tsv)
az role assignment list --assignee $KUBELET_ID --scope $(az acr show -n $ACR --query id -o tsv) -o table
[2026-11-15T09:40:12Z] Checking host name resolution (acraks12345.azurecr.io): SUCCEEDED
[2026-11-15T09:40:12Z] Canonical name for ACR (acraks12345.azurecr.io): r0123cnc-1.canadacentral.cloudapp.azure.com.
[2026-11-15T09:40:12Z] ACR location: canadacentral
[2026-11-15T09:40:13Z] Validating managed identity existance: SUCCEEDED
[2026-11-15T09:40:13Z] Validating image pull permission: SUCCEEDED
[2026-11-15T09:40:13Z]
Your cluster can pull images from acraks12345.azurecr.io!
Principal     Role     Scope
------------  -------  ----------------------------------------------
1a2b…         AcrPull  /subscriptions/…/registries/acraks12345

How to verify: if you see “Your cluster can pull images from …”, stages ① and ② are working. If it still fails, check the data endpoints or the image name and architecture. Common errors: when the system node pool architecture differs from the image, check-acr itself may report exec /canipull: exec format error (per the official notes).

# Workload Identity
az aks show -g $RG -n $CLUSTER --query "{issuer:oidcIssuerProfile.issuerUrl, wi:securityProfile.workloadIdentity.enabled}" -o table
az identity federated-credential list --identity-name id-myapp -g $RG --query "[].{name:name,issuer:issuer,subject:subject,aud:audiences[0]}" -o table
kubectl -n myapp get sa myapp-sa -o jsonpath='{.metadata.annotations}{"\n"}'
kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].metadata.labels}{"\n"}'
kubectl -n myapp exec deploy/myapp -- env | grep ^AZURE_
Issuer                                                                        Wi
----------------------------------------------------------------------------  ----
https://canadacentral.oic.prod-aks.azure.com/<tenant-id>/<guid>/         True
Name          Issuer                                                         Subject                                   Aud
------------  -------------------------------------------------------------  ----------------------------------------  -------------------------
fic-myapp     https://canadacentral.oic.prod-aks.azure.com/<tenant>/<guid>/  system:serviceaccount:myapp:myapp-sa      api://AzureADTokenExchange
AZURE_CLIENT_ID=…
AZURE_TENANT_ID=…
AZURE_FEDERATED_TOKEN_FILE=/var/run/secrets/azure/tokens/azure-identity-token
AZURE_AUTHORITY_HOST=https://login.microsoftonline.com/
# Entra / Azure RBAC (people)
kubectl auth can-i list pods -n myapp
az aks show -g $RG -n $CLUSTER --query "{aad:aadProfile.managed, azureRbac:aadProfile.enableAzureRbac, localDisabled:disableLocalAccounts}" -o table
az role assignment list --assignee $(az ad signed-in-user show --query id -o tsv) --scope $(az aks show -g $RG -n $CLUSTER --query id -o tsv) -o table

Production use: encode “the issuer must match the cluster, and the subject is generated as namespace:SA” in IaC (Terraform or Bicep referencing cluster outputs directly), so copy-paste mistakes are eliminated at the source.

Lab 7: Reproduce and fix ACR 401 and Workload Identity failures (about 10 minutes)

Create a second, unauthorized ACR and push an image:
ACR2=acraks2$RANDOM
az acr create -g $RG -n $ACR2 --sku Basic
az acr import -n $ACR2 --source $ACR.azurecr.io/myapp:1.0 --image myapp:1.0
kubectl -n myapp create deployment noauth --image=$ACR2.azurecr.io/myapp:1.0
sleep 30; kubectl -n myapp describe pod -l app=noauth | grep -A2 Failed | head -6
Warning  Failed  ... Failed to pull image "acraks2xxxx.azurecr.io/myapp:1.0": failed to pull and unpack image "acraks2xxxx.azurecr.io/myapp:1.0": failed to resolve reference "acraks2xxxx.azurecr.io/myapp:1.0": failed to authorize: failed to fetch anonymous token: unexpected status from GET request to https://acraks2xxxx.azurecr.io/oauth2/token?scope=repository%3Amyapp%3Apull&service=acraks2xxxx.azurecr.io: 401 Unauthorized
Diagnose and fix:
az aks check-acr -g $RG -n $CLUSTER --acr $ACR2.azurecr.io
az aks update -g $RG -n $CLUSTER --attach-acr $ACR2
kubectl -n myapp rollout restart deploy/noauth; kubectl -n myapp rollout status deploy/noauth

Role assignment propagation and node credential caching can take a few minutes.

Workload Identity missing label (f6):
./fault-inject.sh inject f6
kubectl -n fault-lab wait --for=condition=Ready pod/wi-test --timeout=120s
kubectl -n fault-lab exec wi-test -- sh -c 'env | grep ^AZURE_ || echo "No AZURE_* variables"'
No AZURE_* variables
kubectl -n fault-lab delete pod wi-test
kubectl -n fault-lab run wi-test --image=mcr.microsoft.com/azure-cli --labels=azure.workload.identity/use=true \
  --overrides='{"spec":{"serviceAccountName":"wi-sa"}}' -- sleep 3600
kubectl -n fault-lab wait --for=condition=Ready pod/wi-test --timeout=120s
kubectl -n fault-lab exec wi-test -- sh -c 'env | grep ^AZURE_'

The variables are now injected. Because the annotation's client-id is an all-zero placeholder and no federated credential exists, running az login --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)" --service-principal -u $AZURE_CLIENT_ID -t $AZURE_TENANT_ID inside the Pod will return an AADSTS error (check the exact code). Use the id-myapp created in Hour 3 and create a federated credential with the correct subject system:serviceaccount:fault-lab:wi-sa, then try again.

Cleanup:
kubectl -n myapp delete deploy noauth
az aks update -g $RG -n $CLUSTER --detach-acr $ACR2
az acr delete -n $ACR2 --yes
./fault-inject.sh restore f6

Cost: Basic ACR is about US$0.17/day (check the official pricing). Permissions: assigning AcrPull requires Owner or User Access Administrator.

Case 1: all 401s after migrating to an ABAC registry

Problem: the security team switched ACR to ABAC repository permissions mode, and the next day every new Pod hit ImagePullBackOff with 401. What happened: AcrPull no longer applies on ABAC registries, and --attach-acr does not assign Container Registry Repository Reader. Configuration: manually assign Repository Reader to the kubelet identity (it can be restricted per repository with conditions). Limitation: node credential cache refresh takes a few minutes; if it takes longer than 5 minutes, perform a node image upgrade.

Case 2: Key Vault access fails after a namespace rename

Problem: the payments namespace was renamed to payments-v2, and the SDK reports AADSTS70021. What happened: the federated credential subject is still system:serviceaccount:payments:api. Configuration: add a federated credential whose subject uses the new namespace (one identity can have several; check the documented limit), verify it, then delete the old one. Limitation: the new credential has a propagation delay.

Case 3: private ACR in another VNet, pull returns 403

Problem: the ACR private endpoint is in the hub VNet, AKS is in the spoke VNet, and pulls return 403. What happened: nslookup <acr>.azurecr.io on the node resolves to a public IP. The private DNS zone privatelink.azurecr.io is not linked to the spoke VNet. Configuration: add the VNet link (with custom DNS, configure conditional forwarding on the DNS server). Limitation: the data endpoints also need private DNS records.

Common errors and fixes

failed to authorize: failed to fetch oauth token: unexpected status: 401 Unauthorized

Cause: the kubelet identity lacks AcrPull or Repository Reader; the service principal has expired; the kubelet identity was removed from the VMSS; the image name is wrong; or the credential cache is stale.

az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
az aks show -g $RG -n $CLUSTER --query identityProfile.kubeletidentity
az vmss identity show -g $NODE_RG -n $VMSS

Fix: az aks update --attach-acr (non-ABAC), or assign Repository Reader manually (ABAC). If the identity was removed, reconcile with az aks update. For cache issues, wait, or run az aks nodepool upgrade --node-image-only.

failed to authorize: failed to fetch anonymous token: unexpected status: 403 Forbidden

Cause: network access was denied: the private DNS zone is not linked to the AKS VNet, or the ACR firewall does not allow the AKS outbound public IP.

az network private-dns link vnet list -g <dns-rg> -z privatelink.azurecr.io -o table
az acr network-rule list -n $ACR

Fix: add the VNet link, or az acr network-rule add -n $ACR --ip-address <AKS outbound IP>.

AADSTS70021: No matching federated identity record found for presented assertion.

Cause: the federated credential issuer (common: missing trailing /) or subject does not match the token.

az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv
az identity federated-credential list --identity-name id-myapp -g $RG -o table

Fix: az identity federated-credential create --identity-name id-myapp -g $RG -n fic-myapp --issuer "$(az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv)" --subject system:serviceaccount:myapp:myapp-sa --audiences api://AzureADTokenExchange

AADSTS90061: Request to External OIDC endpoint failed.

Cause: the cluster OIDC issuer's discovery document or JWKS cannot be reached from the internet.

ISS=$(az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv)
curl -s ${ISS}.well-known/openid-configuration | head -c 300; echo
curl -s ${ISS}openid/v1/jwks | head -c 200

Fix: reconcile with az aks update -g $RG -n $CLUSTER; if it still fails, open a support ticket.

Error from server (Forbidden): pods is forbidden: User "user@contoso.com" cannot list resource "pods" in API group "" in the namespace "myapp": User does not have access to the resource in Azure. Update role assignment to allow access. (check the exact message)

Cause: Azure RBAC for Kubernetes is enabled, but the user has no matching Azure Kubernetes Service RBAC role (at cluster or namespace scope).

az role assignment create --assignee user@contoso.com --role "Azure Kubernetes Service RBAC Reader" \
  --scope $(az aks show -g $RG -n $CLUSTER --query id -o tsv)/namespaces/myapp

Fix: assign a namespace-scoped role following least privilege. Role assignment propagation takes a few minutes.

az aks get-credentials --admin fails: Getting static credential is not allowed because this cluster is set to disable local accounts. (check the exact message)

Cause: the cluster has --disable-local-accounts enabled, so the static admin credentials are unavailable. This is the intended security setting.

Fix: access with an Entra identity and Azure RBAC (az aks get-credentials without --admin, together with kubelogin). The break-glass plan should be set up in advance as an emergency access group in Entra.

Command-line exercises
1. Verify that aks-lab can pull images from $ACR.
az aks check-acr -g rg-aks-lab -n aks-lab --acr $ACR.azurecr.io
2. Create a federated credential for id-myapp whose issuer exactly matches the cluster issuer and whose subject is myapp:myapp-sa.
az identity federated-credential create --identity-name id-myapp -g rg-aks-lab -n fic-myapp \
  --issuer "$(az aks show -g rg-aks-lab -n aks-lab --query oidcIssuerProfile.issuerUrl -o tsv)" \
  --subject system:serviceaccount:myapp:myapp-sa --audiences api://AzureADTokenExchange
Scenario analysis
A newly deployed Pod fails to access Key Vault. The logs show the SDK tried ManagedIdentityCredential (IMDS) instead of WorkloadIdentityCredential, and it finally returns 403. Analyze the cause.

The SDK did not use WorkloadIdentityCredential, which means the Pod has no AZURE_FEDERATED_TOKEN_FILE or similar variables: the webhook did not inject them. The most common cause is that the Pod template is missing the azure.workload.identity/use: "true" label (or the service account is not specified). The SDK then falls back to IMDS and gets a token for the node's kubelet identity, which has no permission on Key Vault, so the result is 403. Fix: add the label to the Pod template, confirm serviceAccountName and the service account's client-id annotation, then perform a rolling restart.

Verified teaching videos

▶
AKS Workload Identity - Quick Tutorial — Azure Kubernetes Service (AKS)
AKS official channel · English · key points of Workload Identity setup (check each step against this when troubleshooting)
▶
Diagnose & Solve with Andrew Scobie: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · identity and pull-related checks in the portal diagnostics

No verified official video was found that specifically covers ACR 401/403 troubleshooting. Please use the storyboard below.

Official documentation

Video storyboard (about 90 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: three colored lines (people, workloads, and nodes) lead to the API server, Key Vault, and ACR respectively.
Narration: AKS has three kinds of identity, and each has its own token path and its own errors.
Shot 2 · 20–45s
Visual: the service account token presents two cards, iss and sub, to Entra. Entra compares them with the federated credential, notices a missing trailing slash, and stamps AADSTS70021.
Narration: the issuer and subject must match exactly, character for character.
Shot 3 · 45–70s
Visual: the kubelet goes to ACR for an image, and the gatekeeper raises 401 and 403 signs.
Narration: a 401 is usually a role or name problem; a 403 is usually a network access problem.
Shot 4 · 70–90s
Visual: a terminal runs az aks check-acr, and the output says Your cluster can pull images.
Narration: use check-acr in one command to verify the full path from the cluster to the registry.
or score ≥ 70% on the quiz

Module 8 · Mixed fault challenge

50:00 – 60:00 · You are not told what is broken. Collect evidence for 90 seconds, identify the layer, then the root cause. This brings the first 7 modules together into muscle memory.
10 minFault-injection script (random mode)Timed diagnosis game + troubleshooting tree★★★★★
Learning goals
  • Use a “90-second evidence collection” script to get a global view quickly, even when you don't yet know the fault type.
  • In the fault blind box, pick the fewest diagnostic commands for a random fault, then state the root cause and the fix command.
  • Use an interactive troubleshooting decision tree to cover every AKS fault type in this hour.
Prerequisites: Modules 1–7. Importance: ★★★★★

What: the five-step method for blind-box diagnosis

  1. Scope (30 seconds): who reported it, when it started, the blast radius (one app / one node pool / the whole cluster), and recent changes (deployments, GitOps commits, Azure operations, network changes).
  2. Global snapshot (60 seconds): az aks show state, node Ready status, non-Running Pods, Warning events, and Azure operations that failed in the last 24 hours.
  3. Locate the layer: classify the issue using the six-layer model from Module 1.
  4. Evidence chain: in that layer, collect 2–3 pieces of evidence that corroborate each other (for example, raw Events + component logs + config diff).
  5. Fix and verify: apply the smallest change that fixes it, confirm the symptom is gone, then write down the root cause and prevention steps (alerts, policies, runbook).

Why: why you collect evidence before you act

AKS has auto-repair, auto-scaling, and reconciliation loops. Much of the evidence disappears within minutes: nodes are reimaged, Pods are recreated, and events are kept for only about an hour by default. Save the snapshot before you restart or roll back anything.

How: common “symptom → layer → module” matches

Symptom keywordsLayerReview
NotReady, Kubelet stopped posting node status, exit status=50Node / outboundModules 2, 4
InsufficientSubnetSize, SubnetIsFullARM / network planningModule 3
Intermittent i/o timeout to a single external target onlyNetwork (SNAT)Module 4
EXTERNAL-IP pending, probe 0%, empty Endpoints, 404/502, could not resolveNetwork (LB / ingress / DNS)Module 5
UpgradeFailed, Too Many Requests, QuotaExceededARM / upgradeModule 6
401, 403, AADSTS70021, ForbiddenIdentityModule 7
Pending with Insufficient cpu/memoryPod / capacityK8s course + Hour 4

When: when to escalate to a support ticket

  • Control plane unavailable (Standard/Premium tiers have an SLA), managed components unhealthy, auto-repair repeatedly failing, or platform error codes (such as InternalServerError) that keep appearing.
  • Collect before you open a ticket: the cluster resource ID, the time window (UTC), the operation correlation ID (the correlationId in the activity log), and the output of this page's script.
Common misconceptions ① “Restart first, think later.” This wipes out evidence and can hide the real root cause (for example SNAT or PDB). ② “A fault has only one cause.” Blind boxes and production can both stack multiple faults (for example, a DNS fault makes readiness fail, which leaves Endpoints empty). ③ “Once it's fixed, it's over.” A fix with no prevention step just postpones the next incident.

Blind-box diagnosis workflow

① DefineScope · time · changes ② Snapshotaks-triage.sh ③ Locate layerSix-layer model ④ Evidence chain2–3 corroborating ⑤ Fix · verify · preventAlerts · policies · runbook Contradicting evidence → back to locate layer
Figure 8-1: the five-step method. Snapshot first, and return to locating the layer when the evidence contradicts itself

Fault-stacking example: three symptoms on one chain

Root cause: NetworkPolicyEgress to 53 denied Redis resolution fails/healthz returns 500 readiness failsEndpoints empty Users see timeouts“Is the LB broken?”
Figure 8-2: user symptoms are on the far right and the root cause is on the far left. Trace back along the dependency chain.

Fault blind box: timed diagnosis game

Click “Draw a blind box” to get an alert description. Each diagnostic command costs time, deducted from your 10-minute budget. After it runs, you see realistic example output. When you think you have enough evidence, pick the root cause. Correct answers in less time score higher. Your score is saved in this browser.

Not drawn yet.
Diagnostic commands (click to run):
$ # output appears here
Your conclusion: what is the root cause?

90-second evidence collection script aks-triage.sh

SectionWhat it collectsLayer
ARMCluster / node pool status, failed operations in the last 24 hours①
NodeNode status, conditions, taints, Quarantined label, auto-repair events③
WorkloadsNon-Running Pods, Warning events, PDBs with ALLOWED=0④⑥
NetworkServices with no endpoints, pending LBs, CoreDNS status and errors, coredns-custom, outbound rules⑤
#!/usr/bin/env bash
# Read-only: collect an AKS global evidence snapshot, write to triage-TIMESTAMP.txt
RG=${RG:-rg-aks-lab}; CLUSTER=${CLUSTER:-aks-lab}
OUT=triage-$(date -u +%Y%m%dT%H%M%SZ).txt
exec > >(tee "$OUT") 2>&1
sec(){ echo; echo "===== $* ====="; }
sec "ARM state"
az aks show -g $RG -n $CLUSTER --query "{state:provisioningState,power:powerState.code,ver:currentKubernetesVersion,outbound:networkProfile.outboundType}" -o table
az aks nodepool list -g $RG --cluster-name $CLUSTER --query "[].{pool:name,state:provisioningState,ver:currentOrchestratorVersion,count:count}" -o table
az monitor activity-log list -g $RG --offset 24h --status Failed --query "[].{t:eventTimestamp,op:operationName.localizedValue}" -o table
sec "Nodes"
kubectl get nodes -o wide -L kubernetes.azure.com/upgrade-status
kubectl get nodes -o custom-columns=NAME:.metadata.name,READY:.status.conditions[?(@.type==\"Ready\")].status,TAINTS:.spec.taints[*].key
kubectl get events -A --field-selector involvedObject.kind=Node --sort-by=.lastTimestamp | tail -15
sec "Workloads"
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded -o wide
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail -30
kubectl get pdb -A
sec "Network"
kubectl get svc -A | grep -E 'LoadBalancer'
for s in $(kubectl get svc -A -o jsonpath='{range .items[?(@.spec.selector)]}{.metadata.namespace}/{.metadata.name}{" "}{end}'); do
  ns=${s%/*}; n=${s#*/}
  c=$(kubectl -n $ns get endpointslices -l kubernetes.io/service-name=$n -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{" "}{end}' | wc -w)
  [[ $c -eq 0 ]] && echo "No endpoints: $s"
done
kubectl -n kube-system get pod -l k8s-app=kube-dns -o wide
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=20 2>/dev/null | grep -iE 'error|timeout' | tail -10
kubectl -n kube-system get cm coredns-custom -o jsonpath='{.data}' 2>/dev/null; echo
NODE_RG=$(az aks show -g $RG -n $CLUSTER --query nodeResourceGroup -o tsv)
az network lb outbound-rule list -g $NODE_RG --lb-name kubernetes -o table 2>/dev/null
echo; echo "Snapshot saved to $OUT"
chmod +x aks-triage.sh && ./aks-triage.sh | less

How to verify: every section in the file has output. A section without permission shows AuthorizationFailed, which is itself a clue. Common error: on a private cluster run from outside the VNet, the kubectl sections fail. Instead, use az aks command invoke --command "$(sed -n '/===== Nodes/,/===== Network/p' aks-triage.sh)", or upload the script with --file and run it (watch the 512 KB output limit). Production use: make it the first step of the on-call runbook, and attach the output to the incident ticket.

Lab 8: 3 random faults injected; locate all of them within 15 minutes (10 minutes in class)

Partner injects (or you inject without looking at the answers):
./fault-inject.sh random 3
3 faults have been injected at random (the answers are in /home/<you>/.aks-fault-state.random, so don't look yet)
Collect a snapshot:
./aks-triage.sh > /dev/null; ls -t triage-*.txt | head -1
Locate each fault: for each one, write down: symptom → layer → evidence (command + key output) → root cause → fix command. You can use the decision tree on the Troubleshooting page to help.
Fix and verify: fix each fault with your own fix command (not restore), then run aks-triage.sh again to confirm that the Warning events and endpoint-less Services are gone, and that curl http://$IP/healthz returns 200.
Check answers and clean up:
cat ~/.aks-fault-state.random
./fault-inject.sh restore-all

Scoring guide: +3 points for each correct root cause, +1 for complete evidence, +1 for a correct fix command; 15 points total. Cost: no extra resources.

Case 1: the “LB is broken” was really DNS

Problem: the business reported that public access was timing out, and the team first suspected the load balancer. Approach: the snapshot showed the myapp Service had no endpoints; Pod readiness was failing; Pod logs showed Redis resolution failures; and a newly merged NetworkPolicy default-denied egress. Fix: add “allow port 53 to kube-dns” to the baseline policy for all namespaces. Limitation: policy engine differences (Azure/Cilium/Calico) can affect FQDN-based rules.

Case 2: a failed upgrade plus SNAT exhaustion

Problem: an upgrade failed (PDB). The on-call engineer forced it with force upgrade. Many Pods were then recreated at once, cold starts opened large numbers of outbound connections, and SNAT exhaustion followed. Approach: the review showed the two faults were a causal chain. Fix: switch to Cordon behavior and set explicit SNAT ports; forbid force upgrade without review. Limitation: force upgrade must be listed as a high-risk operation in the change process.

Case 3: evidence lost

Problem: a node went NotReady. Auto-repair reimaged it and it recovered, but the root cause could not be found. Approach: enable Syslog collection in Container Insights and the control plane diagnostic logs. The next time it recurred, pthread_create failed was captured. Fix: see Hour 6 on observability. Limitation: log collection costs money, so choose tables and retention periods based on need.

Interactive troubleshooting decision tree (covers every fault type in this hour)

Step through the choices from a symptom. At the end you get the diagnosis, the evidence commands, and the fix.

Command-line exercises
1. List all Pods that are not in Running or Succeeded status.
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded
2. List the 30 most recent Warning events in time order.
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail -30
Scenario analysis
Alert: myapp 5xx spike. Snapshot shows: all nodes Ready; myapp 3/3 Running but 0/3 Ready; Warning event “Readiness probe failed: HTTP probe failed with statuscode: 500”; CoreDNS logs have no errors; Redis Pod Pending, with event “0/3 nodes are available: 3 Insufficient memory”. What is the root cause and the fix?

Dependency chain: Redis can't be scheduled (memory requests too low, or the node is filled by Pods with large requests) → myapp /healthz depends on Redis and returns 500 → readiness fails → Endpoints empty → 5xx. Check the Allocated resources in describe node to find the large consumers (such as the hog in blind box f7). Fix: delete or reduce the abnormal requests, or scale out the node pool. Prevention: ResourceQuota/LimitRange, a PriorityClass for Redis, and a /healthz that separates liveness from readiness on dependencies.

Verified teaching videos

▶
Diagnose & Solve with Andrew Scobie: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · good for reviewing the “first-step tools” for blind boxes
▶
AKS MCP Server with Julia Yin: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · approaches to AI-assisted diagnosis (preview feature; conclusions need human review)
▶
Troubleshooting OOM failures with Claudio Godoy: AKS Troubleshooting Series: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · evidence chains for resource-related faults

Official documentation

Video storyboard (about 90 seconds)

This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: a gift box shakes, then opens, and a red alert pops out: “5xx spike.”
Narration: A real fault won't tell you which layer it's in.
Shot 2 · 15–40s
Visual: a terminal runs aks-triage.sh. Four sections scroll by, with key lines highlighted.
Narration: Collect a 90-second global snapshot first, then act. That way, auto-repair won't wipe out the evidence.
Shot 3 · 40–70s
Visual: four boxes connected from right to left: user timeout, empty endpoints, readiness failure, DNS blocked by policy.
Narration: Trace the dependency chain from the symptom back to the root cause. Most incidents are a chain of cause and effect.
Shot 4 · 70–90s
Visual: fix command → verify 200 → write the runbook and alerts.
Narration: After a fix, always verify it, and write down the prevention steps.
or score ≥ 70% on the quiz

Command cheat sheet

Deep troubleshooting: tools, nodes, IPs, SNAT, LB/DNS, upgrades, identity
RG=rg-aks-lab · CLUSTER=aks-lab

① Diagnosis entry

az aks show -g $RG -n $CLUSTER --query "{s:provisioningState,p:powerState.code}" -o table
az monitor activity-log list -g $RG --offset 24h --status Failed -o table
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp
az aks command invoke -g $RG -n $CLUSTER --command "kubectl get pods -A"
kubectl debug node/NODE -it --image=mcr.microsoft.com/azurelinux/busybox:1.36
az vmss run-command invoke -g $NODE_RG -n $VMSS --instance-id 0 \
  --command-id RunShellScript --scripts "systemctl is-active kubelet"

② Node NotReady

kubectl describe node NODE | sed -n '/Conditions:/,/Addresses:/p'
kubectl get lease -n kube-node-lease -o custom-columns=N:.metadata.name,R:.spec.renewTime
kubectl get events -A --field-selector involvedObject.kind=Node | grep -Ei 'reboot|reimage|redeploy'
journalctl -u kubelet -u containerd --since "30 min ago"   # on the node
az vmss restart|reimage -g $NODE_RG -n $VMSS --instance-ids 0
az aks nodepool delete-machines -g $RG --cluster-name $CLUSTER -n POOL --machine-names NODE

③ IP / subnet

az aks nodepool list -g $RG --cluster-name $CLUSTER \
  --query "[].{n:name,c:count,max:maxCount,pods:maxPods,surge:upgradeSettings.maxSurge}" -o table
az network vnet subnet show --ids $SUBNET_ID --query "{p:addressPrefix,used:length(ipConfigurations)}"
# Azure CNI (flat): (nodes + surge) × (1 + maxPods) ≤ 2^(32-prefix) - 5 - other
az aks nodepool add ... --vnet-subnet-id $NEW_SUBNET
az aks nodepool update ... --max-surge 0 --max-unavailable 1

④ SNAT / outbound

az network lb outbound-rule list -g $NODE_RG --lb-name kubernetes -o table
az monitor metrics list --resource $LB_ID --metric SnatConnectionCount \
  --filter "ConnectionState eq 'failed'" --aggregation Total
# 64,000 × IP count ÷ ports per node ≥ max nodes + surge (ports are multiples of 8)
az aks update -g $RG -n $CLUSTER --load-balancer-managed-outbound-ip-count 2 \
  --load-balancer-outbound-ports 2000 --load-balancer-idle-timeout 4
curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/   # CSE check (exit 50)

⑤ LB / ingress / DNS

kubectl describe svc S | sed -n '/Events/,$p'
kubectl get endpointslices -l kubernetes.io/service-name=S
az network lb probe list -g $NODE_RG --lb-name kubernetes -o table
kubectl annotate svc S service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path=/healthz
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=30
kubectl -n kube-system get cm coredns-custom -o yaml
dig +udp @DNS mcr.microsoft.com; dig +tcp @DNS mcr.microsoft.com

⑥ Upgrade failure

kubectl get pdb -A
kubectl get events -A | grep -i drain
az vm list-usage -l $LOC -o table
az aks nodepool update ... --undrainable-node-behavior Cordon --max-blocked-nodes 2 --drain-timeout 30
kubectl label nodes NODE kubernetes.azure.com/upgrade-status-
az aks upgrade -g $RG -n $CLUSTER --kubernetes-version <same version>   # retry
az aks update -g $RG -n $CLUSTER                                    # reconcile

⑦ Identity

az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
az aks update -g $RG -n $CLUSTER --attach-acr $ACR      # non-ABAC
az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv
az identity federated-credential list --identity-name id-myapp -g $RG -o table
kubectl auth can-i list pods -n myapp
kubelogin convert-kubeconfig -l azurecli

⑧ Fault blind box

./fault-inject.sh list
./fault-inject.sh inject f3 ; ./fault-inject.sh restore f3
./fault-inject.sh random 3
./aks-triage.sh
./fault-inject.sh restore-all
az aks stop -g $RG -n $CLUSTER     # or az group delete -n $RG --yes --no-wait

Quick troubleshooting table

Error / symptomLayerFirst commandCommon fix
Kubelet stopped posting node status.Nodeaz vmss run-command invoke ... systemctl is-active kubeletRestart the process or node; roll back the network change
OutboundConnFailVMExtensionError / exit 50OutboundOn the node: curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/Allow the FQDNs; fix the UDR/DNS
InsufficientSubnetSizeARM/networkaz aks nodepool list (max-count, maxPods)New subnet + new pool; lower max-count/surge
SubnetIsFullARM/networkaz network vnet subnet showRetry after scale-in; separate subnet node pool
Intermittent timeouts to a single external targetSNATLB metric SNAT Connection Count (Failed)Connection reuse; ports + IPs; NAT Gateway
EXTERNAL-IP <pending>LBkubectl describe svcCluster identity permissions, annotations, policy
Endpoints emptyServiceget endpointslicesFix selector / readiness
CoreDNS i/o timeoutDNSCoreDNS logs + coredns-customUpstream 168.63.129.16; UDP+TCP 53
UpgradeFailed ... Too Many RequestsUpgradekubectl get pdb -AFix PDB → retry same version; Cordon
QuotaExceededUpgradeaz vm list-usageLower surge / raise quota → reconcile
401 Unauthorized (pull)Identityaz aks check-acrAcrPull / Repository Reader
403 Forbidden (pull)Network accessnslookup <acr>.azurecr.ioPrivate DNS link / ACR firewall
AADSTS70021Workload IdentityCompare issuerUrl with the federated credentialTrailing slash, subject

Recommended config snippets

# PDB allowing 1 Pod disruption at a time (replicas ≥ 2)
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: myapp-pdb, namespace: myapp }
spec:
  maxUnavailable: 1
  selector: { matchLabels: { app: myapp } }
# Keep DNS when default-deny egress is in place
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: allow-dns, namespace: myapp }
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
  - to:
    - namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: kube-system } }
      podSelector: { matchLabels: { k8s-app: kube-dns } }
    ports: [ { protocol: UDP, port: 53 }, { protocol: TCP, port: 53 } ]
# Node pool upgrade behavior baseline (production)
az aks nodepool update -g $RG --cluster-name $CLUSTER -n userpool \
  --max-surge 33% --drain-timeout 30 --undrainable-node-behavior Cordon --max-blocked-nodes 1

Capstone lab + final quiz

“Monday, 9:00”: four alerts at once, and you are the on-call platform engineer
About 30 minIncurs Azure costs

Scenario

Over the weekend, three changes were made: the network team associated a new route table with the node subnet (in the lab, a NetworkPolicy simulates outbound restrictions), the security team enabled a strict PDB template, and the dev team moved the myapp image to a new ACR. At 9:00 on Monday, four alerts arrived: ① myapp 5xx; ② node image auto-upgrade failed; ③ newly deployed Pods show ImagePullBackOff; ④ a node is NotReady. Restore service within 30 minutes and write an incident report.

Setup (run by the instructor or a partner):
./fault-inject.sh inject f1     # node NotReady
./fault-inject.sh inject f2     # strict PDB
./fault-inject.sh inject f3     # image points to an unavailable registry
./fault-inject.sh inject f5     # outbound DNS blocked by policy
Collect a snapshot: ./aks-triage.sh, and save the output as incident evidence.
Restore service first (stop the bleeding): confirm the direct cause of the 5xx (empty Endpoints? readiness failure? image pull failure?). Prefer kubectl -n myapp rollout undo deploy/myapp to roll back to a working image, and allow DNS (apply allow-dns.yaml). Verify that curl http://$IP/healthz = 200.
Node: use az vmss run-command invoke to check the kubelet state and recover it (or watch the auto-repair events), and record a timeline.
Upgrade blocked: run kubectl get pdb -A to find the PDB with ALLOWED DISRUPTIONS=0, and replace it with a version that uses maxUnavailable: 1. Set the Cordon behavior for userpool, run az aks nodepool upgrade --node-image-only, and confirm it succeeds.
Image pull: use az aks check-acr to verify the correct ACR. If you need the new ACR, use --attach-acr (or assign Repository Reader when ABAC is in use).
Prevention: write three prevention steps (for example: run a connectivity check on the nodes before network changes; review the rules in the PDB template; put image registry changes behind a check-acr gate). Also set alerts for the NotReady node count and for UpgradeFailed activity-log events.
Cleanup:
./fault-inject.sh restore-all
kubectl -n myapp delete networkpolicy allow-dns --ignore-not-found
az aks stop -g $RG -n $CLUSTER        # keep the cluster, stop billed compute
# or delete everything: az group delete -n $RG --yes --no-wait
Acceptance checklist

Open-ended self-check (6 questions)

1. Why is “locating the layer” the first step in troubleshooting, rather than reading logs?

The same symptom can come from several layers (for example, an image pull failure can be identity, network, or the image name). Locating the layer decides which evidence and tools to use, so you don't waste time in unrelated logs. AKS also has a managed boundary: ARM operation errors appear only in operation responses and the activity log, not inside the cluster.

2. What does each of kubectl debug node, az aks command invoke, and az vmss run-command depend on?

debug node depends on the Kubernetes API being reachable, the node being schedulable, and the node being able to pull images. command invoke depends on ARM/AKS RP and on the cluster being able to schedule a command Pod (60-second and 512 KB limits). It suits private clusters. vmss run-command depends on the Compute platform and the VM agent, not on Kubernetes. It suits NotReady nodes.

3. Explain SNAT port exhaustion in one sentence, and name three layers of fixes.

When concurrent connections from one node through the same outbound IP to the same destination IP:port (including idle ones that haven't timed out) exceed that node's preallocated ports, new connections can't get a port and time out. Fixes: connection reuse; explicit ports plus more outbound IPs or a NAT gateway; private endpoints to bypass SNAT.

4. Why is flat Azure CNI especially prone to subnet exhaustion? Can Overlay still run out?

Flat CNI pre-allocates 1 + maxPods VNet addresses per node, and the pre-check calculates the theoretical value from max-count and surge. Overlay assigns only VNet addresses to nodes, but the node subnet still has to hold the nodes and surge. The Pod CIDR also has a limit (one /24 per node).

5. After an upgrade fails because of a PDB, which recovery options don't interrupt the business? What is the risk of force upgrade?

Add temporary replicas or change the PDB, then retry the same version. Back up and delete the PDB, then restore it. Use Cordon behavior to isolate nodes. Automatic PDB management (preview). Force upgrade bypasses PDBs. It can drain all Pods at once and cause a full outage, and it makes the undrainable settings ineffective.

6. How do you tell which direction the root cause of an ACR 401 versus 403 points?

401 is mostly authorization (kubelet identity role, ABAC needs Repository Reader, identity removed, cached credentials). It can also be a wrong image name or architecture. 403 is mostly network access (private DNS zone not linked, ACR firewall not allowing the outbound IP). az aks check-acr can verify both resolution and permissions at the same time.

Sources and versions

Verified on 2026-11-15 (Microsoft Learn, AKS docs, Azure Workload Identity project, YouTube oEmbed)

Source table

TopicVerification resultSources (accessed 2026-11-15)
Diagnose and solve problemsSmart self-diagnosis, with no extra setup and no extra charge. Category tiles; View details shows the summary, errors, recommended actions, docs, metrics, and logsaks-diagnostics
command invokeRBAC: runcommand/action + commandResults/read; command Pod requests 200m/500Mi, limits 500m/1Gi; ARM timeout 60 seconds; output 512 KB; CLI ≥ 2.24.0; can be turned off with disableRunCommandaccess-private-cluster
kubectl debug nodeImage mcr.microsoft.com/azurelinux/busybox:1.36, chroot /host; delete the node-debugger Pod when done; get the private IP with az aks machine listnode-access
Node heartbeat and NotReadyLease renews every 10 seconds (on failure, backoff from 200ms to 7s); .status defaults to 5 minutes; docs say 40-second unreachable timeout; PID exhaustion shows pthread_create failed; pod-max-pids cannot be set through AKS node configurationbasic · after-healthy
Node auto-repairConsecutive NotReady or no reports within a 10-minute window; unhealthy for ≥ 5 minutes; aks-remediator; reboot → reimage → redeploy (Linux), up to 3 rounds, about 1 hour at most; event source aks-auto-repairnode-auto-repair
InsufficientSubnetSizeFull original message; requirements of the three modes; the subnet CIDR of an existing node pool cannot be changed; migrate with a new subnet + new pool; temporarily lower MaxCountinsufficientsubnetsize
SubnetIsFullOriginal message (VMSSAgentPoolReconciler); scale-in or a subnet-separated node poolsubnetisfull-upgrade
SNAT and LB outboundAllocatedOutboundPorts defaults to 0; ≤50 nodes get 1024, and 48→52 nodes changes it to 512; formula 64,000/port × IPs; ports in multiples of 8; adding IPs doesn't increase per-node ports; idle timeout 30 minutes, TCP Reset on by default; up to 100 managed outbound IPs; changes made in the portal are overwritten by reconciliation; tcptracer steps for locating issuesconfigure-load-balancer-standard · load-balancer-standard · snat-port-exhaustion
OutboundConnFailVMExtensionError (50)CSE runs curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/; deciding the layer from a curl failure; Connectivity analysis (preview); data endpointsoutboundconnfail
Default health probe behavior and annotationsLocal → HTTP /healthz; Cluster TCP; appProtocol http → /; probe annotations; Basic LB retired on 2025-09-30configure-load-balancer-standard
Application routing NGINX retirementUpstream ingress-nginx stopped maintenance in 2026-03; Microsoft provides critical security patches for managed NGINX until 2026-11-30; migrate to an application routing Gateway API implementation or another supported implementationAKS blog · app-routing-migration
LocalDNS (1.37)From 1.37, AKS Standard node pools with no explicit configuration default to Preferred; needs UDP+TCP 53; can be set explicitly to Disabledupgrade-options
Upgrade failure (PDB)UpgradeFailed original text, the event “Eviction blocked by Too Many Requests (usually a pdb)”, three solutions, retry-with-same-version prompt; CLI 2.67.0+poddrainfailure
Upgrade optionsPre-check list; force upgrade (CLI 2.79.0+ / API 2025-09-01+, default 3-day window); undrainable Schedule/Cordon, Quarantined label, max-blocked-nodes defaults to maxSurge; drain timeout defaults to 30 minutes; soak defaults to 0; production 33%/1; IP formula; platform-initiated upgrades from 2027-06-01upgrade-options
QuotaExceededOriginal message; two-level quota (region and series); az vm list-usage; reconciliation commandsquota-exceeded-error
ACR pullThree phases; original 401/403/i/o timeout text; ABAC registries need Container Registry Repository Reader, which attach-acr doesn't support; if the kubelet identity was removed, run az aks update; check-acr exec format error; credential cachingcannot-pull-image-from-acr
Workload IdentityAADSTS70021 (common cause: issuer missing a trailing /); AADSTS90061 (OIDC endpoint unreachable, az aks update); from v1.0.0 requires the label azure.workload.identity/use: "true"azure-workload-identity troubleshooting
Agentic CLI for AKSPreview; extension aks-agent, command az aks agent; client mode / cluster modeagentic-cli-for-aks-troubleshoot

Video verification notes

The following videos were verified on 2026-11-15 through YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) for titles and channels:

  • UdRzAdraWAE — Diagnose & Solve with Andrew Scobie (Azure Kubernetes Service (AKS))
  • rZuC6m4WH10 — How to troubleshoot common issues with AKS Diagnostics (Microsoft Azure)
  • RaPivLnCzRw — AKS MCP Server with Julia Yin (Azure Kubernetes Service (AKS))
  • YeO5zTDFtHA — Troubleshooting Disk Latency with Burak Ok (Azure Kubernetes Service (AKS))
  • whnksEP0yUI — Troubleshooting OOM failures with Claudio Godoy (Azure Kubernetes Service (AKS))
  • 47Q4JbWxlm4 — Troubleshooting AKS Scaling Issues with Jameson Hearn (Azure Kubernetes Service (AKS))
  • qLRB9_DlABg — Azure CNI Overlay networking in AKS (Preview) (Azure Power Lunch)
  • PRDy-2h_r2E — Upgrade Issues 101 with Mosbah Majed (Azure Kubernetes Service (AKS))
  • CWnQ-nNi9Yw — Troubleshoot Outbound connectivity Issues with Ping He (Azure Kubernetes Service (AKS))
  • V2E1WNR-4KM — AKS Egress Traffic and Outbound Types (Houssem Dellai)
  • 10IQeDOtVqo — Troubleshooting DNS Issues with Qasim Sarfaraz (Azure Kubernetes Service (AKS))
  • i2GobU0Wg48 — AKS Workload Identity - Quick Tutorial (Azure Kubernetes Service (AKS))

No verified video was found that specifically covers InsufficientSubnetSize, LB health probes, or ACR 401/403. The related modules provide storyboard scripts instead. Durations and publish dates weren't available through oEmbed, so they aren't listed.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API to read the narration aloud (en-US voice; English terms are pronounced with en-US). This course material can't embed MP3 files or generate video. The narration and storyboards can be handed to a TTS or video tool to produce audio and video.

Known limitations

  • The command output in this course is all examples. It was not run on a real subscription when it was written. Take node names, IPs, and version numbers (written as 1.3x.y) from your own environment.
  • Error messages marked “check against your environment” (such as the literal Azure RBAC Forbidden message, the admin credential error under disable-local-accounts, the CSE 51/52 names, UnsatisfiablePDB, the FailedCreatePodSandBox literal, and the Overlay Pod CIDR exhaustion message) were compiled from the structure of the official docs. They have not been checked word for word.
  • Value of node-monitor-grace-period: Microsoft docs say 40 seconds, newer upstream versions default to 50 seconds, and the actual value in AKS's managed control plane is not publicly verified.
  • In the SNAT preallocation table, the tiers above 51 nodes are listed according to Azure Load Balancer default allocation rules (the AKS docs directly confirm the 1024 and 512 tiers). The dynamic pod subnet “batch of 16” and the Azure Firewall SNAT port counts should be checked against the official docs.
  • Parameters such as --undrainable-node-behavior, --max-unavailable, and --enable-force-upgrade require specific CLI versions. Older versions may need the aks-preview extension.
  • The CLI names for the LB metrics (SnatConnectionCount, UsedSnatPorts, AllocatedSnatPorts) and their dimension names should be confirmed with az monitor metrics list-definitions.
  • Fault-injection script f5 depends on the network policy engine. f1 depends on the debug Pod being able to schedule onto the target node and pull its image.
  • The animations are simplified simulations of the real mechanisms (for example, the SNAT simulator calculates in discrete seconds, and the IP calculator ignores some of Azure's reservation details). They are for understanding the principles, not for precise capacity planning.