Overview and What You Will Learn
CrashLoopBackOff is a pod status that means a container keeps starting, exiting and being restarted by the kubelet with a growing delay between attempts. It describes the loop, not the cause. OOMKilled is one specific cause: the container used more memory than its limit, so the kernel killed it. The fastest diagnosis starts with the container's last termination reason and exit code, not with guesses.
By the end of this lab you will be able to:
- Read
Last State,Reason,Exit Codeand events fromkubectl describe pod - Recover logs from the crashed container with
kubectl logs --previous - Tell an OOM kill (exit code 137) from an application error, a bad command and a failing probe
- Tell a container OOM kill apart from a node-pressure eviction
- Set memory requests and limits correctly, including for JVM, Node.js and Go apps
- Debug a crashing pod with
kubectl debugand a copy of the pod - Alert on restarts and OOM kills with kube-state-metrics
Why This Matters in Production
A pod stuck in CrashLoopBackOff is capacity you thought you had but do not, and an OOM-killed pod drops its in-flight requests every time it dies. Picture a checkout service at a platform like Swiggy or Shopify during a traffic spike: a memory limit that was fine at normal load gets hit, pods restart one after another, the remaining pods take the extra load and hit the limit too, and the problem spreads. Engineers who read the termination reason first fix this in minutes, while those who start with application logs often spend an hour looking at the wrong layer.
Core Principles
Kubernetes restarts a failed container according to the pod's restartPolicy (Always for Deployments). After each failure the kubelet waits longer before the next restart, starting at 10 seconds and doubling up to a cap, which is traditionally five minutes. The delay resets after the container has run successfully for a while, and newer Kubernetes versions can shorten the cap. While the kubelet waits, the container shows as Waiting with reason CrashLoopBackOff.
The exit code tells you how the container ended:
| Exit code | Meaning | Typical cause |
|---|---|---|
0 |
Exited cleanly | Process finished, so it does not belong in a Deployment |
1 |
Application error | Exception, missing config, failed dependency |
126 |
Command not executable | Wrong permissions or entrypoint |
127 |
Command not found | Typo in command, wrong image or path |
137 |
Killed by SIGKILL (128 + 9) | OOM kill, or a force kill after a failed graceful stop |
139 |
Segmentation fault | Crash in native code |
143 |
Terminated by SIGTERM (128 + 15) | Graceful stop, often after a failed liveness probe |
Memory is enforced at two different levels, and they look different:
- Container limit exceeded: the container's cgroup runs out of memory and the kernel kills the process. The pod stays on the node, the container restarts, and the status shows
OOMKilledwith exit code 137. - Node memory pressure: the node itself is low on memory, so the kubelet evicts whole pods. The pod ends up
Failedwith reasonEvicted, and it is not restarted in place. Pods that use more than they requested are evicted first, and QoS class (BestEffort, thenBurstable, thenGuaranteed) influences which pods the kernel kills first under pressure.
or CrashLoopBackOff]) --> B[kubectl describe pod
read Last State] B --> C{Reason and
exit code?} C -->|OOMKilled 137| D[Memory limit
or leak] C -->|Error 1| E[App or config
error] C -->|127 or 126| F[Wrong command
or entrypoint] C -->|Probe failed| G[Probe tuning] D --> H([Fix and verify]) E --> H F --> H G --> H classDef start fill:#475569,color:#FFFFFF classDef check fill:#F1F5F9,color:#1E293B classDef bad fill:#EF4444,color:#FFFFFF classDef ok fill:#10B981,color:#FFFFFF class A start class B,C check class D,E,F,G bad class H ok
Requests and limits do different jobs. The request is what the scheduler reserves for the pod, and the limit is the ceiling that triggers the OOM kill. A pod whose memory request is far below its real use gets packed onto nodes that cannot sustain it, and a limit set too tight kills a healthy pod at every peak.
Detailed Step-by-Step Practical Lab
How to Reproduce an OOMKilled Pod
Create a pod that deliberately allocates more memory than its limit, so you can see exactly what Kubernetes reports. The stress image allocates 150 MiB while the limit is 100 MiB.
kubectl create namespace debug-lab kubectl apply -n debug-lab -f - << 'EOF'apiVersion: v1kind: Podmetadata: name: memory-hogspec: containers: - name: stress image: polinux/stress command: ["stress"] args: ["--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"] resources: requests: memory: 50Mi limits: memory: 100MiEOF kubectl get pod memory-hog -n debug-lab -wHow to Read the Termination Reason with kubectl describe
kubectl describe pod shows the container's current state, its last state and the event log in one place. Look at Last State first, because the current state is usually just Waiting with CrashLoopBackOff.
kubectl describe pod memory-hog -n debug-labContainers: stress: State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: OOMKilled Exit Code: 137 Started: Wed, 14 Oct 2026 10:15:02 +0530 Finished: Wed, 14 Oct 2026 10:15:03 +0530 Restart Count: 4 Limits: memory: 100Mi Requests: memory: 50MiFor scripts and alerts, pull the same fields directly:
kubectl get pod memory-hog -n debug-lab \ -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}{" "}{.status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}'# OOMKilled 137 # Recent events across the namespace, oldest firstkubectl get events -n debug-lab --sort-by=.lastTimestampCheck the events at the bottom of describe as well. They show image pull errors, failed probes (Liveness probe failed), scheduling problems and Killing messages, which separate an OOM kill from a probe kill.
How to Get Logs from a Crashed Container
The default kubectl logs shows the current container, which may have just started and printed nothing. Use --previous to read the logs of the instance that crashed.
# Current containerkubectl logs memory-hog -n debug-lab # The previous (crashed) instance: the one you wantkubectl logs memory-hog -n debug-lab --previous # Pods with several containers, and init containerskubectl logs orders-7d9f6c5b8-x2k4p -n shop -c orders --previouskubectl logs orders-7d9f6c5b8-x2k4p -n shop -c migrate-dbAn OOM kill usually leaves no error in the application log, because the kernel ends the process without warning. If the log simply stops mid-stream and the exit code is 137, suspect memory.
A pod can also loop in an init container. In that case the status reads Init:CrashLoopBackOff and the logs you need belong to the init container.
How to Reproduce and Diagnose an Application CrashLoop
A container that exits with code 1 is the other common case. The error is in the logs, not in the memory settings.
kubectl apply -n debug-lab -f - << 'EOF'apiVersion: v1kind: Podmetadata: name: bad-configspec: containers: - name: app image: busybox:1.36 command: ["sh", "-c", "echo 'ERROR: DATABASE_URL is not set' >&2; exit 1"]EOF kubectl get pod bad-config -n debug-labkubectl logs bad-config -n debug-lab --previouskubectl get pod bad-config -n debug-lab \ -o jsonpath='{.status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}'# 1Common causes when the exit code is 1 are a missing environment variable, a bad ConfigMap value, a database that is not reachable yet, and wrong credentials. If a referenced ConfigMap or Secret does not exist, the pod will not start at all and the status is CreateContainerConfigError, not CrashLoopBackOff.
How to Debug a Container That Dies Too Fast to Inspect
You cannot exec into a container that exits immediately. Two approaches work: copy the pod with a different command so it stays alive, or attach an ephemeral debug container to a running pod.
# Copy the pod, replace the command with a shell, and keep the original untouchedkubectl debug memory-hog -n debug-lab -it --copy-to=memory-hog-debug --container=stress -- sh # Inside the copy: inspect the environment, files, DNS and connectivityenvls -l /appnslookup postgres.shop.svc.cluster.local # For a running pod: attach an ephemeral container that shares its namespaceskubectl debug -it orders-7d9f6c5b8-x2k4p -n shop --image=busybox:1.36 --target=ordersDelete debug copies when you finish (kubectl delete pod memory-hog-debug -n debug-lab). On a regulated platform such as a payments or trading cluster, treat debug access to production pods as an audited action, and get approval before using it. Packet captures and node-level shells (kubectl debug node/NODE) deserve the same care.
How to Check Memory Usage and Find the Right Limit
Measure real consumption before changing a limit. kubectl top reports the working set, which is the figure the kubelet uses for eviction decisions, and it needs metrics-server.
kubectl top pod -n shop --containers # Node-level view and memory pressurekubectl top nodekubectl describe node NODE_NAME# Conditions: MemoryPressure True means the node is evicting podsFor history, query Prometheus (the peak over a day tells you more than the current value):
max_over_time(container_memory_working_set_bytes{namespace="shop", container="orders"}[1d])To confirm the kernel killed the process, check the node's kernel log or your logging platform for a message like Memory cgroup out of memory: Killed process.
Choose limits from the observed peak plus headroom, not from the average:
- A memory limit between 1.25 and 1.5 times the observed peak is a common starting point, then tighten it with data
- Set the memory request equal to the limit for critical services, so the scheduler reserves what the pod needs and the pod is less likely to be evicted
- Use the Vertical Pod Autoscaler in recommendation mode to get suggested values without it changing running pods
If memory climbs steadily and never levels off, raising the limit only delays the kill. That pattern points to a leak, which needs a heap profile or a fix in the code.
How to Size Runtime Memory Inside the Container Limit
The language runtime's own memory ceiling must sit below the container limit, with room left for non-heap memory (thread stacks, native libraries, buffers). If the runtime believes it can use the whole limit, the kernel kills it first.
# JVM: size the heap as a percentage of the container memory limitenv: - name: JAVA_TOOL_OPTIONS value: "-XX:MaxRAMPercentage=70" # Node.js: cap the old-generation heap below the limit (about 75 percent)# For a 512Mi limit:env: - name: NODE_OPTIONS value: "--max-old-space-size=384" # Go 1.19 and later: a soft memory limit for the garbage collectorenv: - name: GOMEMLIMIT value: "400MiB"These values are starting points. Check them against your runtime version, and load test to confirm the process stays under the limit at peak.
How to Fix Liveness Probe Kills and Slow Starts
A liveness probe that fails restarts the container, and a probe that is too strict kills a healthy but slow-starting app over and over. The events show Liveness probe failed, and the exit code is often 143 or 137. Use a startup probe to give slow applications time to boot, and keep the liveness probe lenient.
containers: - name: orders image: registry.devops.in/orders:v1.4.2 resources: requests: cpu: 250m memory: 512Mi limits: memory: 512Mi startupProbe: httpGet: path: /healthz port: 8080 periodSeconds: 5 failureThreshold: 30 livenessProbe: httpGet: path: /healthz port: 8080 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: 8080 periodSeconds: 5The startup probe above allows up to 150 seconds (30 failures at 5 seconds) before the liveness probe begins. The liveness probe should check only that the process is alive, not that its dependencies are healthy. A liveness probe that calls the database restarts every pod when the database blips.
How to Alert on Restarts and OOM Kills
Alert before users notice. kube-state-metrics exposes the restart count and the last termination reason, so you can page on both a restart loop and an OOM pattern.
# Container restarted more than 3 times in the past hourincrease(kube_pod_container_status_restarts_total[1h]) > 3 # Container whose last termination was an OOM killkube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1 # Container sitting in CrashLoopBackOffkube_pod_container_status_waiting_reason{reason="CrashLoopBackOff"} == 1Also graph working set against the memory limit for each container, so you can see a pod approaching its limit well before the kill.
How to Clean Up the Lab
kubectl delete namespace debug-labProduction Best Practices & Common Pitfalls
- Always set memory requests and limits. A pod with none is
BestEffortand is first in line for eviction and OOM kills. - Set the request equal to the limit for memory on critical services, and keep CPU limits generous or unset to avoid throttling.
- Size from measurements. Use peak working set over several days, not a single
kubectl topreading. - Keep the runtime below the limit. Tune JVM, Node.js and Go memory settings to a fraction of the container limit.
- Use startup probes for slow applications, and keep liveness probes shallow.
- Do not run finite jobs in a Deployment. A process that exits with code 0 under
restartPolicy: Alwaysstill ends up in CrashLoopBackOff. Use aJoborCronJob. - Check previous logs first.
kubectl logs --previousanddescribe podanswer most cases in under a minute. - Roll out limit changes gradually and watch restarts, because a new limit takes effect only when pods are recreated.
| Symptom | Likely cause | First action |
|---|---|---|
OOMKilled, exit 137, restarts under load |
Limit below real peak, or a leak | Measure working set, raise limit, profile for leaks |
| Exit 1 right after start | Missing config, bad credentials, dependency down | logs --previous, check env, ConfigMap and Secret |
| Exit 127 or 126 | Wrong command, image or permissions |
Compare command with the image entrypoint |
Liveness probe failed in events |
Probe too strict or app too slow | Add a startup probe, loosen thresholds |
Pod Evicted |
Node memory pressure | describe node, fix requests, add capacity |
Init:CrashLoopBackOff |
Init container failing | Read logs of the init container |
Exit 0 with CrashLoopBackOff |
Process finishes by design | Move to a Job, or keep a foreground process |
Common MistakeRaising the memory limit again and again without measuring. If usage climbs steadily until the kill, a bigger limit only postpones the crash and wastes node capacity. Graph the working set first: a flat line with spikes needs more headroom, and a rising line needs a code fix.
Remember
OOMKilledandEvictedare different events. OOMKilled means one container exceeded its own limit and restarts in place. Evicted means the node ran short of memory and the pod was removed. They need different fixes: the limit for the first, node capacity and requests for the second.
TipPut the termination reason into your dashboards and runbooks. Search for
OOMKilledin your cluster events and compare the pod'sLast Stateagainst its limit before anyone opens an application log.
Quick Reference & Troubleshooting Commands
| Command | Purpose |
|---|---|
kubectl get pods -n NS |
Status and restart counts |
kubectl describe pod POD -n NS |
Last State, exit code, events |
kubectl logs POD -n NS --previous |
Logs of the crashed instance |
kubectl logs POD -n NS -c CONTAINER --previous |
Logs for one container in a multi-container pod |
kubectl get events -n NS --sort-by=.lastTimestamp |
Recent events in time order |
kubectl top pod -n NS --containers |
Working set memory and CPU per container |
kubectl describe node NODE |
Node conditions such as MemoryPressure |
kubectl debug POD -n NS -it --copy-to=NAME --container=C -- sh |
Debug a copy with a shell instead of the crashing command |
kubectl debug -it POD -n NS --image=busybox:1.36 --target=C |
Attach an ephemeral debug container |
kubectl rollout restart deployment/NAME -n NS |
Recreate pods after a config or limit change |
kubectl get pods -A --field-selector=status.phase=Failed |
Find evicted and failed pods |