Debugging workloads: events, exit codes, and the first three minutes

Events, then previous logs, then exit code. describe before logs, --previous for a crash loop, and exit 137 means something killed it rather than it failing.

Read the briefing
About 8 min to read 8 drills

What to remember

  1. kubectl describe before kubectl logs. Events name the layer: image pull, volume, scheduling, probe failure.
  2. logs --previous is where the crash is. The current container has just started; the reason it died is in the last one.
  3. 137 = SIGKILL, 143 = SIGTERM, 1 = your code. OOM or grace-period expiry versus a genuine application failure.
  4. ImagePullBackOff is a name, a credential or a registry. The event says which. Digest pinning removes the 'which build' question entirely.
  5. Ephemeral debug containers beat baking tools into images. kubectl debug attaches a toolbox to a running pod without shipping curl in production.

The big picture

Debugging a workload is a fixed sequence, not a bag of tricks: read the pod's status and events, read the container's last state and exit code, read the previous instance's logs, then test hypotheses in order of likelihood. Kubernetes puts almost every failure into a handful of statuses (Pending, ImagePullBackOff, CreateContainerConfigError, CrashLoopBackOff, OOMKilled, Running but not Ready), and each status names the layer that failed. Interviewers use this node to watch how you think under time pressure: whether you gather evidence before acting, and whether each command you run is a test of something.

The mental model

A pod passes through gates, and its STATUS column tells you which gate it is stuck at: scheduling (Pending), volumes and image (ContainerCreating, ImagePullBackOff), container configuration (CreateContainerConfigError), the process itself (CrashLoopBackOff, OOMKilled, exit codes), and finally traffic (Running but 0/1 Ready). Every gate writes an Event and a Reason. Your job in the first three minutes is to find the gate, read what it wrote, and only then form a theory.

In depth

The first three minutes: a fixed order

Start with kubectl get pod <p> -o wide and read three columns: STATUS, READY and RESTARTS. Then kubectl describe pod <p> and go straight to two places: the container's State / Last State (with Reason and Exit Code) and the Events at the bottom. Events are the kubelet's and scheduler's own account of what they tried, with counts and ages (x4 over 4m); they are kept for about an hour by default, so capture them early. Third, kubectl logs <p> --previous for the application's own last words; plain kubectl logs shows the current instance, which may be seconds old and silent. Fourth, kubectl get events -n <ns> --sort-by=.lastTimestamp for what else happened around the same time.

Decode STATUS before theorising. Pending is the scheduler or storage (read the FailedScheduling event). ContainerCreating for more than a minute is volumes (FailedMount, MountVolume.SetUp failed), the CNI (FailedCreatePodSandBox), or a slow image pull. ImagePullBackOff and ErrImagePull are the registry conversation. CreateContainerConfigError is a missing ConfigMap, Secret or key. CrashLoopBackOff is the process exiting. Init: prefixes mean an init container. Running with 0/1 READY is a readiness probe. Completed and Error belong to Jobs. Terminating for minutes is a finalizer, a stuck preStop, or a dead node.

Ask "what changed" in the first minute: kubectl rollout history deployment/<d> for a new revision, kubectl get events -A --field-selector type=Warning for cluster-wide noise, and kubectl get nodes for a node that is NotReady or freshly upgraded. Narrate as you go: interviewers score the hypothesis each command tests, not the command.

CrashLoopBackOff and what exit codes tell you

CrashLoopBackOff is a kubelet state, not an error: the container exited, the kubelet restarted it, it exited again, and the kubelet is now waiting before the next attempt. The wait doubles from 10 seconds to a cap of five minutes and resets only after the container runs for ten minutes without exiting. RESTARTS counts the attempts; Last State: Terminated carries the exit code from the last one.

Exit codes are your fastest bisection. 0 under a Deployment still loops, because restartPolicy: Always restarts a container that finished its job; this is the one-shot-image mistake. 1 and 2 are the application refusing to start: read logs --previous. 126 and 127 are the shell saying the command is not executable or not found, usually a wrong command:/args: or a binary missing from the image; the runtime-level cousin is RunContainerError with executable file not found in $PATH or exec format error, the latter meaning an amd64 image on an arm64 node. Codes above 128 are signals: 137 is SIGKILL, 143 is SIGTERM, 139 is SIGSEGV. 137 needs a second look at Reason: OOMKilled means the memory limit; Error with a Liveness probe failed event means the kubelet killed it after the probe threshold and the grace period.

