Debugging CrashLoopBackOff and OOMKilled .NET pods: kubectl describe, events, logs --previous, exit codes (1, 134, 137, 139), probe failures versus startup exceptions, missing configuration or identity, debug containers and dotnet-dump, and prevention.
CrashLoopBackOff means the container keeps exiting and the kubelet is backing off restarts (up to 5 minutes). I start with kubectl describe pod: Last State, Reason and Exit Code, plus events. Then kubectl logs <pod> --previous to see the crashed container's output.
The exit code points the way: 1 is usually an unhandled .NET exception at startup (missing config, Key Vault 403, failed migration); 137 is SIGKILL, either OOMKilled (Reason says so) or a liveness probe kill (events say "Liveness probe failed"); 139 is a native crash.
For OOMKilled I compare working set to the limit with Container Insights and dotnet-counters, then decide if it's a leak, native memory or a limit that's too small. Fix the cause; don't just raise the limit.
"CrashLoopBackOff isn't an error in itself; it's Kubernetes saying 'this container keeps dying, so I'm waiting longer between restarts', 10 seconds, 20, 40, up to five minutes. So the first job is to find out how it died. I run
kubectl describe pod, look at the container's Last State: the reason, the exit code and the timestamps, and read the events at the bottom. Thenkubectl logs <pod> --previous, because the current container might have just started and has nothing useful yet.The exit code splits the problem. Exit code 1 with a stack trace in the previous logs is the app throwing during startup: in .NET that's usually an options validation failure from
ValidateOnStart, a missing connection string, a403from Key Vault because the workload identity isn't federated, or EF Core migrations running at startup against a database it can't reach. Exit code 137 means SIGKILL. If the reason isOOMKilled, the kernel killed it for crossing the memory limit. If the reason isErroror the events show 'Liveness probe failed' then 'Killing', Kubernetes killed a healthy-but-slow app, typically because there's no startup probe and the liveness probe starts checking before the app is ready. Exit 143 is a normal SIGTERM, and 139 is a segfault in native code.For OOMKilled, I compare memory over time in Container Insights with the limit, and check whether it's a gradual climb, which suggests a leak, or a spike at a specific request. I attach
kubectl debugwith an SDK image and rundotnet-countersanddotnet-gcdumpto see if the managed heap is growing or if it's native memory. For example, at [company] a [worker] was OOMKilled every [40 minutes]; the managed heap was flat at [150 MB] but working set climbed to the [512 Mi] limit. It was [a native buffer from an image library not being disposed]. The mistake I see is doubling the memory limit and calling it fixed: that only stretches the time between crashes."
| Exit code | Signal | Usual meaning for .NET | Where to look |
|---|---|---|---|
| 0 | — | App ended normally (worker finished, no host) | Program flow; restartPolicy |
| 1 | — | Unhandled exception | kubectl logs --previous |
| 134 | SIGABRT | Runtime abort (fatal error, failed assert, stack overflow) | Logs, crash dump |
| 137 | SIGKILL | OOMKilled, or killed after failed liveness probe / grace period | describe: Reason and events |
| 139 | SIGSEGV | Native crash (interop, native library) | Crash dump |
| 143 | SIGTERM | Graceful stop requested | Normal during rollouts |
| What you see | Likely cause | Fix |
|---|---|---|
Exit 1, OptionsValidationException |
Missing or bad config | Fix ConfigMap/secret, check env var names (__) |
Exit 1, AuthenticationFailedException / 403 from Key Vault |
Workload identity or RBAC | Federated credential, role assignment |
Events: Liveness probe failed, Killing |
Probe too early or checks dependencies | Add startup probe; liveness checks process only |
Readiness probe failed but no restarts |
App up but not ready | Check dependency or port; not a crash loop |
Reason OOMKilled |
Memory over limit | Leak, native memory, or real need; measure first |
ImagePullBackOff (not a crash loop) |
Wrong tag or no ACR pull rights | Fix tag, attach ACR to AKS |
| Exit 0 repeatedly | Process exits (e.g. no app.Run(), worker loop ends) |
Keep host running; use a Job for one-off work |
A rollout of a new API version went into CrashLoopBackOff on all new pods. logs --previous showed OptionsValidationException: Payments:ApiBaseUrl is required; the new setting had been added to appsettings.Development.json but not to the ConfigMap. Because maxUnavailable was 0 the old pods kept serving, so impact was zero; adding the value fixed it in 4 minutes.
Checks whether the candidate has a systematic method for crashing pods and can read Kubernetes signals correctly.
Green flags
describe and logs --previouskubectl debug and dotnet diagnostic toolsRed flags
` | Last State, Reason, Exit Code, probe config, events | | Previous logs | `kubectl logs
-c api --previous` | stdout/stderr of the crashed run | | Events | `kubectl get events --sort-by=.lastTimestamp` | Probe failures, OOM, scheduling, image pulls | | Node | `kubectl describe node` | Memory pressure, evictions | | Telemetry | Container Insights, Log Analytics (`KubePodInventory`, `ContainerLogV2`) | Restarts and logs over time | | Application Insights | Exceptions, traces | Startup exceptions if the SDK initialised in time | Startup exceptions often happen **before** Application Insights or OpenTelemetry exporters flush, so stdout logs (`kubectl logs --previous` or `ContainerLogV2`) are the most reliable source. Writing console logs in JSON helps. ## 3. Probes that kill healthy apps Without a **startup probe**, the liveness probe starts after `initialDelaySeconds`. A .NET app doing JIT, warming caches or running migrations may take 20–40 s on a small CPU limit. Liveness fails `failureThreshold` times, the kubelet sends SIGTERM, then SIGKILL after the grace period: exit 137 with no OOM. The fix is a startup probe with `failureThreshold × periodSeconds` greater than the worst start time, and a liveness check that doesn't touch dependencies. ## 4. OOMKilled in .NET - The kernel kills the whole container when total memory (managed heap + native + page cache that can't be reclaimed) exceeds `memory.max`. - The GC's hard limit (75% of the container limit by default) protects only the managed heap. If the heap hits it, you get `OutOfMemoryException` (exit 1 or 134), not OOMKilled. - So OOMKilled with a modest heap points at native memory: unmanaged buffers, many threads (1 MB+ stack each), native libraries, or memory-mapped files. - Tools: `dotnet-counters` (working set versus `gc-heap-size`), `dotnet-gcdump` for managed growth, `dotnet-dump` + `!eeheap`/`!dumpheap -stat`, and for native growth, comparing `/proc/1/smaps_rollup` over time. ## 5. Debugging a crashing or chiseled container If the container exits too fast to `exec` into, temporarily override the command (`command: ["sleep", "3600"]`) in a copy of the pod with `kubectl debug
The commands I run, in order:
# 1. What state, how many restarts?
kubectl get pods -n orders -l app=orders-api
# 2. Why did the last container die? Look at Last State, Reason, Exit Code and Events
kubectl describe pod orders-api-7d9f8-abcde -n orders
# 3. What did it print before dying?
kubectl logs orders-api-7d9f8-abcde -n orders -c api --previous
# 4. Recent events across the namespace (probe failures, OOM, image pulls)
kubectl get events -n orders --sort-by=.lastTimestamp | tail -20
# 5. Memory against the limit (needs metrics-server)
kubectl top pod -n orders --containers
# 6. Attach .NET diagnostics to a running pod via an ephemeral container
kubectl debug -it orders-api-7d9f8-abcde -n orders \
--image=mcr.microsoft.com/dotnet/sdk:10.0 --target=api -- bash
# dotnet tool install -g dotnet-counters && ~/.dotnet/tools/dotnet-counters monitor -p 1
Make startup failures loud and readable, and probes honest:
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Fail fast at startup with a clear message instead of failing on the first request
builder.Services.AddOptions<PaymentsOptions>()
.BindConfiguration("Payments")
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Logging.AddJsonConsole(); // stdout survives in 'kubectl logs --previous' and ContainerLogV2
builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapHealthChecks("/healthz/live");
app.Run();
public sealed record PaymentsOptions
{
[System.ComponentModel.DataAnnotations.Required, System.ComponentModel.DataAnnotations.Url]
public string ApiBaseUrl { get; init; } = "";
}
# Startup probe gives a slow-starting app up to 60 s before liveness takes over
startupProbe:
httpGet: { path: /healthz/live, port: 8080 }
periodSeconds: 2
failureThreshold: 30
livenessProbe:
httpGet: { path: /healthz/live, port: 8080 }
periodSeconds: 10
failureThreshold: 3
// Log Analytics: restarts and OOM kills in the last day
KubePodInventory
| where TimeGenerated > ago(1d) and Namespace == "orders"
| summarize Restarts = max(ContainerRestartCount) by Name, ContainerLastStatus
| order by Restarts desc
kubectl logs without --previous. Why it is wrong: You see the new container's startup, not the crash. Instead: Always check --previous for a crash loop.Program.cs on every pod. Why it is wrong: Several replicas race, one fails, and a schema problem becomes a crash loop. Instead: Run migrations once in a pipeline step or a Kubernetes Job with a migration bundle.ContainerLogV2.A crash loop is a symptom; the useful skill is narrowing it down in a fixed order: describe, previous logs, events, metrics, then live diagnostics. I also design for it: ValidateOnStart so config errors fail fast and clearly, JSON stdout logs, startup probes, migrations out of the app process, and rollouts with maxUnavailable: 0 so a bad version never takes the old pods down.
| Symptom | First check | Common fix | Don't |
|---|---|---|---|
| Exit 1 crash loop | logs --previous |
Config, identity, dependency at startup | Disable ValidateOnStart to make it start |
| Exit 137 + probe events | Probe settings | Startup probe, process-only liveness | Remove probes |
| OOMKilled | Working set versus heap over time | Fix leak or native usage, then size | Double the limit blindly |
| Exit 0 loop | Program flow | Keep host alive or use a Job | Add while(true) hacks |
I measure restart counts per deployment, OOMKilled events and mean time to diagnosis in post-incident reviews.
RAM is physical memory. Each process gets a virtual address space that the OS maps onto RAM page by page. The working set is what's resident in RAM right now; private (committed) memory is what the process owns. The GC heap is only one part: native allocations (native libraries, NativeMemory, unmanaged buffers), thread stacks, JIT code, and runtime structures add to it. In Kubernetes, the cgroup limit counts all of it, and going over gets the container OOMKilled (exit code 137), not an OutOfMemoryException. So if the GC heap is small but the pod dies, I compare GC heap size with working set in dotnet-counters. A big gap points to native memory or too many threads; a growing GC heap points to a managed leak I'd chase with dotnet-gcdump. Then I fix the cause and set limits and GC settings deliberately.
When I can't attach a debugger, I take a dump: a snapshot of the process's memory, threads and stacks that I analyse offline. For a hang or a leak, dotnet-dump collect -p <pid> does it in seconds. For crashes, I enable automatic crash dumps with the DOTNET_DbgEnableMiniDump environment variables. On App Service I use Diagnose and solve problems, and in Kubernetes dotnet-monitor. Then I analyse with dotnet-dump analyze: clrstack -all and syncblk for hangs, dumpheap -stat and gcroot for leaks, pe for exceptions. Or I open the dump in Visual Studio and use the Threads and Parallel Stacks windows. Dumps contain customer data, so they're handled as sensitive.
On a laptop, DefaultAzureCredential uses my az login identity, which has broad dev rights. In Azure it uses the app's managed identity, which may not exist, may be the wrong one, or may lack roles. I diagnose in layers:
AZURE_CLIENT_ID set?ForbiddenByRbac means missing Key Vault Secrets User (or the vault uses access policies). SQL's <token-identified principal> means the token worked but there is no contained database user.ForbiddenByFirewall or ForbiddenByConnection means firewall or private endpoint and DNS problems.The trade-off: granting broad roles makes the error go away fast but breaks least privilege; the right fix is the exact data role at the exact scope.
How to tell it (STAR)
**S:** Our [document-processing] worker on AKS was being OOMKilled every [40 minutes], and the upload backlog was growing. **T:** I owned finding the root cause rather than just adding memory. **A:** I confirmed OOMKilled with `kubectl describe`, then attached a debug container and used `dotnet-counters`: the managed heap was flat, but working set kept climbing, so it was native memory. I traced it to [native image objects] that weren't disposed, fixed it with `using`, and added a soak test and a CA2000 analyser rule. **R:** Restarts went from [about 36 a day] to zero, memory stayed flat at [220 MB], and we returned to the original limit, saving [the extra node].
Last updated 23 Nov 2026.