AKS Hour 7: Deep Troubleshooting and Advanced Topics
- 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), andaz 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 + maxPodsaddresses per node, while Overlay uses only the node address. Be able to interpretInsufficientSubnetSize/SubnetIsFulland 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, andSubnetIsFull. 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 pull401 Unauthorized/403 Forbidden, and useaz 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
| # | Time | Module | Core content | Animation / interactive | Lab (aks-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup: fault-injection lab | Reuse aks-lab, deploy myapp, download fault-inject.sh | Environment self-check list | Script list / inject / restore |
| 1 | 00–06 | Troubleshooting methodology and AKS diagnostic tools | Layer 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 |
| 2 | 06–13 | Nodes NotReady and node pool failures | Lease heartbeats, node-monitor-grace-period, the unreachable taint and 300-second eviction, node auto-repair, CSE error codes, PID / disk pressure | Node heartbeat timeline simulator | Stop kubelet to reproduce NotReady, then recover |
| 3 | 13–21 | IP addresses and subnet exhaustion | IP consumption under CNI flat vs Overlay vs dynamic Pod subnet, Azure reserves 5, surge and max-count are counted, InsufficientSubnetSize, migrating to a new subnet | Core animation: subnet IP exhaustion calculator | Calculate and reproduce a failed scale-out (drill) |
| 4 | 21–28 | Outbound connectivity: SNAT port exhaustion and UDR issues | Pre-allocated port table, 5-tuple reuse, idle timeout, LB metrics, tcptracer to locate the Pod, NAT Gateway, UDR / firewall, exit code 50 | Core animation: SNAT port exhaustion simulator | Check outbound rules and metrics, adjust ports |
| 5 | 28–35 | Load balancers, ingress, and DNS failures | EXTERNAL-IP pending, health probes, externalTrafficPolicy, NSG, retirement of the application routing NGINX, CoreDNS / LocalDNS / custom DNS | Request path hop-by-hop tracer (can inject 6 kinds of faults) | Selector errors, DNS failure reproduction |
| 6 | 35–42 | Upgrade failures: PDB blocking, quotas, and eviction | Pre-upgrade checks, reading UpgradeFailed messages, Cordon isolation, force upgrade, quotas, same-version retry | Surge upgrade + PDB eviction simulator | Block a drain with a PDB, then recover |
| 7 | 42–50 | Identity and permission failures: Entra, Workload Identity, ACR pulls | kubelogin / Azure RBAC 403, local accounts, AADSTS70021 / 90061, webhook labels, ACR 401/403, check-acr | Token exchange failure injector | Reproduce and fix ACR 401 and a Workload Identity subject mismatch |
| 8 | 50–60 | Mixed-fault mystery box | Random faults + timed diagnosis + root-cause selection + interactive troubleshooting tree | Fault mystery-box game + troubleshooting decision tree | Script randomly injects 3 faults |
| — | After class | Cheat sheet · Capstone lab | "Monday 9 a.m." multi-fault drill | Final quiz, 12 questions | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Identify the failing layer and choose the tool | ✓ | · | · | · | · | · | · | ✓ | az aks show, az monitor activity-log list | M1 / mystery box |
| Access nodes and private clusters | ✓ | ✓ | · | ✓ | · | · | · | ✓ | kubectl debug node, az aks command invoke | M1 / M2 |
| Node NotReady and CSE failures | · | ✓ | · | ✓ | · | · | · | ✓ | describe node, journalctl -u kubelet | M2 |
| Subnet IP planning and exhaustion fixes | · | · | ✓ | · | · | ✓ | · | ✓ | az network vnet subnet show, nodepool add --vnet-subnet-id | M3 |
| SNAT ports and the outbound path | · | ✓ | · | ✓ | · | · | · | ✓ | az network lb outbound-rule list, --load-balancer-outbound-ports | M4 |
| LB / ingress / DNS failures | · | · | · | · | ✓ | · | · | ✓ | get endpointslices, nslookup, CoreDNS logs | M5 |
| Upgrade failure recovery | · | · | ✓ | · | · | ✓ | · | ✓ | get pdb, --undrainable-node-behavior, az vm list-usage | M6 |
| Identity and image pull failures | · | · | · | · | · | · | ✓ | ✓ | az aks check-acr, az identity federated-credential list | M7 |
What this hour does not cover (and where to learn it)
| Topic | Reason | Where to learn it |
|---|---|---|
| General Pod-level troubleshooting (CrashLoopBackOff, OOMKilled, probes, Pending scheduling) | This is general Kubernetes knowledge; this hour covers only the AKS-specific layers | Kubernetes 8 + 1 hour crash course (Hour 2 scheduling/resources; Hour 6 includes an AKS introduction: part6) |
| Network selection, outbound types, private cluster design | This hour only covers "how to troubleshoot when something breaks" | AKS Hour 2: Networking |
| Setting up Entra integration, Workload Identity, and Key Vault CSI | Same as above | AKS Hour 3: Identity and Security |
| Configuring upgrade policy, maintenance windows, Container Insights, and Managed Prometheus | Same as above | AKS Hour 6; for Prometheus details see Prometheus & Grafana Hour 3 |
| Helm release failures, pipeline deployment failures | These belong to delivery tools | Helm Hour 3 · GitHub Hour 3 · Azure DevOps Hour 3 |
| 50 production problems and interview questions | Length: too much for one hour | AKS Hour 8 (optional) |
How to use this course material
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.
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).
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.
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.Module 0 · Environment setup: fault-injection lab (complete before class)
- 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-upgraderequires 2.79+; if--undrainable-node-behaviorreports an unknown parameter, upgrade or installaks-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 pooluserpool), ACRacraks<suffix>attached, and myapp (Flask + gunicorn, port 5000,/healthz) and Redis running in themyappnamespace.
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
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.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).Module 1 · Troubleshooting methodology and AKS diagnostic tools
- 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), andaz vmss run-command invoke(when the API is unreachable or the node is NotReady).
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:
| Layer | Typical symptom | Where the evidence is | Preferred tool |
|---|---|---|---|
| ① ARM / AKS RP operations | az aks upgrade/scale fails, and the cluster is Failed | The Code: returned by the operation, the activity log | az aks show --query provisioningState, az monitor activity-log list, Diagnose and solve problems |
| ② Control plane | kubectl timeouts, 429s, webhook rejections | Control plane diagnostic logs (kube-apiserver, kube-audit) | Diagnostic settings → Log Analytics (Hour 6), Diagnose and solve problems "Cluster and Control Plane Availability"-type checks |
| ③ Nodes | NotReady, CSE failures, disk/PID pressure | Node conditions, kubelet / containerd logs, VMSS instance state | kubectl describe node, kubectl debug node, az vmss run-command invoke |
| ④ Pods / workloads | Pending, CrashLoop, ImagePullBackOff | Events, container logs | kubectl describe pod, kubectl logs --previous |
| ⑤ Network | Timeouts, DNS failures, EXTERNAL-IP pending, SNAT | EndpointSlices, CoreDNS logs, LB metrics, NSG/UDR | kubectl get endpointslices, Network Watcher, LB Metrics |
| ⑥ Identity | 401/403, AADSTS errors | AADSTS codes in Pod logs, role assignments | az 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 afterchroot /hostyou can runjournalctl -u kubeletandcrictl. Prerequisites: the API server is reachable, and the node can schedule the Pod and pull images.az aks command invoke: runskubectl/helminside the cluster through the Azure API, so you don't need a VPN to reach a private cluster. Permissions:Microsoft.ContainerService/managedClusters/runcommand/actionand.../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 withapiServerAccessProfile.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, commandaz 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
| Situation | API reachable? | Preferred |
|---|---|---|
| Public cluster, node Ready, need to look inside the node | Yes | kubectl debug node |
| Private cluster, you are not inside the VNet | No (for you) | az aks command invoke |
| Node NotReady / kubelet stopped / outbound blocked | Not applicable to that node | az vmss run-command invoke |
| Operation failed (upgrade, scale, create) | Not relevant | Error code → matching Microsoft Learn article → Diagnose and solve problems |
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
Flowchart: layered troubleshooting decision flow
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks show | provisioningState / powerState of the cluster and node pools | --query "{s:provisioningState,p:powerState.code}" |
az aks nodepool list | State, version, and count for each pool | -o table |
az monitor activity-log list | Who did what and when, and the failure code | --resource-group, --offset 24h, --status Failed |
kubectl get events -A --sort-by=.lastTimestamp | Cluster event timeline | --field-selector type=Warning |
kubectl debug node/N | Privileged debug Pod on a node | -it --image=mcr.microsoft.com/azurelinux/busybox:1.36, --profile=sysadmin |
az aks command invoke | Run kubectl / helm on a private cluster | --command, --file (can be repeated) |
az vmss run-command invoke | Run a script on a node without going through Kubernetes | --command-id RunShellScript --instance-id N --scripts |
az aks machine list | Get 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)
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)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.
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).
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]
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).
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"
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
Official documentation
- AKS Diagnose and Solve Problems overview
- Connect to AKS cluster nodes (kubectl debug / az aks machine)
- Access a private AKS cluster using command invoke / Run command
- AKS troubleshooting documentation (main entry point)
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.
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.
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.
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.
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.
Module 2 · Nodes NotReady and node pool failures
- Explain the two kinds of node heartbeat (
.statusand the Lease inkube-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).
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) ornode.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 group | Typical evidence | First command |
|---|---|---|
| Network / outbound change (all nodes break at once) | kubelet logs show API server timeouts; recent changes to UDR, NSG, DNS, or the firewall | az monitor activity-log list + curl -v https://<API FQDN>:443 via vmss run-command |
| kubelet / containerd process | container runtime is down, PLEG is not healthy (check against actual output) | journalctl -u kubelet -u containerd |
| Resource pressure | DiskPressure, PIDPressure, MemoryPressure; pthread_create failed: Resource temporarily unavailable; OS disk IOPS throttling | kubectl describe node, the node performance detectors in Diagnose and solve problems |
| VM platform events | VMSS instance Stopped/Deallocated, platform maintenance, Spot eviction | az 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
| AKS | EKS | Self-managed kubeadm | |
|---|---|---|---|
| Node auto-repair | On by default: reboot → reimage → redeploy | Managed node group node auto repair (must be enabled) | None. You must build it yourself (for example, Node Problem Detector plus custom remediation) |
| Enter the node | kubectl debug / vmss run-command / Bastion | SSM Session Manager | SSH |
--kubelet-config, --linux-os-config) or a new node pool instead.Timeline: from kubelet stopping to Pod recreation
Structure diagram: four root-cause categories for NotReady
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl describe node N | Conditions, Taints, Allocated, Events | Check the reason/message of Ready |
kubectl get lease -n kube-node-lease | Heartbeat renewal time | -o custom-columns=NAME:.metadata.name,RENEW:.spec.renewTime |
kubectl get events --field-selector source=aks-auto-repair | Auto-repair events | or --field-selector involvedObject.kind=Node |
journalctl -u kubelet -u containerd | Node process logs (on the node) | --since, -n |
az vmss list-instances / get-instance-view | VM-level status | --instance-id |
az vmss restart / reimage | Manually restart / reimage the node | --instance-ids |
az aks nodepool delete-machines | Delete 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)
kubectl -n myapp scale deploy/myapp --replicas=4 kubectl -n myapp get pod -o wide
./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
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}]az vmss run-command invoke from the Command tab, and confirm kubelet inactive../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.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.
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"
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
Official documentation
- Basic troubleshooting of Node Not Ready
- Node Not Ready after being healthy
- Automatically repair AKS nodes
- Kubernetes Node Status
Video storyboard (about 90 seconds)
This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.
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.
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.
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.
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.
Module 3 · IP addresses and subnet exhaustion
- 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
InsufficientSubnetSizemessage (“Pre-allocated IPs … exceeds IPs available …”). Understand why autoscaling usesmax-countin 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.
What: What consumes addresses in the node subnet
| Mode | Node subnet consumption per node | Pod addresses come from | Common limit |
|---|---|---|---|
| Azure CNI (flat / traditional) | 1 + maxPods (pre-allocated for Pods when the node is created; default maxPods is 30) | Node subnet | Subnet 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 Overlay | 1 (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) | 1 | Pod CIDR + route table | Route 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-countrather than the current node count. - Upgrades default to
maxSurge=1(or the percentage you set). Surge nodes also consume addresses at1 + maxPodseach. The official formula isrequired 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 aFailedCreatePodSandBoxevent 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
| Option | Timing | Notes |
|---|---|---|
Create a larger subnet + new node pool (--vnet-subnet-id) + drain the old pool + delete the old pool | Permanent fix | Official approach: the subnet CIDR of an existing node pool cannot be changed |
Temporarily lower max-count on the autoscaling pool | Emergency | Reduces the pre-check's theoretical value. Set it back after the operation finishes. |
Lower --max-surge or use --max-unavailable | Emergency (upgrade) | Rotate existing nodes. No extra addresses are used, but capacity drops. |
| Scale in the node pool to free addresses | Emergency | The official first recommendation for SubnetIsFull |
| Migrate to Azure CNI Overlay | Medium to long term | The node subnet uses only node addresses. Pod addresses do not take up VNet space. (For migration steps, see Hour 2 and the official docs.) |
Address layout: how many nodes the same /24 can hold in each mode
Flow: address pre-check for one scale-out request
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks show --query networkProfile | Network plugin, mode, Pod CIDR | networkPlugin, networkPluginMode, podCidr |
az aks nodepool list | Per 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 show | Subnet prefix and number of IP configurations in use | --query "{p:addressPrefix,used:length(ipConfigurations)}" |
az aks nodepool add --vnet-subnet-id | Create a pool in the new subnet | --max-pods, --mode |
az aks nodepool update | Adjust 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).
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)
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
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
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
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.
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 table2. 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
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
No verified video specifically covering InsufficientSubnetSize was found. Use the storyboard below.
Official documentation
- Troubleshoot InsufficientSubnetSize
- SubnetIsFull during upgrade
- IP address planning for AKS
- Upgrade options (IP exhaustion scenarios and formulas)
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.
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.
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.
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.
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.
Module 4 · Outbound connections: SNAT port exhaustion and UDR issues
- 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
tcptracerto locate the Pod, and then push the application to reuse connections. - Adjust
--load-balancer-outbound-portsand outbound IPs using the formula64,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.
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–50 | 1024 |
| 51–100 | 512 |
| 101–200 | 256 |
| 201–400 | 128 |
| 401–800 | 64 |
| 801–1000 | 32 |
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
- The SNAT detection in Diagnose and solve problems in the portal, or the metrics of the load balancer
kubernetesin 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). kubectl get nodes -o wide | grep <node IP>finds the node. Usekubectl node-shellto get onto the node and run the BCC tooltcptracer -t4v. Filter public destinations, count by source address or network namespace, and map back to Pods (official docs steps).- Fix the application first: connection pooling, HTTP keep-alive, reuse client objects, and reduce concurrency to the same endpoint.
- 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 showscurl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/. IfcurlreportsCould not resolve host, it is a DNS problem. If it reportsConnection 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.comis allowed, but the data endpoint*.data.mcr.microsoft.comis not (for ACR,*.blob.core.windows.netor<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 allocation | Statically pre-allocated per node | Dynamically allocated on demand, 64,512 per IP | Determined by the firewall's SNAT capacity (Azure Firewall: 2,496 ports per public IP per instance; check the docs) |
| Default idle timeout | AKS sets it to 30 minutes | 4 minutes (TCP, adjustable) | Depends on the device |
| Suitable for | Small clusters, simple outbound | High volume of outbound connections, fixed egress IP | Enterprise egress control and auditing |
--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
UDR outbound and 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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az network lb outbound-rule list | Check AllocatedOutboundPorts / IdleTimeout | --lb-name kubernetes -g $NODE_RG |
az monitor metrics list | SNAT metrics | --metric SnatConnectionCount --filter "ConnectionState eq 'failed'" (check the metric and dimension names in the portal) |
az aks update --load-balancer-outbound-ports | Explicit ports per node (multiple of 8) | Used together with --load-balancer-managed-outbound-ip-count |
az aks update --load-balancer-idle-timeout | Outbound idle timeout (minutes) | Default 30; set to 4 if there are many short connections |
az aks update --outbound-type | Migrate 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/close | Filter 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)
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 tableaz 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
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.
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-*.
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
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
Official documentation
- Troubleshoot SNAT port exhaustion on AKS nodes
- Configure a public Standard Load Balancer (outbound ports / IPs / idle timeout)
- Source NAT for outbound connections
- OutboundConnFailVMExtensionError (50)
- Outbound network and FQDN rules for AKS
Video storyboard (about 90 seconds)
This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.
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.
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.
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.
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.
Module 5 · Load balancer, ingress, and DNS failures
- 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 ofexternalTrafficPolicy. - 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 to168.63.129.16. For LocalDNS in 1.37, both TCP and UDP port 53 must be allowed.
What: each hop an external request passes through
- DNS: The client resolves the domain name to a public IP (Azure DNS zone or external DNS).
- 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.
- NSG: AKS automatically adds inbound rules for Service ports in the node NSG.
loadBalancerSourceRanges/azure-allowed-ip-rangesnarrow the allowed sources. - Node → kube-proxy / Cilium eBPF: NodePort → Service → pick one ready endpoint.
- Ingress controller (application routing NGINX, a Gateway API implementation, or Application Gateway for Containers): routes to the backend Service by Host/Path.
- EndpointSlice → Pod: Only Ready Pods are endpoints. If the selector is wrong, the endpoints are empty.
- 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 to168.63.129.16).
Why: AKS-specific pitfalls
- Default health probe behavior: with
externalTrafficPolicy: Local, the HTTP/healthzprobe targets kube-proxy'shealthCheckNodePort. Nodes with no local Pod are marked unhealthy; this is by design. WithCluster+ TCP, only the port is probed. IfappProtocol: httpis set, the default probe path is/. If the app returns 404 for/, all backends are marked unhealthy. Fix it with the annotationservice.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-groupannotation 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
Preferredmode, 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 withdig +udpanddig +tcp, and set it explicitly toDisabledif 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
| Symptom | First check |
|---|---|
EXTERNAL-IP <pending> | Events from kubectl describe svc (SyncLoadBalancerFailed) |
| Has an IP but times out | Health probe status, NSG, externalTrafficPolicy, UDR asymmetric routing (Module 4) |
| Ingress returns 404 | ingressClassName, Host, Path; ingress controller logs |
| Ingress returns 502/503 | Backend Service has no endpoints, or the port is wrong |
could not resolve host inside a Pod | CoreDNS Pods, whether NetworkPolicy allows port 53, coredns-custom, VNet DNS |
coredns-custom and whether the upstream DNS is reachable. A restart only hides the evidence.Request path and evidence at each hop
Default health probe behavior
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl describe svc | LB sync events, NodePort, healthCheckNodePort | Look for EnsuringLoadBalancer / SyncLoadBalancerFailed |
kubectl get endpointslices -l kubernetes.io/service-name=S | Whether endpoints exist and are ready | -o yaml to view conditions |
az network lb probe list / rule list | LB probes and rules | --lb-name kubernetes |
az network nic list-effective-nsg | Effective NSG rules on the node NIC | VMSS instance NICs need the vmss nic command (check the actual syntax) |
kubectl -n kube-system logs -l k8s-app=kube-dns | CoreDNS logs | --tail |
kubectl -n kube-system get cm coredns-custom -o yaml | Custom CoreDNS configuration | AKS 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)
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/healthz200
./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-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-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.
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.
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
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
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
- Configure Standard LB (annotations and default health probe behavior)
- Application routing migration
- AKS blog: Application Routing add-on and Ingress-NGINX update
- Upgrade options (1.37 LocalDNS pre-checks)
- Customize CoreDNS for AKS
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.
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.”
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.
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.
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.
Module 6 · Upgrade failures: PDB blocking, quotas, and eviction
- 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
UpgradeFailedmessage caused by a PDB, and confirm it usingALLOWED DISRUPTIONSfromkubectl get pdband theEviction 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 Cordonto quarantine the node (labelkubernetes.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 withaz aks update/az aks nodepool update.
What: the upgrade pipeline and where it fails
| Stage | What AKS does | Typical failure |
|---|---|---|
| Pre-checks | Breaking API changes, upgrade path, PDBs (such as maxUnavailable=0), quota, subnet, expired credentials, managed resource group locks | The operation is rejected outright (for example UnsatisfiablePDB or InsufficientSubnetSize; check the exact error codes) |
| Surge | Create new nodes per maxSurge (new version / new image) | QuotaExceeded, SubnetIsFull, SKUNotAvailable / AllocationFailed / OverconstrainedAllocationRequest, CSE exit code 50 |
| Cordon + Drain | Call the Eviction API on old nodes and wait for Pods to terminate gracefully; the default drain timeout is 30 minutes | PDB blocks → UpgradeFailed “Too Many Requests”; Pods terminate too slowly |
| Soak (optional) | After draining each node, wait --node-soak-duration (default 0) | — |
| Delete old nodes | Delete VMSS instances | Resource 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)
- Fix the PDB or add replicas so that ALLOWED DISRUPTIONS ≥ 1, then re-run
az aks upgradefor 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.”). - Back up → delete the PDB → upgrade → reapply (when the PDB cannot be modified).
- Undrainable node behavior:
az aks nodepool update --undrainable-node-behavior Cordon --max-blocked-nodes 2 --drain-timeout 30. The default isSchedule(delete the blocked node and surge a replacement).Cordon(recommended) isolates the node and labels itkubernetes.azure.com/upgrade-status=Quarantined, and the upgrade continues.max-blocked-nodesdefaults to the value of maxSurge. Afterwards: fix the PDB → remove the label → optionallyaz aks nodepool delete-machines→az aks update, ornodepool scalebased on the number of upgraded nodes, to bring the state back to Succeeded. - Automatic PDB management (preview extension): temporarily adds replicas when a PDB blocks the drain, then scales back once the drain completes.
- 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
| Setting | Extra nodes | Behavior |
|---|---|---|
maxSurge=5, maxUnavailable=0 | 5 surge | Official 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=5 | None | Drain the 5 existing nodes directly (suited to tight quota or subnets) |
| Official recommendation (production) | — | maxSurge=33%, maxUnavailable=1; dev/test 50% / 2 |
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
Failure triage: read the error code to find the direction
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl get pdb -A | Find PDBs with ALLOWED DISRUPTIONS = 0 | Check before every upgrade |
kubectl get events -A | grep -i drain | Drain events | “Eviction blocked by Too Many Requests (usually a pdb)” |
az aks nodepool update | Upgrade behavior | --max-surge, --max-unavailable, --drain-timeout (minutes), --node-soak-duration, --undrainable-node-behavior, --max-blocked-nodes |
az aks upgrade | Upgrade / retry the same version | --kubernetes-version, --control-plane-only, --enable-force-upgrade --upgrade-override-until |
az vm list-usage | Regional and VM family vCPU quota | -l canadacentral -o table |
az aks update | Reconcile without parameters; restores Succeeded | Use 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).
./fault-inject.sh inject f2 kubectl -n myapp get pdb
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
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.
./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
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.
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
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
Official documentation
- UpgradeFailed due to eviction failures caused by PDBs
- Upgrade options and recommendations (undrainable, force upgrade, pre-checks)
- Troubleshoot QuotaExceeded
- Platform-initiated upgrades
Video storyboard (about 90 seconds)
This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.
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.
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.
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.
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.
Module 7 · Identity and permission failures: Entra, Workload Identity, ACR pulls
- 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;AADSTS70021andAADSTS90061. - 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), andi/o timeout(private link peering). Useaz aks check-acr.
What: the three identity paths
| Path | Who | Where the token comes from | Where authorization happens | Common errors |
|---|---|---|---|---|
| People → API server | Engineers / pipelines | kubelogin gets a token from Entra (audience is the AKS server application) | Kubernetes RBAC or Azure RBAC for Kubernetes | Forbidden ... User does not have access to the resource in Azure (check the exact message), kubelogin not installed |
| Workload → Azure resources | Pod (service account) | Projected SA token (issued by the cluster OIDC issuer) → exchanged with Entra (client assertion) → access token | Role of the managed identity or application on the target resource | AADSTS70021, AADSTS90061, 403 from the target resource |
| Node → ACR | kubelet identity (managed identity) | The acr-credential-provider on the node gets a token from IMDS → ACR token exchange | AcrPull on ACR (non-ABAC) or Container Registry Repository Reader (ABAC) | 401 Unauthorized, 403 Forbidden, i/o timeout |
Why: the four checkpoints of Workload Identity
- 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). OtherwiseAZURE_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 annotationazure.workload.identity/client-id. - Issuer: the federated credential's issuer must match the cluster's
oidcIssuerProfile.issuerUrlexactly. The official troubleshooting guide says the most common cause is a missing trailing/. A mismatch givesAADSTS70021: No matching federated identity record found for presented assertion. - 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 toapi://AzureADTokenExchange. - Authorization: the token exchange succeeded, but the managed identity has no role on Key Vault or Storage, so the target service returns 403 (
ForbiddenByRbacin Key Vault RBAC mode; check the exact message). Also, if the OIDC issuer endpoint is unreachable, you getAADSTS90061: Request to External OIDC endpoint failed.; on AKS, first tryaz aks updateto 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-acrdoes not assign this role, so you must assign it manually. The kubelet identity was removed from the VMSS (fixed by reconciling withaz 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.iofor 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
| Symptom | Tool |
|---|---|
| ImagePullBackOff | Raw 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 Pod | AADSTS code in the Pod logs → az identity federated-credential list → compare with az aks show --query oidcIssuerProfile.issuerUrl |
| kubectl Forbidden | kubectl auth can-i → az role assignment list --scope <cluster or namespace ID> |
azure.workload.identity/use label.Workload Identity token exchange and failure points
Three ACR pull stages mapped to errors
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks check-acr | Verify from the cluster whether images can be pulled from ACR | --acr <acr>.azurecr.io; can add --node-name |
az aks show --query identityProfile.kubeletidentity | kubelet identity | Compare with az vmss identity show |
az role assignment list --scope <ACR ID> | Roles on ACR | AcrPull / Container Registry Repository Reader |
az aks show --query oidcIssuerProfile.issuerUrl | Cluster OIDC issuer | Compare character by character with the federated credential |
az identity federated-credential list | Federated credential | --identity-name id-myapp -g $RG |
kubectl auth can-i | Check the caller's permissions | --list -n NS, --as |
kubelogin convert-kubeconfig -l azurecli | Non-interactive login mode | Pipelines 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)
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
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.
./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.
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.
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
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
No verified official video was found that specifically covers ACR 401/403 troubleshooting. Please use the storyboard below.
Official documentation
- Troubleshoot AKS image pull errors from ACR
- Azure Workload Identity — Troubleshooting
- Workload ID overview
- ACR ABAC repository permissions
Video storyboard (about 90 seconds)
This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.
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.
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.
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.
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.
Module 8 · Mixed fault challenge
- 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.
What: the five-step method for blind-box diagnosis
- 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).
- Global snapshot (60 seconds):
az aks showstate, node Ready status, non-Running Pods, Warning events, and Azure operations that failed in the last 24 hours. - Locate the layer: classify the issue using the six-layer model from Module 1.
- Evidence chain: in that layer, collect 2–3 pieces of evidence that corroborate each other (for example, raw Events + component logs + config diff).
- 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 keywords | Layer | Review |
|---|---|---|
| NotReady, Kubelet stopped posting node status, exit status=50 | Node / outbound | Modules 2, 4 |
| InsufficientSubnetSize, SubnetIsFull | ARM / network planning | Module 3 |
| Intermittent i/o timeout to a single external target only | Network (SNAT) | Module 4 |
| EXTERNAL-IP pending, probe 0%, empty Endpoints, 404/502, could not resolve | Network (LB / ingress / DNS) | Module 5 |
| UpgradeFailed, Too Many Requests, QuotaExceeded | ARM / upgrade | Module 6 |
| 401, 403, AADSTS70021, Forbidden | Identity | Module 7 |
| Pending with Insufficient cpu/memory | Pod / capacity | K8s 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.
Blind-box diagnosis workflow
Fault-stacking example: three symptoms on one 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.
90-second evidence collection script aks-triage.sh
| Section | What it collects | Layer |
|---|---|---|
| ARM | Cluster / node pool status, failed operations in the last 24 hours | ① |
| Node | Node status, conditions, taints, Quarantined label, auto-repair events | ③ |
| Workloads | Non-Running Pods, Warning events, PDBs with ALLOWED=0 | ④⑥ |
| Network | Services 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)
./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)
./aks-triage.sh > /dev/null; ls -t triage-*.txt | head -1
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.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.
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
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
Official documentation
- AKS troubleshooting documentation
- Use Kubernetes events for troubleshooting in AKS
- Agentic CLI for AKS (preview) troubleshooting
Video storyboard (about 90 seconds)
This course material can't generate a video or MP3 directly, so a storyboard and narration script are provided.
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.
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.
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.
Visual: fix command → verify 200 → write the runbook and alerts.
Narration: After a fix, always verify it, and write down the prevention steps.
Command cheat sheet
① 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 / symptom | Layer | First command | Common fix |
|---|---|---|---|
Kubelet stopped posting node status. | Node | az vmss run-command invoke ... systemctl is-active kubelet | Restart the process or node; roll back the network change |
OutboundConnFailVMExtensionError / exit 50 | Outbound | On the node: curl -v --insecure --proxy-insecure https://mcr.microsoft.com/v2/ | Allow the FQDNs; fix the UDR/DNS |
InsufficientSubnetSize | ARM/network | az aks nodepool list (max-count, maxPods) | New subnet + new pool; lower max-count/surge |
SubnetIsFull | ARM/network | az network vnet subnet show | Retry after scale-in; separate subnet node pool |
| Intermittent timeouts to a single external target | SNAT | LB metric SNAT Connection Count (Failed) | Connection reuse; ports + IPs; NAT Gateway |
EXTERNAL-IP <pending> | LB | kubectl describe svc | Cluster identity permissions, annotations, policy |
| Endpoints empty | Service | get endpointslices | Fix selector / readiness |
CoreDNS i/o timeout | DNS | CoreDNS logs + coredns-custom | Upstream 168.63.129.16; UDP+TCP 53 |
UpgradeFailed ... Too Many Requests | Upgrade | kubectl get pdb -A | Fix PDB → retry same version; Cordon |
QuotaExceeded | Upgrade | az vm list-usage | Lower surge / raise quota → reconcile |
401 Unauthorized (pull) | Identity | az aks check-acr | AcrPull / Repository Reader |
403 Forbidden (pull) | Network access | nslookup <acr>.azurecr.io | Private DNS link / ACR firewall |
AADSTS70021 | Workload Identity | Compare issuerUrl with the federated credential | Trailing 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
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.
./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
./aks-triage.sh, and save the output as incident evidence.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.az vmss run-command invoke to check the kubelet state and recover it (or watch the auto-repair events), and record a timeline.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.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)../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
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
Source table
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| Diagnose and solve problems | Smart self-diagnosis, with no extra setup and no extra charge. Category tiles; View details shows the summary, errors, recommended actions, docs, metrics, and logs | aks-diagnostics |
| command invoke | RBAC: 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 disableRunCommand | access-private-cluster |
| kubectl debug node | Image mcr.microsoft.com/azurelinux/busybox:1.36, chroot /host; delete the node-debugger Pod when done; get the private IP with az aks machine list | node-access |
| Node heartbeat and NotReady | Lease 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 configuration | basic · after-healthy |
| Node auto-repair | Consecutive 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-repair | node-auto-repair |
| InsufficientSubnetSize | Full 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 MaxCount | insufficientsubnetsize |
| SubnetIsFull | Original message (VMSSAgentPoolReconciler); scale-in or a subnet-separated node pool | subnetisfull-upgrade |
| SNAT and LB outbound | AllocatedOutboundPorts 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 issues | configure-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 endpoints | outboundconnfail |
| Default health probe behavior and annotations | Local → HTTP /healthz; Cluster TCP; appProtocol http → /; probe annotations; Basic LB retired on 2025-09-30 | configure-load-balancer-standard |
| Application routing NGINX retirement | Upstream 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 implementation | AKS 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 Disabled | upgrade-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 options | Pre-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-01 | upgrade-options |
| QuotaExceeded | Original message; two-level quota (region and series); az vm list-usage; reconciliation commands | quota-exceeded-error |
| ACR pull | Three 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 caching | cannot-pull-image-from-acr |
| Workload Identity | AADSTS70021 (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 AKS | Preview; extension aks-agent, command az aks agent; client mode / cluster mode | agentic-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-upgraderequire 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 withaz 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.