If the logs are empty, the process died before it could log, or it logs to a file. Set terminationMessagePolicy: FallbackToLogsOnError on the container so the last log lines appear in describe under Message whenever it exits non-zero, and compare probe timing with startup time before blaming the code: a liveness probe that fires before the app listens produces a textbook crash loop with a healthy application.

Image pulls and container configuration errors

The kubelet pulls images with the node's credentials and the pod's imagePullSecrets (directly or via its ServiceAccount), never with your laptop's login. ErrImagePull is a failed attempt; ImagePullBackOff is the kubelet backing off between attempts, up to five minutes. The message, not the Reason, tells you which fix: manifest unknown or not found is the tag or repository name; unauthorized, authentication required or pull access denied is credentials (missing secret, wrong registry host in the secret, or an expired token from a registry that issues short-lived ones); i/o timeout, no such host or x509 is network, DNS or a CA the node does not trust; no match for platform in manifest is an image built for the wrong CPU architecture. Reproduce on the node with crictl pull <image> when the message is ambiguous. Remember that imagePullPolicy defaults to Always for :latest and to IfNotPresent otherwise, so a cached tag can mask a broken registry until a new node appears.

CreateContainerConfigError happens after the image is present: the kubelet cannot assemble the container's configuration because a referenced ConfigMap or Secret does not exist, or the named key is missing. The event says exactly which (configmap "x" not found, couldn't find key y in Secret ns/z). Keys are case-sensitive, envFrom fails on the whole object while valueFrom fails on one key, and optional: true turns the failure into an unset variable, which is only right when the code handles it. Its sibling CreateContainerError is the runtime refusing to create the container for other reasons, such as mounting a file over a directory. A pod stuck in ContainerCreating with FailedMount is the same family one layer down: a Secret or PVC named in volumes that does not exist or cannot attach.

Memory and CPU: OOMKilled, Evicted, and throttling

Exit code 137 with Reason: OOMKilled means the container exceeded its own memory limit and the kernel's OOM killer ended it; the node may have plenty of memory free. The kubelet restarts it in place, so the symptom is a restart count climbing with OOMKilled in Last State. Confirm with kubectl get pod <p> -o jsonpath='{.status.containerStatuses[*].lastState}' and compare container_memory_working_set_bytes (what the kernel counts) with kube_pod_container_resource_limits. Three surprises: each container in the pod has its own limit, so a sidecar can be the one dying; a tmpfs emptyDir (medium: Memory) is charged to the writing container's limit; and JVMs and other runtimes that size heaps from node memory blow past a limit they never read.

Evicted is different: the pod's phase is Failed, the Reason is Evicted, and the message says The node was low on memory (or disk, or PIDs) with the threshold. That is the kubelet protecting the node under pressure, ranking pods by usage over requests, and the pod is not restarted in place; its controller creates a replacement elsewhere. Evicted pods accumulate until the controller manager's terminated-pod garbage collection runs; clean them deliberately with kubectl delete pod -n <ns> --field-selector=status.phase=Failed.

CPU never produces either status. A container over its CPU limit is throttled by the CFS quota: latency rises, probes may time out, and the effect can look like a hang, but there is no kill and no restart unless a liveness probe fails as a consequence. When a "slow" pod has no OOMKills and no restarts, check the throttling ratio before anything else.

kubectl debug, ephemeral containers and distroless images

Production images increasingly have no shell, no package manager and no debugging tools, which is good for security and useless for kubectl exec. kubectl debug fills the gap in three modes. Ephemeral container: kubectl debug -it <pod> --image=busybox --target=<container> adds a new container to the running pod without restarting it; --target puts it in the target container's process namespace, so ps, ss -tlnp and /proc/<pid>/root/ show the application's processes, sockets and filesystem. Ephemeral containers have no ports, probes or resource requests, cannot be removed once added (they stay until the pod dies), and need RBAC on the pods/ephemeralcontainers subresource, which on-call roles should carry.

