Skip to main content

Containers and Kubernetes · Intermediate · 30 min

Debug a failing Kubernetes pod with kubectl

By Padding · Updated 18 Nov 2026
Kubernetes 1.37 · kubectl 1.37 · kind 0.33

You will break Deployments on a kind cluster in six common ways, read each failure from kubectl get, describe, logs and events, fix it, and finish by opening a shell beside a distroless pod with kubectl debug.

On this page

When a pod does not work, Kubernetes usually tells you why. The answer is spread over three places: the status column in kubectl get, the container state and events in kubectl describe, and the application's own output in kubectl logs. Once you know which of the three to read for which symptom, most broken pods take a minute to diagnose.

In this tutorial you build that habit on purpose. You create a handful of small Deployments in a throwaway namespace, broken in six common ways: a bad image, an app that exits, a pod that cannot be scheduled, a memory kill, a readiness probe that never passes and a missing Secret key. For each one you read the symptom, find the cause and fix it. You finish with kubectl debug, which attaches a temporary debugging container to a pod whose image has no shell at all.

Everything runs on the kind cluster from run your first Kubernetes cluster with kind. The images are small, but they still come over your connection the first time. If you are on prepaid mobile data, as many readers in Nigeria and across Africa are, pull them once on Wi-Fi and copy them into the cluster, so the pods start from local copies:

Bash
for img in nginx:1.30-alpine busybox:1.37 python:3.15-slim gcr.io/distroless/python3-debian13; do
  docker pull "$img"
  kind load docker-image "$img"
done

The distroless manifest later sets imagePullPolicy: IfNotPresent, because an image without a tag counts as :latest and would otherwise be pulled again every time a pod starts. The other images have fixed tags, so the kubelet uses the copy already on the node. Only the deliberate typo in the first step still contacts the registry, and that failed lookup costs very little data.

Step 1 · Set up a scratch namespace and a triage routine

Make a folder for the manifests and a namespace for the broken workloads, so nothing you do here touches anything else on the cluster:

Bash
mkdir -p ~/pod-debug-demo
cd ~/pod-debug-demo
kubectl create namespace pod-debug-demo
kubectl config set-context --current --namespace=pod-debug-demo

The last command makes pod-debug-demo the default namespace for your current kubectl context, so the commands below do not need -n. The clean-up step sets it back.

Every failure in this tutorial is read with the same four commands. Learn their jobs now:

Bash
kubectl get pods
kubectl describe pod -l app=<name>
kubectl logs deploy/<name> --previous
kubectl get events --sort-by=.metadata.creationTimestamp
  • kubectl get pods gives you the symptom: the STATUS, READY and RESTARTS columns.
  • kubectl describe pod shows each container's State and Last State (with a Reason and Exit Code) and, at the bottom, the recent events for that pod. Most answers are here.
  • kubectl logs --previous prints what the last crashed copy of the container wrote before it died. Without --previous you see the current copy, which may have printed nothing yet.
  • kubectl get events --sort-by=.metadata.creationTimestamp lists everything that happened in the namespace, oldest first. kubectl events --for pod/<pod-name> narrows that to one object.

<name> is a placeholder: replace it with the Deployment name each step uses.

Check it worked

kubectl config view --minify --output 'jsonpath={..namespace}' prints pod-debug-demo, and kubectl get pods prints No resources found in pod-debug-demo namespace.

Step 2 · Fix an ImagePullBackOff

Write a Deployment with a typo in the image tag (alpline instead of alpine) and apply it:

Bash
cat > typo.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: typo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: typo
  template:
    metadata:
      labels:
        app: typo
    spec:
      containers:
        - name: web
          image: nginx:1.30-alpline
EOF
kubectl apply -f typo.yaml
kubectl get pods -l app=typo

Within a few seconds the status shows ErrImagePull, then ImagePullBackOff. ErrImagePull is a single failed attempt. ImagePullBackOff means the kubelet has failed more than once and is now waiting longer between tries. Neither tells you why, so describe the pod:

