Kubernetes Pod CrashLoopBackOff: Inspecting Exit Codes, Pre-Crash Logs & Probes
Systematic root cause analysis for Pod crashes: read exit code 137/1/127, retrieve kubectl logs --previous, and adjust probe timing.
Key Takeaways & Prerequisites
- Exit code 137 indicates the container was terminated by SIGKILL, typically triggered by the Linux OOM Killer exceeding limits.memory.
- Exit code 139 denotes a Segmentation Fault (SIGSEGV) in native C/C++ libraries or memory corruption.
- A misconfigured livenessProbe checking slow external dependencies (e.g. database ping) triggers continuous kill-restart cycles.
- Distinguish between initial startup latency and ongoing health checks using startupProbe with failureThreshold * periodSeconds headroom.
Architecture & Execution Flow
- 01 →Exit Code Triage137 (OOM), 1, 139, 143
- 02 →StartupProbe GuardIsolate slow cold boots
- 03 →Liveness DecouplingNever probe external databases
- 04 →Resource LimitsMemory requests vs limits
Table of Contents
When operating Kubernetes clusters, CrashLoopBackOff is one of the most frequently encountered states. Operators often react reflexively: seeing a failing pod, they delete it via kubectl delete pod or trigger a rolling restart on the deployment. Consequently, the newly spawned pod crashes again, while the crash logs and forensics from the preceding failure are permanently lost.
CrashLoopBackOff is not an application-level error in itself. Rather, it is a self-preservation mechanism enforced by the kubelet: because the container is repeatedly terminating, the kubelet intentionally throttles subsequent restart attempts to protect the node's CPU and memory from thrashing.
This guide breaks down the root causes of CrashLoopBackOff, how to interpret Linux exit codes, log extraction techniques using the --previous flag, and production-grade startupProbe configuration.
Scope and Test Environment: All YAML manifests and Bash scripts in this guide have been syntax-validated using PyYAML and bash -n on Ubuntu 22.04. The kubectl workflows are designed for hands-on execution on real Kubernetes clusters (minikube, kind, k3s, or managed platforms such as EKS/GKE); a dedicated namespace is required for isolated testing.
1. Mechanics of CrashLoopBackOff
Within a Pod spec, the default value for restartPolicy is always Always[1]. When the container's primary process (PID 1) terminates with a non-zero exit code (or exits prematurely), the kubelet automatically restarts the container.
If the container repeatedly fails, the kubelet engages an exponential backoff delay algorithm:
- Crash 1: Immediate restart (0-second delay).
- Crash 2: 10-second delay (
10s). - Subsequent crashes: Delays double incrementally through
20s,40s,80s,160s, capped at a maximum of 300 seconds (5 minutes). - Once a container maintains stability continuously for 10 minutes, the backoff counter resets to 0.
During the wait intervals between restart attempts, the Pod status displays as CrashLoopBackOff. This status appears only after the RESTARTS counter increments to 1 or higher.
2. Exit Code Taxonomy
When investigating a pod stuck in CrashLoop, inspect the Last State block in the output of kubectl describe pod to determine the Reason and Exit Code[4].
Linux exit codes conform to POSIX standards: when a process is terminated by an OS signal, the exit code equals 128 + Signal Number.
The most common exit codes include:
- Exit Code 1: Application Error
- Symptoms:
Reason: Error,Exit Code: 1. - Root Cause: Uncaught exceptions, missing mandatory environment variables (such as
DATABASE_URL), syntax errors in mounted configuration files, or socket/port binding conflicts. - Mitigation: Inspect stderr using
kubectl logs <pod-name> --previous. - Exit Code 137: SIGKILL (128 + 9) via OOMKilled
- Symptoms:
Reason: OOMKilled,Exit Code: 137. - Root Cause: The container's memory usage exceeded its
resources.limits.memorythreshold[3]. The Linux kernel out-of-memory killer dispatched aSIGKILLto immediately terminate the process. - Mitigation: Increase
limits.memory, optimize the runtime heap size, or profile the service for memory leaks. - Exit Code 127: Command Not Found
- Symptoms:
Reason: Error,Exit Code: 127. - Root Cause: The binary defined in
commandorargsdoes not exist inside the container image filesystem, or thePATHenvironment variable was overwritten. Commonly encountered when migrating to Alpine or distroless base images while still invoking/bin/bash. - Mitigation: Verify the startup command, entrypoint configuration, and base image binaries.
- Exit Code 126: Permission Denied
- Symptoms:
Reason: Error,Exit Code: 126. - Root Cause: The entrypoint script lacks execute permissions (
chmod +x), or the pod runs as a non-root UID while the binary requires root privileges. - Mitigation: Grant execute permissions in the Dockerfile or adjust the pod's
securityContext. - Exit Code 143: SIGTERM (128 + 15)
- Symptoms:
Reason: Error,Exit Code: 143. - Root Cause: The container received a graceful termination signal. If observed in an active CrashLoop cycle, it almost always stems from a failing Liveness Probe, forcing the kubelet to send a SIGTERM to reboot the container.
- Mitigation: Inspect the Events block to verify whether a
Liveness probe failedevent was dispatched.
3. Four-Step Diagnostic Runbook with kubectl
Apply the following systematic four-step workflow to diagnose failures:
Step 1: Enumerate Pod Status and Restart Counts
kubectl get pods -n k8s-lab-crashloop -o wide
If the pod shows an increasing RESTARTS count and alternates between Error and CrashLoopBackOff, proceed to Step 2.
Step 2: Inspect Last State and Kubernetes Events
kubectl describe pod <ten-pod> -n k8s-lab-crashloop
Focus on two critical sections:
Containers -> Last State: Review the termination reason and exit code from the previous run:text Last State: Terminated Reason: OOMKilled Exit Code: 137Eventssection at the bottom: CorrelateBackOfforUnhealthyprobe failure events.
Step 3: Extract Logs from Terminated Containers Using the Previous Flag
When running kubectl logs <ten-pod>, the returned output is often empty because the freshly spawned container instance has not yet emitted any log entries.
To retrieve the logs of the immediately preceding failed instance, append the --previous flag[5]:
kubectl logs <ten-pod> -n k8s-lab-crashloop --previous --tail=100
For multi-container pods, specify the target container with -c <ten-container>:
kubectl logs <ten-pod> -c app -n k8s-lab-crashloop --previous --tail=100
Step 4: Validate Active Resources and Injected Environment Variables
kubectl get pod <ten-pod> -n k8s-lab-crashloop -o jsonpath='{.spec.containers[*].resources}'
kubectl get pod <ten-pod> -n k8s-lab-crashloop -o jsonpath='{.spec.containers[*].env}'
4. Dissecting Probes: Avoiding Slow-Startup CrashLoop Traps
The three Kubernetes probe types govern distinctly different lifecycles:
- Liveness Probe: Asserts whether the container is functional. Failing more than
failureThresholdtimes triggers the kubelet to kill and restart the container. - Readiness Probe: Asserts whether the container is ready to accept ingress traffic. Failure causes the kubelet to isolate the pod from Service Endpoints, without terminating the container.
- Startup Probe: Specifically designed for workloads with protracted initialization phases (e.g., cache warming, database migrations)[2].
The Pitfall: If an application takes 40 seconds to initialize, configuring only a livenessProbe with:
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 3
Probing begins at second 10. Three consecutive failures cause the kubelet to send a SIGTERM at second 25. The container is killed before completing startup, entering an unrecoverable CrashLoop.
Production-Grade Remediation: Avoid inflating initialDelaySeconds to excessively high values (such as 120s), as this blinds the kubelet to genuine runtime deadlocks later on. Instead, implement a startupProbe:
startupProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 30
periodSeconds: 2
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
failureThreshold: 3
When a startupProbe is defined, the application is granted up to 60 seconds (30 * 2s) to complete initialization. During this window, livenessProbe and readinessProbe execution is completely suspended. Once the startupProbe succeeds for the first time, the livenessProbe assumes responsibility for routine health checks.
5. Hands-on Lab: Failure Simulation and Triage
The following manifests simulate canonical failure scenarios.
Prerequisites: Provision an Isolated Namespace
kubectl create namespace k8s-lab-crashloop
Scenario 1: Missing Environment Variable (Exit Code 1)
Save as 01-crash-missing-env.yaml:
apiVersion: v1
kind: Pod
metadata:
name: lab-missing-env
namespace: k8s-lab-crashloop
spec:
restartPolicy: Always
containers:
- name: app
image: alpine:3.20
command: ["/bin/sh", "-c"]
args:
- |
if [ -z "$DATABASE_URL" ]; then
echo "[FATAL] Thieu bien DATABASE_URL!" >&2;
exit 1;
fi;
sleep 3600;
Apply the manifest and inspect the previous container logs:
kubectl apply -f 01-crash-missing-env.yaml
kubectl logs lab-missing-env -n k8s-lab-crashloop --previous
Scenario 2: Memory Limit Exceeded - OOMKilled (Exit Code 137)
Save as 02-crash-oom-killed.yaml:
apiVersion: v1
kind: Pod
metadata:
name: lab-oom-killed
namespace: k8s-lab-crashloop
spec:
restartPolicy: Always
containers:
- name: app
image: alpine:3.20
resources:
limits:
memory: "32Mi"
command: ["/bin/sh", "-c"]
args:
- |
head -c 64M /dev/zero | tail -c 64M;
Upon execution, the 32Mi limit is breached, resulting in exit code 137:
kubectl apply -f 02-crash-oom-killed.yaml
kubectl describe pod lab-oom-killed -n k8s-lab-crashloop | grep -E "Reason|Exit Code"
Scenario 3: Protracted Startup Killed by Liveness Probe (Exit Code 143)
Save as 03-crash-probe-mismatch.yaml:
apiVersion: v1
kind: Pod
metadata:
name: lab-probe-mismatch
namespace: k8s-lab-crashloop
spec:
restartPolicy: Always
containers:
- name: app
image: alpine:3.20
command: ["/bin/sh", "-c"]
args:
- |
sleep 15;
touch /tmp/healthy;
sleep 3600;
livenessProbe:
exec:
command: ["cat", "/tmp/healthy"]
initialDelaySeconds: 2
periodSeconds: 2
failureThreshold: 2
The application requires 15 seconds to create the health file, but the probe configuration allows a maximum of only 6 seconds. The container is terminated via SIGTERM.
Scenario 4: Remediation via startupProbe
Save as 04-crash-probe-fixed.yaml:
apiVersion: v1
kind: Pod
metadata:
name: lab-probe-fixed
namespace: k8s-lab-crashloop
spec:
restartPolicy: Always
containers:
- name: app
image: alpine:3.20
command: ["/bin/sh", "-c"]
args:
- |
sleep 15;
touch /tmp/healthy;
sleep 3600;
startupProbe:
exec:
command: ["cat", "/tmp/healthy"]
failureThreshold: 15
periodSeconds: 2
livenessProbe:
exec:
command: ["cat", "/tmp/healthy"]
periodSeconds: 5
failureThreshold: 2
The startupProbe permits up to 30 seconds (15 * 2s), allowing the container to initialize successfully and transition to the Running phase.
6. Automated Pod Triage Script
Below is the pod-triage.sh Bash script, which parses JSON payloads directly from kubectl to diagnose root causes:
#!/usr/bin/env bash
# pod-triage.sh: Rapid CrashLoopBackOff root cause analysis from Pod status
set -euo pipefail
POD_NAME="${1:-}"
NAMESPACE="${2:-default}"
if [ -z "$POD_NAME" ]; then
echo "Cach dung: $0 <ten-pod> [namespace]" >&2
exit 1
fi
POD_JSON=$(kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o json 2>/dev/null || true)
if [ -z "$POD_JSON" ]; then
echo "[LOI] Khong tim thay Pod $POD_NAME trong namespace $NAMESPACE." >&2
exit 2
fi
STATUS=$(echo "$POD_JSON" | jq -r '.status.phase // "Unknown"')
WAITING_REASON=$(echo "$POD_JSON" | jq -r '.status.containerStatuses[0].state.waiting.reason // empty')
LAST_REASON=$(echo "$POD_JSON" | jq -r '.status.containerStatuses[0].lastState.terminated.reason // empty')
LAST_EXIT=$(echo "$POD_JSON" | jq -r '.status.containerStatuses[0].lastState.terminated.exitCode // empty')
RESTARTS=$(echo "$POD_JSON" | jq -r '.status.containerStatuses[0].restartCount // 0')
echo "=================================================="
echo "BAO CAO CHAN DOAN POD: $POD_NAME (ns: $NAMESPACE)"
echo "Trang thai hien tai: $STATUS"
echo "Ly do cho: ${WAITING_REASON:-None}"
echo "So lan khoi dong lai: $RESTARTS"
echo "Ly do lan chet truoc: ${LAST_REASON:-None}"
echo "Exit Code lan chet truoc: ${LAST_EXIT:-None}"
echo "--------------------------------------------------"
if [ "$LAST_EXIT" = "137" ] || [ "$LAST_REASON" = "OOMKilled" ]; then
echo "[CHAN DOAN] Nguyen nhan: OOMKilled (Tran RAM)."
echo "[XU LY] Tang resources.limits.memory hoac kiem tra memory leak."
elif [ "$LAST_EXIT" = "127" ]; then
echo "[CHAN DOAN] Nguyen nhan: Command Not Found."
echo "[XU LY] Kiem tra lai command/args hoac entrypoint trong image."
elif [ "$LAST_EXIT" = "126" ]; then
echo "[CHAN DOAN] Nguyen nhan: Permission Denied."
echo "[XU LY] Kiem tra chmod +x cho script hoac securityContext."
elif [ "$LAST_EXIT" = "143" ]; then
echo "[CHAN DOAN] Nguyen nhan: SIGTERM (Kha nang cao do Liveness Probe)."
echo "[XU LY] Kiem tra Events trong describe pod va them startupProbe."
elif [ "$LAST_EXIT" = "1" ] || [ -n "$LAST_EXIT" ]; then
echo "[CHAN DOAN] Nguyen nhan: Loi ung dung (Exit Code: $LAST_EXIT)."
echo "[XU LY] Chay: kubectl logs $POD_NAME -n $NAMESPACE --previous --tail=100"
else
echo "[CHAN DOAN] Pod chua ghi nhan lan thoat nao co exit code ro rang."
fi
echo "=================================================="
7. Resource Cleanup and Cost Implications
Upon lab completion, tear down the namespace to reclaim cluster resources:
kubectl delete namespace k8s-lab-crashloop
Cost Analysis: The entire lab utilizes minimal Alpine containers (~5MB footprint) with zero LoadBalancers or PersistentVolumes. Execution cost on a local cluster is zero; impact on managed cloud environments (EKS/GKE) is negligible.
8. Official References
Technical specifications in this guide were verified against official Kubernetes documentation as of October 26, 2026:
- [1] Kubernetes Documentation: Pod Lifecycle and Restart Policy -
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/ - [2] Kubernetes Documentation: Configure Liveness, Readiness and Startup Probes -
https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ - [3] Kubernetes Documentation: Assign Memory Resources to Containers and Pods -
https://kubernetes.io/docs/tasks/configure-pod-container/assign-memory-resource/ - [4] Kubernetes Documentation: Determine the Reason for Pod Failure -
https://kubernetes.io/docs/tasks/debug/debug-application/determine-reason-pod-failure/ - [5] Kubernetes Documentation: Debug Pods and Container Logs -
https://kubernetes.io/docs/tasks/debug/debug-application/debug-pods/