Skip to main content

Troubleshooting

Core

Drill until fluent: hands-on rounds test this directly. Phase 4 of the Learning Path.

Docs: Debug Pods Β· Debug Services Β· Debug running Pods Β· Learnk8s visual guide

Overview​

Debugging Kubernetes is a walk down the six-step chain behind every kubectl apply. kubectl get pods tells you which step broke; the STATUS column is the index into this page. The method is always the same: read the status, run the one command that explains that status, fix the cause, and confirm with the same command. Guessing, or restarting things to see what happens, wastes the most time in the exam and in interviews.

Figure 13-1: Troubleshooting decision tree. Amber marks the one command to run first for each status.

Key concepts​

Status β†’ first command β†’ usual causes​

StatusStage that failedFirst commandUsual causes
No Pods at allAdmissionkubectl describe rs (or describe job)ResourceQuota exceeded, Pod Security violation, bad ServiceAccount
PendingSchedulingkubectl describe pod β†’ EventsRequests too big, taints, nodeSelector/affinity, PVC not bound
ContainerCreating (stuck)Volume attach, network setupkubectl describe pod β†’ EventsMissing ConfigMap/Secret volume, Multi-Attach error, CNI failure
ErrImagePull / ImagePullBackOffImage pullkubectl describe pod β†’ EventsTag typo, private registry without imagePullSecrets, rate limits
CreateContainerConfigErrorContainer configkubectl describe pod β†’ EventsMissing ConfigMap/Secret or key, runAsNonRoot with a root image
RunContainerErrorContainer startkubectl describe podCommand not found in image, bad mount path
CrashLoopBackOffRunningkubectl logs --previousApp error at startup, missing config, liveness probe killing it
OOMKilled (in Last State)Runningkubectl describe podMemory limit too low, leak
Running, 0/1 ReadyReadinesskubectl describe pod β†’ probe eventsWrong probe path/port, dependency down, too slow
Running, unreachableService routingkubectl describe svc β†’ EndpointsSelector/label mismatch, wrong targetPort, NetworkPolicy
Terminating (stuck)Deletionkubectl get pod -o yaml β†’ finalizersFinalizer controller gone, node unreachable

Exit codes​

CodeMeaningUsual cause
0Clean exitA long-running app exiting means it has nothing to do: wrong command, or a Job in a Deployment
1App errorRead the logs
126Command not executablePermissions, wrong architecture binary
127Command not foundTypo in command, or the binary isn't in the image
137SIGKILL (128+9)OOMKilled, or killed after the grace period
139SIGSEGV (128+11)Crash in native code
143SIGTERM (128+15)Normal shutdown during a rollout or scale-down

Timeout vs refused​

Symptom from a client PodLikely cause
bad address / could not resolve hostName doesn't exist: typo, or the Service is in another namespace
Connection refusedService has no endpoints (kube-proxy rejects), or wrong targetPort
TimeoutNetworkPolicy drop (a blocked DNS lookup looks like this too), or the app accepted but hangs

β†’ See Services & Ingress and Network Policy.

kubectl essentials​

The core loop:

kubectl get pods -o wide # STATUS, RESTARTS, node, IP
kubectl describe pod <pod> # Events at the bottom: read them first
kubectl logs <pod> --previous # output of the crashed container
kubectl get events --sort-by=.lastTimestamp --field-selector type=Warning
kubectl get pod <pod> -o yaml | less # the full spec and status as the API sees it

When no Pods appear:

kubectl describe deployment <name> # Conditions: ReplicaFailure
kubectl describe rs -l app=<name> # FailedCreate events: quota, Pod Security

Get inside:

kubectl exec -it <pod> -- sh # if the image has a shell
kubectl debug -it <pod> --image=busybox:1.36 --target=<container> # ephemeral container, shares process namespace
kubectl debug <pod> -it --copy-to=dbg --container=<container> -- sh # copy of the Pod with a shell instead of the app
kubectl debug node/<node> -it --image=busybox:1.36 # shell on the node, host fs at /host
kubectl port-forward pod/<pod> 8080:8080 # bypass Service and Ingress
kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://<svc>