Bash
kubectl describe pod -l app=typo

Read the Events section at the bottom. A Failed event says something like failed to pull and unpack image "docker.io/library/nginx:1.30-alpline" ... not found. "Not found" means the name or tag is wrong. Fix the tag on the Deployment:

Bash
kubectl set image deploy/typo web=nginx:1.30-alpine
kubectl rollout status deploy/typo

When the image is private

The same ImagePullBackOff appears when the image exists but the registry refuses to hand it over. The event then says something like pull access denied, 401 Unauthorized or 403 Forbidden instead of not found. Kubernetes needs registry credentials in a Secret of type kubernetes.io/dockerconfigjson, named in the pod spec under imagePullSecrets.

If you have a private image to try, log in once with docker login <registry> (it prompts for the password, so nothing lands in your shell history), then build the Secret from the file that login wrote:

Bash
kubectl create secret generic regcred \
  --from-file=.dockerconfigjson="$HOME/.docker/config.json" \
  --type=kubernetes.io/dockerconfigjson

This only works if ~/.docker/config.json contains an auths entry with credentials in it. Docker Desktop and some Linux setups keep the password in a credential helper instead, and the file then holds only a credsStore line; in that case create a read-only access token in your registry and log in with it on a machine without a helper. Then reference the Secret in the pod template, next to containers:

YAML
    spec:
      imagePullSecrets:
        - name: regcred
      containers:
        - name: web
          image: <registry>/<team>/<image>:<tag> # replace this with your private image

Check it worked

kubectl get pods -l app=typo shows 1/1 under READY and Running under STATUS, and kubectl describe pod -l app=typo now ends with Pulled, Created and Started events.

Step 3 · Fix a CrashLoopBackOff

This Deployment runs a script that refuses to start without a DATABASE_URL setting and exits with code 3:

Bash
cat > crashy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: crashy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: crashy
  template:
    metadata:
      labels:
        app: crashy
    spec:
      containers:
        - name: app
          image: busybox:1.37
          command:
            - sh
            - -c
            - |
              if [ -z "$DATABASE_URL" ]; then
                echo "fatal: DATABASE_URL is not set" >&2
                exit 3
              fi
              echo "connecting to $DATABASE_URL"
              sleep 3600
EOF
kubectl apply -f crashy.yaml
kubectl get pods -l app=crashy --watch

Watch the RESTARTS count climb and the status flip between Error and CrashLoopBackOff. Press Ctrl+C to stop watching. CrashLoopBackOff is not the error itself: it means the container keeps exiting and the kubelet is waiting before the next restart, by default doubling the wait each time, up to five minutes on most clusters. Newer Kubernetes releases are shortening that default and let cluster operators set a different maximum, so your waits may be shorter.

Two questions find the cause: how did it exit, and what did it say first?

Bash
kubectl describe pod -l app=crashy
kubectl logs deploy/crashy --previous

In describe, Last State: Terminated shows Reason: Error and Exit Code: 3. The log of the previous run prints fatal: DATABASE_URL is not set. Exit codes are a quick first clue:

  • 1, or another small number such as 3: the application chose to exit. Read its log.
  • 126 or 127: the command could not be run or was not found. Check command and args against what the image contains.
  • 137: killed with SIGKILL (128 + 9). Look for OOMKilled next to it; you meet that two steps on.
  • 143: stopped with SIGTERM (128 + 15), usually a normal shutdown or a failing liveness probe.

Give the app the setting it asked for:

Bash
kubectl set env deploy/crashy DATABASE_URL=postgres://db.example.internal:5432/app
kubectl rollout status deploy/crashy
kubectl logs deploy/crashy

The URL here holds no password. A real one with credentials belongs in a Secret, which is what the last broken Deployment is about.

Check it worked

kubectl get pods -l app=crashy shows a new pod, Running, with 0 restarts, and kubectl logs deploy/crashy prints connecting to postgres://db.example.internal:5432/app.