Pod copy: kubectl debug <pod> -it --copy-to=<name> --share-processes --set-image='*=<image>' -- sh (or --container=<c> -- sh) creates a copy of the pod with a changed command or image, which is the way to get a shell when the original container exits immediately and there is nothing to attach to. Node: kubectl debug node/<node> -it --image=ubuntu runs a privileged pod on the node with the host filesystem mounted at /host and host networking, for journalctl -u kubelet, crictl ps and disk checks without SSH.

Keep a blessed debug image (busybox for basics, a netshoot-style image for network tooling) in your own registry so the pull does not fail at the worst moment, and write the three commands into the runbook. For the common "Running but not Ready" case, describe already has the probe failure text: connection refused usually means the process is bound to 127.0.0.1 rather than 0.0.0.0, because probes arrive from the kubelet on the pod IP; an HTTP status means the app answered and did not like the path.

Myths and facts

Myth: CrashLoopBackOff is the error I need to fix.

Fact: It is the kubelet's backoff after repeated exits. The cause is in the exit code, the previous instance's logs, and the events; the status only says 'it keeps exiting'.

Myth: ImagePullBackOff means the registry is down.

Fact: Far more often the tag is wrong, the credentials are missing or expired, or the image was built for another architecture. The event message names which; registry outages show as timeouts.

Myth: Exit code 137 always means out of memory.

Fact: 137 is SIGKILL from anyone. OOMKilled as the Reason means the memory limit; Error with a liveness-probe event means the kubelet killed it after the grace period; a human can also send it.

Myth: kubectl logs shows why the container crashed.

Fact: It shows the current instance, which may be a fresh restart with nothing to say. The crash is in kubectl logs --previous, or in the termination message if you enabled FallbackToLogsOnError.

Myth: Distroless containers cannot be debugged without rebuilding the image.

Fact: kubectl debug attaches an ephemeral container with tools to the running pod, optionally sharing its process namespace; no rebuild and no restart.

Myth: Deleting the pod is a harmless first step.

Fact: The Deployment recreates an identical pod that fails the same way, and you have destroyed the events, the last state and the previous logs that would have explained it.

How pros do it

  • Describe before you delete: capture kubectl describe pod and kubectl logs --previous into the incident channel before any mitigation, because a restart or rollback erases the evidence.
  • Set terminationMessagePolicy: FallbackToLogsOnError on every container so a non-zero exit leaves its last log lines in describe, visible without exec or log access.
  • Alert from kube-state-metrics on waiting reasons (CrashLoopBackOff, ImagePullBackOff, CreateContainerConfigError), on last-terminated reason OOMKilled, and on restart rate, so the first three minutes start before a user reports it.
  • Make config references fail before deploy: a CI check or admission policy that every ConfigMap and Secret named by a pod exists in the same release, and optional: true only where the code handles the absence.
  • Keep a blessed debug image in your own registry, grant on-call RBAC on pods/ephemeralcontainers, and put the three kubectl debug invocations in the runbook for distroless fleets.
  • Match probe timing to measured startup (a startupProbe for slow starters) so the liveness probe is never the thing causing the crash loop you are debugging.

Questions people ask

Why does kubectl logs show nothing when the pod keeps crashing?

Say you are reading the new instance and reach for kubectl logs --previous for the one that died. If that is empty too, say the process exited before it could log or logs to a file, then name the fix: terminationMessagePolicy FallbackToLogsOnError and the container's Message in describe. Knowing --previous without being prompted is the point.

My pod says Running but 0/1 Ready. Is it crashing?

Say no: the process is up and the readiness probe is failing, so the pod is out of Service endpoints. Then read the probe result from describe: connection refused points at the bind address (127.0.0.1 instead of 0.0.0.0) or the port, an HTTP status at the path or the app's dependencies.

The image exists and I can pull it on my laptop; why is the node getting ImagePullBackOff?

Say the node uses its own credentials and network, never yours. Then list what you check in order: the pod's imagePullSecrets (or the ServiceAccount's), whether the registry issues short-lived tokens that expired, whether the node can reach the registry at all, and whether the image has a manifest for the node's CPU architecture. Read the message, not just the Reason.