πŸ§ͺ Lab​

Lab 4-1 β˜…β˜…β˜…

Requires: Standard lab setup Β· Config & Secrets Β· Services & Ingress Β· How the tiers work.

Three bugs, one manifest.

Goal

Save this as broken.yaml and apply it to namespace lab4-1. Make wget -qO- http://web from a Pod in the namespace return the nginx welcome page. Fix every problem using only get, describe, logs and edit/set/patch, and write down the status that led you to each fix.

apiVersion: v1
kind: ConfigMap
metadata:
name: web-conf
data:
MODE: prod
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 2
selector:
matchLabels: {app: web}
template:
metadata:
labels: {app: web}
spec:
containers:
- name: nginx
image: nginx:1.27-alpinee
env:
- name: MODE
valueFrom:
configMapKeyRef: {name: web-config, key: MODE}
ports: [{containerPort: 80}]
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector: {app: webapp}
ports:
- port: 80
targetPort: 80

Verify

kubectl -n lab4-1 get pods # 2/2 Running, 1/1 Ready each
kubectl -n lab4-1 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://web | head -4
🟑 Hints
  1. Start with kubectl get pods and look up the STATUS in the status table. It tells you the first command to run.
  2. Two of the bugs show up as Pod statuses, one after the other. The third only shows up when you call the Service.
  3. Fix at the owner: kubectl set image and kubectl patch deployment, not the Pods.
  4. For the Service, compare describe svc β†’ Selector with get pods --show-labels.
🟒 Guided
  1. Create the lab namespace.

    kubectl create namespace lab4-1
  2. Apply the broken manifest.

    kubectl -n lab4-1 apply -f broken.yaml
  3. Read the status: ErrImagePull / ImagePullBackOff.

    kubectl -n lab4-1 get pods
  4. Read the first Pod's events: Failed to pull image nginx:1.27-alpinee: not found (tag typo).

    kubectl -n lab4-1 describe pod -l app=web | grep -A3 Events -m1
  5. Fix the tag on the Deployment.

    kubectl -n lab4-1 set image deployment/web nginx=nginx:1.27-alpine
  6. Read the status again: CreateContainerConfigError.

    kubectl -n lab4-1 get pods
  7. Find the message: configmap "web-config" not found (the ConfigMap is called web-conf).

    kubectl -n lab4-1 describe pod -l app=web | grep -i configmap
  8. Point the env var at the right ConfigMap.

    kubectl -n lab4-1 patch deployment web --type=json \
    -p '[{"op":"replace","path":"/spec/template/spec/containers/0/env/0/valueFrom/configMapKeyRef/name","value":"web-conf"}]'
  9. Wait for the fixed Pods.

    kubectl -n lab4-1 rollout status deployment/web
  10. Call the Service: Connection refused.

    kubectl -n lab4-1 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://web
  11. See why: app=webapp, Endpoints: <none>.

    kubectl -n lab4-1 describe svc web | grep -E "Selector|Endpoints"
  12. Fix the selector; Verify now succeeds.

    kubectl -n lab4-1 patch svc web -p '{"spec":{"selector":{"app":"web"}}}'
  13. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab4-1

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
kubectl -n lab4-1 run chk --image=busybox:1.36 --restart=Never -- sleep 600 2>/dev/null; kubectl -n lab4-1 wait --for=condition=Ready pod/chk >/dev/null
t "2 Pods Ready" "$(kubectl -n lab4-1 get deploy web -o jsonpath='{.status.readyReplicas}')" "2"
t "web answers" "$(kubectl -n lab4-1 exec chk -- wget -qO- -T 3 http://web | grep -o '<title>.*</title>')" "<title>Welcome to nginx!</title>"

β†’ More drills in the same format: Troubleshooting Drills.