Step 4 · Fix pods stuck in Pending

Pending means the pod exists but no container has started. Usually the scheduler has not found a node for it. You make three Pending pods for three different reasons, then read the same event for each.

First, a pod that asks for more memory than the node has. The scheduler places pods by their requests, not by what they really use:

Bash
cat > greedy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: greedy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: greedy
  template:
    metadata:
      labels:
        app: greedy
    spec:
      containers:
        - name: web
          image: nginx:1.30-alpine
          resources:
            requests:
              memory: 64Gi
EOF

Second, a pod that only runs on nodes labelled disktype=ssd, which no node is:

Bash
cat > picky.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: picky
spec:
  replicas: 1
  selector:
    matchLabels:
      app: picky
  template:
    metadata:
      labels:
        app: picky
    spec:
      nodeSelector:
        disktype: ssd
      containers:
        - name: web
          image: nginx:1.30-alpine
EOF

Third, a pod that mounts a PersistentVolumeClaim asking for a StorageClass called fast-ssd, which does not exist on kind:

Bash
cat > claimy.yaml <<'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: claimy-data
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: fast-ssd
  resources:
    requests:
      storage: 100Mi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: claimy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: claimy
  template:
    metadata:
      labels:
        app: claimy
    spec:
      containers:
        - name: web
          image: nginx:1.30-alpine
          volumeMounts:
            - name: data
              mountPath: /data
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: claimy-data
EOF
kubectl apply -f greedy.yaml -f picky.yaml -f claimy.yaml
kubectl get pods

All three stay Pending. Look at the FailedScheduling events:

Bash
kubectl get events --sort-by=.metadata.creationTimestamp | grep -E 'FailedScheduling|ProvisioningFailed'

Each message starts with something like 0/1 nodes are available: and then names the reason. For greedy it is Insufficient memory. For picky it is that the node didn't match Pod's node affinity/selector. For claimy the pod event mentions an unbound PersistentVolumeClaim, and kubectl describe pvc claimy-data shows the claim itself Pending with a note that the fast-ssd StorageClass was not found.

Fix each one in the way that suits its cause. For greedy, ask for a size that fits; a real app should request roughly what it uses, as covered in set CPU and memory requests and limits:

Bash
kubectl set resources deploy/greedy --requests=memory=64Mi

For picky, either remove the selector or give a node the label. kind names its single node kind-control-plane; check yours with kubectl get nodes and replace the name if it differs:

Bash
kubectl label node kind-control-plane disktype=ssd

A claim's StorageClass cannot be changed after it is created, so claimy needs its claim replaced. The claim is protected while a pod uses it, so delete the Deployment first, then the claim, then apply a fixed copy that uses kind's default standard class:

Bash
kubectl delete deploy/claimy
kubectl delete pvc/claimy-data
kubectl get storageclass
sed 's/storageClassName: fast-ssd/storageClassName: standard/' claimy.yaml > claimy-fixed.yaml
kubectl apply -f claimy-fixed.yaml

kubectl get storageclass should list standard marked (default). If your cluster's default class has another name, open claimy-fixed.yaml and put that name on the storageClassName line before applying.

Check it worked

kubectl get pods shows the greedy, picky and claimy pods all Running, and kubectl get pvc claimy-data shows Bound under STATUS.

Step 5 · Fix an OOMKilled container

This Deployment gives Python a 64 MiB memory limit and then builds a 200 MiB string:

Bash
cat > hungry.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hungry
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hungry
  template:
    metadata:
      labels:
        app: hungry
    spec:
      containers:
        - name: worker
          image: python:3.15-slim
          command:
            - python3
            - -c
            - |
              import time
              data = b"x" * (200 * 1024 * 1024)
              print("loaded", len(data), "bytes", flush=True)
              time.sleep(3600)
          resources:
            requests:
              memory: 64Mi
            limits:
              memory: 64Mi