How long does CrashLoopBackOff wait between restarts?

10 seconds, then 20, 40, 80, 160, capped at five minutes, and the backoff resets after the container has run for ten minutes. Then use it: that is why a pod can show 6 restarts and a 5-minute wait after only a quarter of an hour, and why deleting it to 'speed things up' just destroys the evidence.

Can I get a shell in a distroless container without restarting it?

Yes: kubectl debug -it --image=busybox --target= adds an ephemeral container sharing the process namespace, so ps, ss and /proc//root show the app. Then cover the edge: if the container exits immediately, use --copy-to with --share-processes and a changed command instead. Mention the RBAC on pods/ephemeralcontainers and a blessed debug image.

Why are there hundreds of Evicted pods in my namespace?

Say they stay in phase Failed as evidence until the controller manager's terminated-pod garbage collection threshold is reached, and that they are harmless. Then say what you do: read their messages for the threshold that fired, then clean them with kubectl delete pod --field-selector=status.phase=Failed.

What is the difference between CreateContainerConfigError and CreateContainerError?

ConfigError is the kubelet failing to build the container spec, almost always a missing ConfigMap, Secret or key, named in the event. CreateContainerError is the runtime refusing the container it was given, for example a volume mounting a file over a directory or an invalid command. Say which layer each one lives in and you have answered it.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

kubectl get pods shows a pod in CrashLoopBackOff with 7 restarts. What does that status actually mean, and what is the single most useful next command?

  1. The image could not be pulled from the registry. Check imagePullSecrets. Pull problems show as ImagePullBackOff / ErrImagePull; the container never ran, so there is nothing to crash.
  2. The node is unhealthy and the pod is being moved. Check kubectl get nodes. Pods are not moved by the kubelet; and the status says the container ran and exited.
  3. The container starts and exits repeatedly; the kubelet waits longer between restarts each time. Run kubectl logs <pod> --previous to read the crashed instance. The process is exiting on its own; the backoff is the kubelet's, and the previous container's logs hold the exit reason.
  4. The scheduler cannot place the pod. Check resource requests. Unschedulable pods sit in Pending; this pod has been running and crashing.
In short

The container keeps starting and exiting, so run kubectl logs --previous to read the crashed instance.

Why

CrashLoopBackOff is a kubelet state, not an application error: the container exited (any code) and the kubelet is applying an exponential backoff (10 s, 20 s, 40 s… capped at five minutes) before the next start. The evidence lives in the previous container's logs and in the exit code shown by kubectl describe pod.

The common mistake

Treating CrashLoopBackOff as the cause, or deleting the pod to 'see if it comes back'. That destroys the events and the previous logs and reproduces the same failure.

Read the docs

2 Pick the strongest answer

kubectl describe pod shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137 on a container with limits.memory: 256Mi. The node has plenty of free memory. What happened?

  1. The whole node ran out of memory, so the kubelet evicted the pod. Node-pressure eviction shows the pod as Evicted with a message about the node; OOMKilled on the container means the container's own limit.
  2. The liveness probe failed three times and the kubelet restarted it. Probe-driven restarts show Reason: Error with the probe failure in events, not OOMKilled.
  3. The container exceeded its CPU limit and was killed for throttling. CPU limits throttle via the CFS quota; they never kill. Only memory limits produce OOMKilled.
  4. The container's memory usage reached its 256Mi limit and the kernel's cgroup OOM killer terminated it; raise the limit or fix the leak. 137 is 128 + 9 (SIGKILL); with OOMKilled as the reason, the killer was the memory cgroup enforcing the limit.
In short

The container used more memory than its limit, so the kernel killed it; raise the limit or fix the leak.

Why

Exit code 137 alone means SIGKILL; the OOMKilled reason tells you who sent it. Because the memory cgroup enforces the limit per container, the node can have plenty of free memory while one container is killed. The fix is either a realistic limit set from observed usage or finding the leak; raising the request without the limit changes nothing.

The common mistake

