跳到正文
DEV Community· Feres Berbeche·· 6 小時前AI 評分56

如何在 Kubernetes 中不靠猜測排查 CrashLoopBackOff

How to debug CrashLoopBackOff in Kubernetes without guessing

AI 導讀

這篇指南提出一套以證據排查 Kubernetes CrashLoopBackOff 的流程,先檢查容器的終止原因與退出碼,再讀取前次容器日誌。終止原因為 OOMKilled、退出碼 137 可指向記憶體終止;退出碼 1 則表示一般應用程式錯誤。Pod 事件、記憶體數據、節點狀態及部署記錄可用來排查探針、設定、掛載或節點問題,並確認故障是否始於一次部署。

正文

CrashLoopBackOff is the most common thing a Kubernetes cluster will ever tell you, and it is
almost useless on its own. It does not say the container ran out of memory. It does not say a
config value is missing. It does not even say the container is broken — a failing readiness probe
and a bad image entrypoint both end up here. All it says is: this container keeps exiting, and
the kubelet is now waiting longer between attempts.

The backoff itself is the only part that is precise. The kubelet restarts a failed container after
10 seconds, then 20, then 40, doubling to a five-minute ceiling. When you see the gaps widening,
you are watching that timer, not a diagnosis.

A timeline of a crash-looping container: it starts and exits four times, with the kubelet waiting 10 seconds, then 20, then 40 between restarts
The widening gaps are the kubelet’s backoff timer. They tell you how long it has been failing, and nothing at all about why.

So the work is the same every time: figure out which of the half-dozen causes you have, using
evidence rather than the order you happen to think of them in. This article is the order that
actually works, and what each step rules in or out.

Start with the exit, not the logs

The single most informative field is how the container died, and it is one command away:

kubectl -n <namespace> get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated}' | jq

You are looking for two things:

Field What it tells you
reason Error means the process exited on its own. OOMKilled means the kernel killed it.
exitCode 1 is an ordinary application error. 137 is SIGKILL — nearly always the OOM killer. 139 is a segfault. 143 is SIGTERM.

This one distinction splits the problem space in half before you have read a single log line.

The lastState.terminated field branching into two cases: exit code 1 with reason Error, where the process chose to stop, and exit code 137 with reason OOMKilled, where the kernel stopped it
One field, two very different investigations. Chasing logs before reading it is how the first ten minutes get spent on the wrong branch.

An exitCode of 1 with reason: Error means the application chose to stop, and its logs will
say why. OOMKilled with 137 means it never got the chance, and the logs will simply stop
mid-sentence.

Note: A container that is OOMKilled is not always leaking. A perfectly healthy process that
allocates one large batch can cross its limit in the gap between two metrics scrapes, and the
memory graph will look flat the whole time. We walk through exactly that case in
OOMKilled and exit code 137.

Then read the logs of the previous container

The running container is a fresh attempt and usually has nothing in it yet. The one that died has
the answer:

kubectl -n <namespace> logs <pod> --previous --tail=50

An application that refuses to start almost always says so in its last few lines. What you want is
the final non-framework line — the one written by the service itself rather than by the runtime
unwinding afterwards.

Here is a real one, from a crash loop in a lab cluster. The container printed configuration error: DATABASE_URL is not set, refusing to start and exited
with code 1, about a second after each start. That is a complete diagnosis: the Deployment's pod
template does not supply a variable the image requires. No node problem, no image problem, no
probe problem — and, importantly, no memory problem, which the working set of ~8 MiB against a
128 MiB limit independently confirms.

When the logs are empty

Two cases produce a crash loop with no useful logs at all:

  • The process was killed before it could write. Check lastState.terminated.reason again — an OOMKilled during startup looks exactly like this.
  • The entrypoint is wrong. exec: "serve": executable file not found in $PATH appears in the pod's events, not its logs, because the container never started:
  kubectl -n <namespace> describe pod <pod> | sed -n '/Events:/,$p'

Rule out the four impostors