EOF
kubectl apply -f hungry.yaml
kubectl get pods -l app=hungry --watch

The status shows OOMKilled for a moment, then CrashLoopBackOff as the restarts pile up. Press Ctrl+C. This is one of the cases where the log will not help: the kernel killed the process before it could print anything. describe has the answer:

Bash
kubectl describe pod -l app=hungry

Under Last State: Terminated you see Reason: OOMKilled and Exit Code: 137. The container went over its memory limit, so the kernel stopped it. You have two choices: make the program use less memory, or give it a limit that matches what it really needs. Here the work needs about 200 MiB, so raise both values:

Bash
kubectl set resources deploy/hungry --requests=memory=256Mi --limits=memory=256Mi
kubectl rollout status deploy/hungry

Check it worked

kubectl logs deploy/hungry prints loaded 209715200 bytes, and kubectl get pods -l app=hungry shows the new pod Running with 0 restarts.

Step 6 · Fix a readiness probe that never passes

A pod can be Running and still receive no traffic. This nginx Deployment has a readiness probe pointing at /healthz, a path nginx does not serve, and a Service in front of it:

Bash
cat > notready.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notready
spec:
  replicas: 1
  selector:
    matchLabels:
      app: notready
  template:
    metadata:
      labels:
        app: notready
    spec:
      containers:
        - name: web
          image: nginx:1.30-alpine
          ports:
            - containerPort: 80
          readinessProbe:
            httpGet:
              path: /healthz
              port: 80
            periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: notready
spec:
  selector:
    app: notready
  ports:
    - port: 80
      targetPort: 80
EOF
kubectl apply -f notready.yaml
kubectl get pods -l app=notready

STATUS says Running but READY stays at 0/1, and RESTARTS stays at 0. A failing readiness probe never restarts a container; it only keeps the pod out of the Service. Confirm both halves:

Bash
kubectl describe pod -l app=notready
kubectl describe endpointslices -l kubernetes.io/service-name=notready

The pod's events repeat something like Readiness probe failed: HTTP probe failed with statuscode: 404. In the EndpointSlice, the pod's address is listed with Ready: false under its conditions, so the Service sends it nothing. Point the probe at a path that answers 200:

Bash
kubectl patch deploy/notready --type=json \
  -p='[{"op":"replace","path":"/spec/template/spec/containers/0/readinessProbe/httpGet/path","value":"/"}]'
kubectl rollout status deploy/notready

In your own apps, the better fix is usually the other way round: add a real health endpoint to the app, as keep Snip healthy with probes and graceful shutdown does.

Check it worked

kubectl get pods -l app=notready shows 1/1 under READY, and kubectl describe endpointslices -l kubernetes.io/service-name=notready shows Ready: true for the new pod's address.

Step 7 · Fix a CreateContainerConfigError

Create a Secret that holds only a user name, then a Deployment that also expects a DB_PASSWORD key from it:

Bash
kubectl create secret generic app-secrets --from-literal=DB_USER=app
cat > needsecret.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: needsecret
spec:
  replicas: 1
  selector:
    matchLabels:
      app: needsecret
  template:
    metadata:
      labels:
        app: needsecret
    spec:
      containers:
        - name: app
          image: busybox:1.37
          command: ["sh", "-c", 'echo "user $DB_USER has a password of ${#DB_PASSWORD} characters"; sleep 3600']
          env:
            - name: DB_USER
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: DB_USER
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: DB_PASSWORD
EOF
kubectl apply -f needsecret.yaml
kubectl get pods -l app=needsecret

The status is CreateContainerConfigError. The image pulled fine, but the kubelet cannot build the container's environment, so it never starts it. There are no logs to read. The event says exactly what is missing:

Bash
kubectl describe pod -l app=needsecret

Look for something like Error: couldn't find key DB_PASSWORD in Secret pod-debug-demo/app-secrets. The same status appears when the Secret or ConfigMap itself is missing, or a name is misspelt.