Concluding the node ran out of memory, or that CPU had anything to do with it. Node pressure shows as Evicted with a message about the node; CPU limits only throttle.

Read the docs

3 Answer out loud

A pod is in CrashLoopBackOff. Walk me through your first three minutes, out loud, including what each step can rule in or out.

In short

A strong answer runs describe first for the exit code and events, then logs --previous, and says what each step rules out.

What a strong answer does
  • method: describe events and last state first (exit code, reason), logs --previous for the app's own words, then config/env/secret references and probes, each step narrowing the cause.
  • mechanism: Explains the backoff, distinguishes exit 137/OOMKilled from exit 1 (app error) from probe-driven restarts, and says what each implies.
  • communication: Thinks aloud: states the hypothesis each command tests and what result would change the plan.
Why

Interviewers score the method: whether you read evidence before acting, whether each step is a test of a hypothesis, and whether you narrate it. Knowing the exact commands matters less than knowing what they can tell you.

The common mistake

Restarting or deleting the pod first, or guessing the cause before reading the exit code. The reveal is in the previous instance and the events, which the delete destroys.

4 Read the output

The image exists and the developer can pull it from their laptop. What is the most likely fix?

$ kubectl describe pod worker-5d8f7-q2m9x | tail -6
Events:
  Type     Reason     Age                 From     Message
  ----     ------     ----                ----     -------
  Normal   Pulling    2m (x4 over 4m)     kubelet  Pulling image "registry.internal.example.com/team/worker:1.8.0"
  Warning  Failed     2m (x4 over 4m)     kubelet  Failed to pull image "registry.internal.example.com/team/worker:1.8.0": rpc error: code = Unknown desc = failed to pull and unpack image "registry.internal.example.com/team/worker:1.8.0": failed to resolve reference "registry.internal.example.com/team/worker:1.8.0": unexpected status from HEAD request to https://registry.internal.example.com/v2/team/worker/manifests/1.8.0: 401 Unauthorized
  Warning  Failed     2m (x4 over 4m)     kubelet  Error: ErrImagePull
  1. Give the pod (or its ServiceAccount) an imagePullSecret with valid credentials for the private registry. A 401 Unauthorized from the registry means the kubelet pulled anonymously or with expired credentials; the developer's laptop login proves nothing about the node.
  2. Change the tag to latest so the kubelet finds an image. The error is authorization, not a missing tag; latest would fail identically and adds non-reproducible deploys.
  3. Increase the container's resource requests so the pull is not throttled. Image pulls are not governed by pod resources.
  4. Drain the node; its container runtime cache is corrupted. A 401 from the registry is not a node fault.
In short

The registry answered 401 Unauthorized, so give the pod or its ServiceAccount an imagePullSecret with valid credentials.

Why

Read the registry's message, not just the Reason column. A 401 Unauthorized (or pull access denied ... may require authorization) points at credentials; manifest unknown or not found points at the tag or repository name; i/o timeout points at network or the registry being down. Each has a different fix, and interviewers check that you read the text.

Read the docs

5 Scenario: what do you do next?

A new StatefulSet ledger has been Pending for three minutes in a cluster where everything else is healthy. Nodes have spare CPU and memory. The on-call engineer says "the scheduler is broken".

Step 1. What do you do first?

  1. Restart kube-scheduler. A Pending pod with events is the scheduler doing its job and telling you why.
  2. Add a node to the pool. Resources are not the constraint per the situation; adding capacity blind is expensive guessing.
  3. kubectl describe pod ledger-0 and read the Events. The FailedScheduling event names the filter that eliminated each node. Ten seconds of reading beats any theory.
  4. Delete the pod so the controller recreates it. The new pod will hit the same condition; you also lose the events that explain it.

Step 2. The event reads: 0/6 nodes are available: pod has unbound immediate PersistentVolumeClaims. What next?

  1. kubectl get pvc -l app=ledger and kubectl describe pvc, then check the StorageClass and provisioner events. The scheduler is waiting on storage; the PVC's events will say whether provisioning failed and why.
  2. Increase the PVC size. Nothing suggests size; the claim is unbound, not too small.
  3. Create a PersistentVolume by hand and bind it. That works around dynamic provisioning instead of finding out why it failed, and it does not scale to the next replica.
  4. Change the StatefulSet to a Deployment. The workload needs stable storage; changing the controller does not make storage appear.

