TExcelTAD
Home › Kubernetes › Troubleshooting

Troubleshooting

Most Kubernetes problems fall into a handful of patterns, and the STATUS column of kubectl get pods usually tells you which one. Learn to read it and you'll solve the majority of incidents in minutes.

The three commands

bash
kubectl get pods -o wide            # what state is it in? which node?
kubectl describe pod <pod>          # why? (conditions, last state, events at the bottom)
kubectl logs <pod> [--previous]     # what did the app say?

Then, as needed: kubectl get events, kubectl exec -it <pod> -- sh, kubectl debug, kubectl port-forward.

Status → cause → fix

Status Usual cause Where to look
Pending No node fits (requests, selectors, taints), or an unbound PVC describe pod events: FailedScheduling
ContainerCreating (stuck) Volume can't attach/mount, missing Secret/ConfigMap, CNI problem describe pod events
ImagePullBackOff / ErrImagePull Typo in image/tag, private registry without imagePullSecrets describe pod: "manifest unknown", "unauthorized"
CrashLoopBackOff App exits on start: bad config, missing env, failed DB connection logs --previous, exit code
OOMKilled (last state) Memory limit too low or a leak describe pod: Reason: OOMKilled, exit 137
Running but 0/1 READY Readiness probe failing describe pod events: Unhealthy
CreateContainerConfigError Referenced ConfigMap/Secret key missing, runAsNonRoot vs root image describe pod
Terminating (stuck) Finalizers, or the node is unreachable get pod -o yaml (finalizers), node status
Evicted Node ran out of memory/disk describe pod, node conditions

Here is that table as a small diagnosis assistant. It reads a simplified Pod status (the shape of kubectl get pod -o yaml) and suggests the next step:

python · try it yourself
import yaml

def diagnose(pod):
    s = pod["status"]
    if s["phase"] == "Pending" and not s.get("containerStatuses"):
        cond = next((c for c in s.get("conditions", []) if c["type"] == "PodScheduled"), {})
        return f"not scheduled: {cond.get('message', 'unknown')} -> check requests, nodeSelector, taints"
    for cs in s.get("containerStatuses", []):
        waiting = cs.get("state", {}).get("waiting", {})
        last = cs.get("lastState", {}).get("terminated", {})
        reason = waiting.get("reason")
        if reason in ("ImagePullBackOff", "ErrImagePull"):
            return f"{cs['name']}: cannot pull image {cs['image']!r} -> check name/tag and imagePullSecrets"
        if reason == "CrashLoopBackOff":
            if last.get("reason") == "OOMKilled":
                return f"{cs['name']}: OOMKilled (exit {last['exitCode']}) -> raise memory limit or fix leak"
            return f"{cs['name']}: crashes with exit {last.get('exitCode')} -> kubectl logs --previous"
        if reason == "CreateContainerConfigError":
            return f"{cs['name']}: {waiting.get('message')} -> create the missing ConfigMap/Secret key"
        if not cs.get("ready"):
            return f"{cs['name']}: running but not Ready -> check the readiness probe"
    return "looks healthy"

pods = yaml.safe_load_all("""
metadata: {name: api-1}
status:
  phase: Pending
  conditions:
    - {type: PodScheduled, status: "False", message: "0/3 nodes are available: 3 Insufficient memory."}
---
metadata: {name: api-2}
status:
  phase: Pending
  containerStatuses:
    - {name: api, image: ghcr.io/acme/api:2.4.O, ready: false, state: {waiting: {reason: ImagePullBackOff}}}
---
metadata: {name: worker-1}
status:
  phase: Running
  containerStatuses:
    - name: worker
      image: ghcr.io/acme/worker:1.2
      ready: false
      state: {waiting: {reason: CrashLoopBackOff}}
      lastState: {terminated: {reason: OOMKilled, exitCode: 137}}
---
metadata: {name: web-1}
status:
  phase: Running
  containerStatuses:
    - {name: web, image: nginx:1.27, ready: false, state: {running: {}}}
---
metadata: {name: api-3}
status:
  phase: Pending
  containerStatuses:
    - name: api
      image: ghcr.io/acme/api:2.4.0
      ready: false
      state: {waiting: {reason: CreateContainerConfigError, message: "secret \\"db-credentials\\" not found"}}
""")
for pod in pods:
    print(f"{pod['metadata']['name']:9} {diagnose(pod)}")