Before accepting "the application is broken", eliminate the four causes that produce an identical
CrashLoopBackOff without the application being at fault:

  1. A failing readiness or liveness probe. A liveness probe that fails restarts a container that was working. The tell is a Killing event citing the probe, and an application log that ends normally rather than with an error.
  2. A memory limit the workload cannot live inside. reason: OOMKilled, exitCode: 137.
  3. A missing ConfigMap, Secret or volume. The pod never reaches Running; events show CreateContainerConfigError or FailedMount.
  4. Node trouble. Disk pressure, a full emptyDir, or an evicted pod. kubectl describe node shows the pressure conditions.

Each of these has a distinct signature in a different data source — events, metrics, the pod
spec, the node. That is the actual reason crash-loop triage is slow: the evidence that separates
them is scattered across four tools, and you are switching between them under time pressure while
a service is down.

Gathering all of it in one pass

A crash loop rarely arrives as one alert: restarts, failed probes and unavailable replicas all
fire, across every pod of the workload. Treat them as one incident first, and investigate that
once rather than each alert on its own.

A good investigation, by hand or automated, does not replay a checklist. It states the candidate causes as hypotheses, each
with a prediction: if this is an OOM kill, the last termination reason is OOMKilled and the
exit code is 137
; if a config value is missing, the previous container's last log line names it
and the exit is the application's own
; if a release caused it, the restarts begin at the
rollout
. Then it reads the cluster, the previous container's logs, Prometheus, Loki and the
rollout history to confirm or refute each one.

The value is not that a model looked at your cluster. It is that the reads you would have made by
hand were made within seconds of the alert, while the evidence was still there. Metrics get thin
fast: series for a deleted pod disappear, and the terminated container's logs age out of
retention. An investigation that starts at 03:05 sees things that an engineer starting at 09:00
cannot.

Reading the result critically

A crash-loop diagnosis is only worth having if you can check it. Three things make that possible.

The mechanism has to be stated, not the category. "The application is misconfigured" is a
restatement of the symptom. A mechanism names the value, the file, the line and the consequence,
so you can disagree with it.

The losing hypotheses have to be shown. If the answer is a missing environment variable, you
should be able to see that an OOM kill and a failing probe were considered, and which record
ended each of them. A diagnosis that hides its refuted alternatives cannot be argued with.

Every claim has to lead to a query. Each finding cites the tool call behind it: the exact
kubectl read or PromQL, the cluster, the time and the raw answer. You can re-run it and see the
new answer diffed against the recorded one, which settles "is that still true?" in a few seconds.

Tip: An empty answer, a source that failed and a source you never configured are three
different facts. Only the first is evidence that something did not happen. If a source you
needed could not be read, the honest result is "insufficient evidence", with the missing source
named.

A checklist you can keep

For the next crash loop, in order:

  1. lastState.terminated.reason and exitCode — split OOM from application exit.
  2. logs --previous — the last line the application wrote.
  3. describe pod events — probes, mounts, image pulls, scheduling.
  4. Memory working set against the limit — was there headroom at the kill?
  5. What changed — a rollout, a sync, an out-of-band edit to a ConfigMap.
  6. The restart gaps — widening means the kubelet's backoff, not an accelerating fault.

Step 5 is the one most often skipped and most often decisive. A crash loop that starts at a
deploy boundary is a different investigation from one that starts on its own, and
Argo CD's sync history will tell you which you have.

Related failures

Crash loops sit next to two neighbours worth recognising on sight. A pod that never starts at all
is not crash-looping — it is stuck in Pending, and the scheduler will say
why
. And a container killed at its memory ceiling
deserves its own reading of the evidence, because the
metrics frequently look innocent.

If you want the general version of the method rather than this one failure mode, the same
discipline — enumerate causes, gather evidence per cause, eliminate explicitly — is written up in
root cause analysis for Kubernetes incidents.

This article was written with AI assistance. It first appeared on alertigate.com.

來源:DEV Community · dev.to