Add the key. The password is read at a prompt and written to a file that only you can read, so it never appears on the command line or in your shell history. Type any practice password when asked:

Bash
printf 'Practice DB password: '; stty -echo; read -r DB_PW; stty echo; echo
( umask 077; printf '%s' "$DB_PW" > db-password.txt )
unset DB_PW
kubectl delete secret app-secrets
kubectl create secret generic app-secrets \
  --from-literal=DB_USER=app \
  --from-file=DB_PASSWORD=db-password.txt
rm db-password.txt

The kubelet keeps retrying a pod in this state, so it starts on its own once the key exists, usually within a minute. If it has not, run kubectl rollout restart deploy/needsecret. Note that environment variables are read only when a container starts: changing the Secret later does not change a running pod until it restarts.

Check it worked

kubectl get pods -l app=needsecret shows Running, and kubectl logs deploy/needsecret prints user app has a password of <n> characters, where <n> is the length of what you typed. The password itself is never printed.

Step 8 · Open a shell beside a distroless pod with kubectl debug

Minimal images such as Google's distroless images ship your program and its runtime and nothing else: no shell, no ls, no ps. That makes them smaller and harder to attack, and it means kubectl exec has nothing to run. Deploy a distroless Python web server to see this:

Bash
cat > slim.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: slim
spec:
  replicas: 1
  selector:
    matchLabels:
      app: slim
  template:
    metadata:
      labels:
        app: slim
    spec:
      containers:
        - name: app
          image: gcr.io/distroless/python3-debian13
          imagePullPolicy: IfNotPresent
          args: ["-m", "http.server", "8080"]
EOF
kubectl apply -f slim.yaml
kubectl rollout status deploy/slim
POD=$(kubectl get pods -l app=slim -o jsonpath='{.items[0].metadata.name}')
kubectl exec -it "$POD" -- sh

The last command fails with something like executable file not found in $PATH. Distroless images publish floating tags rather than version numbers; for anything beyond practice, pin the image by digest.

kubectl debug adds an ephemeral container to the running pod: a temporary extra container, from an image you choose, that shares the pod's network. With --target, it also joins the app container's process namespace, so it can see the app's processes:

Bash
kubectl debug -it "$POD" --image=busybox:1.37 --target=app --profile=general

You land at a BusyBox prompt inside the pod. Try these:

Bash
ps
wget -qO- http://localhost:8080/ | head -5
ls /proc/1/root/usr/bin

ps lists the app's python3 process as PID 1 next to your shell. wget reaches the app on localhost because the containers share a network. /proc/1/root is a window into the app container's own filesystem, so the last command lists what the distroless image actually contains. If it says Permission denied, the debug container lacks the rights to look into another container's process; leave the shell and retry with --profile=sysadmin, which gives the debug container more privileges, so use it only on clusters you control. Type exit to leave.

An ephemeral container cannot be removed from a pod once added; it stays listed under Ephemeral Containers in kubectl describe pod until the pod is replaced. To get a clean pod back, run kubectl rollout restart deploy/slim.

Check it worked

kubectl describe pod "$POD" shows an Ephemeral Containers section with a debugger- container using busybox:1.37, and inside the debug shell ps listed a python3 process you could not reach with kubectl exec.

Step 9 · Clean up

Deleting the namespace removes every Deployment, pod, Service, Secret and claim you made. Then put your context back on the default namespace, remove the node label from the Pending step and delete the folder:

Bash
kubectl delete namespace pod-debug-demo
kubectl config set-context --current --namespace=default
kubectl label node kind-control-plane disktype-
cd ~
rm -rf ~/pod-debug-demo

If you are finished with Kubernetes for now, kind delete cluster removes the whole cluster as well.

Check it worked

kubectl get namespace pod-debug-demo says the namespace is NotFound, kubectl get nodes --show-labels no longer lists disktype=ssd, and ls ~/pod-debug-demo reports no such directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.