Gotchas​

  • Read Events before logs. Most failures before Running never produce app logs at all.
  • No Pods means look one level up. Admission errors land on the ReplicaSet or Job, not on a Pod that doesn't exist.
  • CrashLoopBackOff waits grow to 5 minutes. After a fix, kubectl delete pod skips the wait.
  • --previous or nothing. The current container's log starts empty after each restart.
  • Events expire after about an hour. For overnight failures, use the log system.
  • Distroless images have no shell. kubectl exec -- sh fails. Use kubectl debug --target.
  • Fix the owner. Editing a Pod owned by a Deployment is undone. Fix the Deployment.

Scenario questions​

Q1 β˜… A Deployment shows 0/3 ready and kubectl get pods shows nothing. Where are the Pods?

Model answer
  • Clarify: new Deployment, or did this start after a namespace change (a quota or Pod Security label)?
  • Observe: kubectl describe deployment β†’ ReplicaFailure. kubectl describe rs β†’ FailedCreate: exceeded quota or violates PodSecurity.
  • Hypothesise: admission rejects every Pod the ReplicaSet tries to create. Nothing exists to show.
  • Fix: add requests the quota needs (or raise the quota), or fix the securityContext.
  • Prevent: teach the team to go one level up when Pods are missing. Alert on FailedCreate events.

Q2 β˜…β˜… A Pod is Pending with 0/3 nodes are available: 1 node(s) had untolerated taint {dedicated: gpu}, 2 Insufficient memory. Explain and fix.

Model answer
  • Clarify: is this Pod meant for the GPU node? How much memory does it request?
  • Observe: the message covers every node: one is tainted for GPU workloads, two lack free memory (by requests, not usage).
  • Hypothesise: a regular Pod with a large memory request and no GPU toleration. Nowhere is legal.
  • Fix: right-size the memory request, or add capacity. Only add a toleration if it really belongs on the GPU node.
  • Prevent: check requests against kubectl describe node allocatable; let the cluster autoscaler add nodes for legitimate demand.

Q3 β˜…β˜… A container crashes instantly and kubectl logs --previous is empty. What next?

Model answer
  • Clarify: new image or new command/args?
  • Observe: kubectl describe pod β†’ Last State exit code. 127 is command not found, 126 not executable, 0 means the process simply finished.
  • Hypothesise: the process dies before writing anything: wrong entrypoint, a missing binary, or a script that exits.
  • Fix: start a copy with a shell and inspect it: kubectl debug <pod> -it --copy-to=dbg --container=<name> -- sh, then run the command by hand.
  • Prevent: smoke-test images in CI by running their real entrypoint.

Q4 β˜…β˜…β˜… Users report the app is "slow sometimes". Nothing is crashing. How do you approach it?

Model answer
  • Clarify: which endpoints, how slow, since when, all users or some? Is there a pattern: time of day, after deploys?
  • Observe: kubectl top pods against requests and limits, restart counts, readiness flapping in events, HPA activity (kubectl describe hpa), and whether slow requests come from particular Pods or nodes.
  • Hypothesise: CPU throttling from limits; one bad node; Pods flapping in and out of endpoints; cold Pods after HPA scale-out without warm-up; a slow dependency.
  • Fix: follow the evidence. Throttling β†’ remove or raise CPU limits (β†’ Resources & Scaling); cold starts β†’ readiness that waits for warm-up; one bad node β†’ cordon and drain.
  • Prevent: per-Pod latency metrics and tracing. kubectl shows the present; intermittent problems need history.

Summary​

  • STATUS picks the command. Pending and pull errors β†’ describe; crashes β†’ logs --previous; unreachable β†’ describe svc.
  • Events explain everything before Running. Logs explain everything after.
  • Missing Pods mean admission. Describe the ReplicaSet.
  • Exit code 137 is a kill, usually OOM. 127 is a missing command.
  • Walk the chain in order. Admission, scheduling, pull, start, readiness, Service. Stop at the first broken link.

Next in path β†’ Troubleshooting Drills