Step 3. The PVC event says storageclass.storage.k8s.io "gp3" not found; the cluster's classes are gp2 and standard. What is your fix and your systemic follow-up?

  1. Create a StorageClass named gp3 that aliases gp2 and move on. Papering over a typo with a misleading class name creates the next incident.
  2. Point the volumeClaimTemplate at an existing class now; then add a default StorageClass and a CI policy check that manifests reference known classes. Immediate fix plus a mechanism that prevents the next typo from becoming a Pending workload.
  3. Tell the team to double-check class names. A reminder, not a mechanism.
In short

Read the pod's events first, follow them to the PVC and its StorageClass, then fix the class name and add a check for it.

Why

Pending has many causes and one entry point: the pod's events. Here the scheduler correctly refused to place a pod whose storage could not be provisioned. The sequence interviewers score is evidence → the specific failing dependency → a fix matched to the cause → a mechanism that prevents recurrence.

Read the docs

6 Pick the strongest answer

A production pod runs a distroless image, no shell and no tools, and it is misbehaving right now. How do you get at its process list and sockets without restarting it?

  1. kubectl debug -it <pod> --image=busybox --target=<container> to attach an ephemeral container that shares the target's process namespace. Ephemeral containers add tooling to a running pod without restarting it; --target shares the PID namespace so you can see the app's processes and sockets.
  2. SSH to the node and run docker exec on the container. Modern nodes run containerd or CRI-O, and node access for routine debugging is a last resort that many environments forbid.
  3. kubectl exec -it <pod> -- sh and install the tools you need. Distroless images have no shell or package manager; exec has nothing to run.
  4. Edit the pod to add a sidecar container with debugging tools. Pod containers are immutable after creation; you would have to recreate the pod and lose the misbehaving state.
In short

Use kubectl debug with --target to add an ephemeral container that shares the app's process namespace.

Why

kubectl debug was built for exactly this: an ephemeral container with your tools, attached to the live pod, optionally sharing its process namespace so ps, ss, and /proc/<pid>/ show the application's state. It is also how you debug a node (kubectl debug node/<name>) without SSH.

Read the docs

7 Quick recall

The current container just restarted and its log is empty. Which kubectl logs flag gets you the crashed instance?

In short

The --previous (or -p) flag shows the logs of the crashed container instance.

Accepted

--previous · -p · kubectl logs --previous

Why

kubectl logs --previous (short -p) reads the log of the last terminated instance of the container, which is where the crash reason usually is.

8 Find what's broken

The ConfigMap worker-config has one key, QUEUE_URL, and the Secret worker-secrets exists with DB_PASSWORD. The pod shows CreateContainerConfigError; after a colleague fixes that, it starts and is OOMKilled within seconds. Which lines?

apiVersion: v1
kind: Pod
metadata:
  name: worker
spec:
  containers:
    - name: worker
      image: registry.example.com/worker:1.8.0
      env:
        - name: QUEUE_URL
          valueFrom:
            configMapKeyRef:
              name: worker-config
              key: queue-url
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: worker-secrets
              key: DB_PASSWORD
      command: ["python", "worker.py"]
      resources:
        limits:
          memory: 64Mi
In short

The ConfigMap key name is wrong (queue-url instead of QUEUE_URL), and the 64Mi memory limit is too small.

What's broken
  • Line 14: The ConfigMap key is QUEUE_URL, not queue-url; a missing key makes container creation fail with CreateContainerConfigError.
  • Line 23: A 64Mi memory limit is below what a Python worker needs at startup, so the memory cgroup kills it immediately.
Why

CreateContainerConfigError is the kubelet failing to assemble the container's configuration: a ConfigMap or Secret, or a key inside one, does not exist. The event names it. The second fault only appears after the first is fixed because the container never started before, which is a common shape in real incidents: fix one layer, the next surfaces.

Read the docs

Next lesson Nodes: NotReady, cordon and drain, PDBs, and upgrades
Drill · Debugging workloads
0:00

Loading…