Sub topic 7
Out-of-memory kills and resource pressure
This chapter assumes you can read docker inspect output and exit codes, which earlier chapters cover. You should also know that a container is a Linux process running inside cgroups, which are kernel limits on memory, CPU, and process count. Here you will learn to confirm that a container was killed for using too much memory, find out why, and tell that case apart from other resource problems.
How the kill happens
A container with no memory limit can use as much host memory as the kernel allows. A container started with --memory (or -m) gets a cgroup limit. When the processes in that cgroup try to use more than the limit, and the kernel cannot reclaim enough memory, the kernel's OOM killer sends SIGKILL to a process in the cgroup. A process cannot catch or handle SIGKILL, so it gets no chance to log a message or clean up.
If the killed process is the container's main process (PID 1), the container exits with code 137, which is 128 plus signal 9. Docker also records OOMKilled=true in the container state.
Confirming an OOM kill
Exit code 137 alone does not prove an OOM kill. docker kill and a docker stop that exceeds its timeout also end in SIGKILL. Check the flag:
docker inspect --format 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}} error={{.State.Error}}' webRead the result like this:
| exit | oom | Likely meaning |
|---|---|---|
| 137 | true | The kernel killed the container for exceeding its memory limit. |
| 137 | false | Something sent `SIGKILL`: `docker kill`, a stop timeout, or an orchestrator. |
| 0 or 1 | true | A child process was OOM-killed, and PID 1 later exited by itself. |
| 143 | false | `SIGTERM` was delivered and the process exited. This is a normal stop. |
The third row matters. OOMKilled is set when the cgroup records an OOM event, not only when PID 1 dies. A web server that forks workers may lose one worker to the OOM killer and keep running. The application then shows odd errors, such as dropped requests, while docker ps shows nothing wrong.
On the host, the kernel log gives independent confirmation:
dmesg -T | grep -i -E 'out of memory|oom-kill|killed process'You may need sudo. The log names the process that was killed and the cgroup it belonged to. On systems with systemd you can also use journalctl -k.
Reproducing an OOM kill
You can see the whole sequence on a throwaway container. This command limits the container to 64 MB and then allocates 200 MB:
docker run --name hog --memory=64m --memory-swap=64m python:3.12-alpine \
python -c "x = b'x' * (200 * 1024 * 1024); print(len(x))"
docker inspect --format 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' hog
docker rm hogThe container prints nothing, and the inspect output shows exit=137 oom=true. The silence is typical. A process killed by SIGKILL writes no final log line, so an empty or abruptly ending log is itself a clue.
Setting --memory-swap equal to --memory turns off swap for the container. Without it, Docker lets the container use swap up to the same amount again (if the host has swap enabled), which delays the kill and makes the application slow before it dies.
Seeing resource use with docker stats
docker stats reports live usage per container. For a one-time snapshot with chosen columns:
docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.CPUPerc}}\t{{.PIDs}}'
docker stats --no-streamThings to keep in mind when reading it:
MemPercis measured against the container's limit. If the container has no limit, the denominator is the host's total memory, and a high percentage can mean nothing about the container itself.- Docker subtracts reclaimable page cache from
MemUsageon current versions, but the exact accounting depends on the cgroup version. Do not expect it to matchpsortopfigures exactly. - A snapshot taken after the crash shows nothing, because stopped containers are not listed. To catch a leak, run
docker stats webin a second terminal while you reproduce the problem and watch whether memory climbs steadily (a leak) or jumps at one moment (a large allocation). - A steady climb followed by a kill points to a leak or an unbounded cache. A jump points to a specific request or job, so correlate it with
docker logs --timestamps.
To see the configured limit, and to confirm that one is set at all:
docker inspect --format 'memory={{.HostConfig.Memory}} swap={{.HostConfig.MemorySwap}} cpus={{.HostConfig.NanoCpus}} pids={{.HostConfig.PidsLimit}}' webA value of 0 for memory means no limit. The number is in bytes, so 536870912 is 512 MB.
Reading the cgroup counters
From inside a running container you can read the kernel's own counters. On a host using cgroup v2:
docker exec web cat /sys/fs/cgroup/memory.max
docker exec web cat /sys/fs/cgroup/memory.current
docker exec web cat /sys/fs/cgroup/memory.eventsmemory.max is the limit (or the word max when unlimited), and memory.current is the present usage. In memory.events, the oom_kill counter shows how many processes the kernel has killed in this cgroup. A non-zero value with a container that still runs is the child-process case described above. Cgroup v1 hosts use different file names under /sys/fs/cgroup/memory/, so check which version you have with docker info --format '{{.CgroupVersion}}'.
Common causes and fixes
- The limit is too small for the workload. Raise it with
--memory, or change it on a live container withdocker update --memory 1g --memory-swap 1g web. Change--memory-swaptogether with--memory, or Docker may reject the update. - A runtime does not know about the limit. Older Java versions, and Node.js with a large default heap, sized themselves from host memory and ignored the cgroup. Modern JVMs read the cgroup limit, but you may still want
-XX:MaxRAMPercentage=75. For Node.js, set--max-old-space-sizebelow the container limit. Leave headroom, because the runtime also uses memory outside its heap (thread stacks, native buffers, the code itself). - A real leak. Raising the limit only delays the kill. Use
docker statsover time to confirm the climb, then profile the application. - Too many processes sharing one limit. The limit covers every process in the container. A server with many workers needs a limit sized for all of them.
- A memory-backed filesystem. Files written to
tmpfsmounts, or to/dev/shm, count against the container's memory. A job that writes large temporary files there can cause an OOM kill that looks like a heap problem.
Other kinds of resource pressure
Not every limit kills. CPU limits throttle instead. With --cpus=0.5 the container is paused for part of each scheduling period, so it slows down but keeps running. This shows up as high latency with a CPUPerc pinned near the limit. On cgroup v2 check docker exec web cat /sys/fs/cgroup/cpu.stat and look for rising nr_throttled and throttled_usec.
A --pids-limit is different again. When the container reaches it, calls to fork and thread creation fail with errors such as Resource temporarily unavailable, and the application may crash with its own message. These errors appear in the logs, unlike an OOM kill.
Disk is a third source of pressure. A full host disk or a full volume causes write errors and startup failures, not kills. Check it with docker system df and df -h.
Summary of the diagnosis
- Read
ExitCodeandOOMKilledwithdocker inspect. - Confirm in
dmesgormemory.events. - Compare usage from
docker statsagainstHostConfig.Memory. - Decide whether the limit, the runtime configuration, or the application is wrong.
- Change one thing, then reproduce and check again.
Exercise
A container named api exits repeatedly. docker inspect shows exit=137 oom=false, and dmesg has no OOM entries. Is memory the cause? What do you check next?
Show answer
Memory is unlikely to be the cause. Exit code 137 only means the process received SIGKILL, and OOMKilled=false with a clean kernel log says the kernel did not send it. Something else did: a docker kill, a docker stop whose timeout expired because the application ignored SIGTERM, or an orchestrator or script. Check docker events --filter container=api to see which events (kill, stop, die) precede each exit, and look at who ran them. If a stop timeout is the cause, make PID 1 handle SIGTERM, for example by using an exec-form ENTRYPOINT or an init process.
Exercise
You run docker stats --no-stream and a container shows MemPerc of 3%, yet it was OOM-killed an hour ago. Give two possible reasons that the figure looks harmless.
Show answer
First, the container may have no memory limit, so the percentage is calculated against the host's total memory and says nothing about a limit. Second, the snapshot was taken after a restart, when usage had dropped, and the kill happened at the peak. Run docker stats continuously during the failing workload, and read HostConfig.Memory to see whether a limit exists.