Debugging Non-Functional Kubernetes Pods: A Systematic Diagnostic Framework
System DesignModel answerLast updated
Outline a structured troubleshooting approach for diagnosing and resolving broken Kubernetes pods, detailing state transitions, kubectl commands, diagnostic paths, and mitigation techniques.
Imagine you are on call and receive an alert indicating that a Kubernetes workload is failing, but no specific error details are provided. Describe a structured, end-to-end diagnostic workflow for investigating and resolving the issue using kubectl.
Your answer should address:
- Initial Assessment & Scoping: How to determine the scale of the failure (single pod vs. entire workload vs. node-wide) and prioritize initial checks.
- State-Driven Diagnostics: How to inspect pod status, container states, and cluster events, mapping specific pod phases (e.g.,
Pending,ImagePullBackOff,CrashLoopBackOff,OOMKilled, running but unready) to their root causes. - Deep Investigation Techniques: How to effectively leverage application logs (including previous instances), ephemeral debug containers, networking checks (DNS, Service endpoints, NetworkPolicies), and node conditions.
- Remediation & Incident Management: How to mitigate immediate customer impact while preserving operational state for root-cause analysis.
Hints
Hint 1
Start top-down: check cluster/namespace events and high-level pod statuses before diving into individual application logs.
Hint 2
Pay close attention to container termination reasons (like exit codes and OOMKilled flags) and distinguish between startup failures, probe failures, and runtime crashes.
Hint 3
Separate immediate incident containment (restoring availability) from post-mortem root-cause analysis.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Initial Assessment & Scope Determination
When investigating an unspecified pod failure, avoid randomly running commands or immediately deleting pods. A structured, top-down workflow narrows the scope efficiently:
Step 1: Broad Status Check
Run high-level diagnostics to check the scope across the namespace:
# View pod status, restart counts, and node assignments
kubectl get pods -n <namespace> -o wide
# Check recent namespace events sorted by time
kubectl get events -n <namespace> --sort-by='.metadata.creationTimestamp'
Step 2: Determine Scope
- Single Pod: Likely a localized issue (e.g., disk full on a specific node, transient hardware issue, or specific data payload causing a crash).
- All Pods in Deployment: Configuration error (bad environment variable, missing Secret/ConfigMap), application binary bug, missing dependency, or image registry issue.
- All Pods on a Specific Node: Node failure (DiskPressure, MemoryPressure, Kubelet non-responsive, or CNI plugin crash).
2. State-Driven Diagnostic Tree
Inspect the detailed state of the target pod using:
kubectl describe pod <pod-name> -n <namespace>
Look at the Events section at the bottom and the State / Last State fields of individual containers.
┌──────────────────────────────┐
│ kubectl describe pod <name> │
└──────────────┬───────────────┘
│
┌────────────────────────────┼───────────────────────────┐
▼ ▼ ▼
[ Pending ] [ ImagePullBackOff ] [ CrashLoopBackOff ]
│ │ │
- Resource limits - Bad image tag - Exit Code 137 (OOM)
- Unsatisfied Taints - Missing image pull secret - Exit Code 1 (App Err)
- Unbound PVCs - Registry throttled - Failed liveness probe
│ │ │
▼ ▼ ▼
[ Check Node Cap ] [ Verify Secret ] [ Check Logs/Limits ]
Scenario A: Pod Status is Pending
- Meaning: The Kubernetes scheduler cannot place the pod on any node.
- Common Root Causes:
- Insufficient CPU/Memory: Node capacity cannot satisfy container
resources.requests. - Unbound PersistentVolumeClaim (PVC): Storage provisioner hasn't bound a PV.
- Node Affinity / Taints / Tolerations: Taints on nodes block scheduling;
nodeSelectormatches zero nodes.
- Insufficient CPU/Memory: Node capacity cannot satisfy container
- Diagnostic Commands:
# Look for 'FailedScheduling' events kubectl describe pod <pod-name> -n <namespace> # Check aggregate cluster resources kubectl describe nodes | grep -A 8 "Allocated resources"
Scenario B: ImagePullBackOff or ErrImagePull
- Meaning: The node kubelet cannot download the specified container image.
- Common Root Causes:
- Incorrect image tag or repository name.
- Missing or invalid
imagePullSecretsfor a private registry. - Network egress blocked to the container registry, or registry rate limits exceeded.
- Diagnostic Check:
Inspect the exact event error in
kubectl describe pod <pod-name>. It clearly states whether it was a404 Not Found,403 Unauthorized, orTimeout.
Scenario C: CrashLoopBackOff or OOMKilled
- Meaning: The container starts, fails, and restarts repeatedly with exponential backoff.
- Diagnostic Step: Check the container exit code and termination state.
-
OOMKilled(Exit Code 137):- Cause: Container memory usage exceeded
resources.limits.memory, or the Linux kernel out-of-memory killer terminated the process. - Fix: Increase memory limits or profile the application for memory leaks.
- Cause: Container memory usage exceeded
-
Application Error (Exit Code 1 or non-zero):
- Cause: Missing configuration, unhandled application exception, or unreachable database on startup.
- Diagnostic: Check application logs (see Section 3).
-
Failed Probes:
- Cause: Failing
startupProbeorlivenessProbe. Checkdescribe podevents for "Liveness probe failed".
- Cause: Failing
Scenario D: Pod is Running but NOT Ready (0/1 Containers Ready)
- Meaning: The application is running, but passing readiness probes fails, meaning traffic is not routed to this pod by Services.
- Common Root Causes:
- Readiness Probe Failure: Misconfigured HTTP path, incorrect port, or initial delay too short.
- Dependency Timeout: Application is stuck waiting for a database connection or cache warmup.
- Diagnostic Commands:
kubectl describe pod <pod-name> -n <namespace> # Check events for: "Readiness probe failed: HTTP probe failed with statuscode 500"
3. Advanced Logs & Deep-Dive Diagnostics
When kubectl describe points to an internal application failure, move deeper:
1. Container Logs (Current and Previous Execution)
If a container is crashing repeatedly, standard kubectl logs only shows the current (newly spawned) instance. Fetch logs from the instance that just crashed:
# Get logs from the crashed container instance
kubectl logs <pod-name> -n <namespace> --previous
# Get logs for multi-container pods
kubectl logs <pod-name> -c <container-name> -n <namespace> --previous
2. Ephemeral Debug Containers & Shell Access
If the container is running or minimal (e.g., Distroless / Scratch image without a shell):
# Attach an ephemeral debug container with diagnostic tools (tcpdump, curl, nslookup)
kubectl debug -it <pod-name> -n <namespace> --image=nicolaka/netshoot -- target=<container-name>
# Or exec directly if a shell exists:
kubectl exec -it <pod-name> -n <namespace> -- /bin/sh
3. Networking & Service Discovery Checks
If the application runs but clients report connection errors or timeouts:
-
Endpoints Check: Verify the Service actively routes traffic to the pod IP.
kubectl get endpoints <service-name> -n <namespace>If Endpoints is empty
<none>, selector labels on the Service do not match the Pod labels, or the Pod is notReady. -
DNS & Egress Resolution: Inside a debug container, test internal cluster DNS and network reachability:
nslookup <dependent-service>.<namespace>.svc.cluster.local curl -v http://<dependent-service>:<port>/health -
NetworkPolicies: Ensure strict egress or ingress rules aren't blocking cross-namespace traffic.
4. Remediation vs. Root-Cause Isolation
In a production incident, restoring service takes precedence over immediate root-cause identification. However, evidence must be preserved before modifying resources.
Mitigation Tactics (Immediate Relief)
- Bad Rollout: Revert deployment to the previous revision immediately.
kubectl rollout undo deployment/<deployment-name> -n <namespace> - Resource Starvation: Dynamically patch deployment limits to give temporary head room.
kubectl set resources deployment/<deployment-name> -c=<container> --limits=memory=2Gi - Failing Node: Cordons and drain a suspicious node if multiple pods crash on the same host.
kubectl cordon <node-name> kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
Evidence Preservation for Post-Mortem
Before deleting or restarting a failing pod (e.g., via kubectl delete pod):
- Save container logs to an external file (
kubectl logs --previous > crash_log.txt). - Save full YAML specs and events (
kubectl get pod <pod-name> -o yaml > pod_spec.yaml). - If heap dumps or core dumps are needed, attach a debug sidecar or copy files via
kubectl cpprior to pod deletion.
Summary Checklist
| Pod State / Symptom | Primary Diagnostic Check | Likely Solution |
|---|---|---|
Pending | kubectl describe pod -> Events | Adjust node capacity, lower requests, fix PVCs or Taints. |
ImagePullBackOff | kubectl describe pod -> Image error | Fix image name/tag, create/mount imagePullSecrets. |
OOMKilled (137) | kubectl describe pod -> Last State | Increase memory limit, fix application memory leak. |
CrashLoopBackOff (1) | kubectl logs --previous | Fix application bug, missing environment variable, or Secret. |
Running (0/1 Ready) | kubectl describe pod -> Probes | Fix readiness probe configuration or downstream dependency connection. |
Ready, but 502/503 | kubectl get endpoints | Fix Service label selectors or target ports. |