api-1     not scheduled: 0/3 nodes are available: 3 Insufficient memory. -> check requests, nodeSelector, taints
api-2     api: cannot pull image 'ghcr.io/acme/api:2.4.O' -> check name/tag and imagePullSecrets
worker-1  worker: OOMKilled (exit 137) -> raise memory limit or fix leak
web-1     web: running but not Ready -> check the readiness probe
api-3     api: secret "db-credentials" not found -> create the missing ConfigMap/Secret key

(Did you spot the typo in api-2's image? 2.4.O with a letter O.)

Exit codes

A container's exit code is often the quickest clue:

python · try it yourself
import signal

def explain(code):
    if code == 0:
        return "success"
    if code > 128:
        sig = code - 128
        name = signal.Signals(sig).name
        hint = {"SIGKILL": "killed: OOM kill or forced termination after the grace period",
                "SIGTERM": "terminated: normal stop request (deploy, scale-down, eviction)",
                "SIGSEGV": "segmentation fault in the app"}.get(name, "killed by a signal")
        return f"128 + {sig} ({name}): {hint}"
    return {1: "generic application error: read the logs",
            2: "misuse of a shell builtin / bad arguments",
            126: "command found but not executable (permissions)",
            127: "command not found: wrong command/args or missing binary"}.get(code, "application-specific error")

for code in [0, 1, 127, 137, 139, 143]:
    print(f"exit {code:3}: {explain(code)}")
exit   0: success
exit   1: generic application error: read the logs
exit 127: command not found: wrong command/args or missing binary
exit 137: 128 + 9 (SIGKILL): killed: OOM kill or forced termination after the grace period
exit 139: 128 + 11 (SIGSEGV): segmentation fault in the app
exit 143: 128 + 15 (SIGTERM): terminated: normal stop request (deploy, scale-down, eviction)

Debugging inside the cluster

bash
# a throwaway Pod with network tools, in the same namespace
kubectl run debug --rm -it --image=nicolaka/netshoot -- bash
#   curl -v http://api:80/healthz ; nslookup api ; nc -zv db 5432

# attach an ephemeral debug container to a running Pod (shares its process namespace)
kubectl debug -it api-7d9f-x2k4p --image=busybox:1.37 --target=api

# a copy of a crashing Pod with a different command, to look around
kubectl debug api-7d9f-x2k4p -it --copy-to=api-debug --container=api -- sh

# debug a node (runs a privileged Pod with the host filesystem at /host)
kubectl debug node/demo-worker -it --image=busybox:1.37

A checklist for "my Service doesn't work"

  1. Are the Pods Running and READY 1/1? (kubectl get pods -l app=api)
  2. Does the Service have endpoints? (kubectl get endpointslices -l kubernetes.io/service-name=api). Empty means selector/label mismatch or no Ready Pods.
  3. Does targetPort match the port the container listens on?
  4. Does it work from inside? (kubectl run … curl http://api). If yes, the problem is Ingress/LoadBalancer; if no, DNS or NetworkPolicy.
  5. Any NetworkPolicy selecting the Pods? (kubectl get netpol)

Tip: Change one thing at a time and re-check. And look at what changed recently (kubectl rollout history, Git log, helm history): most outages follow a change.

Test yourself

A Pod shows ImagePullBackOff. What is the most likely cause?

  1. Not enough memory
  2. A wrong image name/tag or missing registry credentials
  3. A failing readiness probe
  4. A NetworkPolicy

A container's last state shows exit code 137. What happened?

  1. It exited normally
  2. It was killed with SIGKILL, often an OOM kill
  3. Command not found
  4. It segfaulted

A Service has no endpoints. What do you check first?

  1. etcd backups
  2. Whether the Service selector matches the Pods' labels and the Pods are Ready
  3. The kubelet version
  4. The Ingress class