Setting Docker resource limits and debugging JVM OOMKilled (137)
Configure cgroup v2 CPU and memory limits in Docker, size JVM heap for container overhead, and diagnose Exit Code 137 OOMKilled crashes.
Unbounded Docker containers can exhaust host memory and trigger the kernel OOM Killer against critical host daemons. This post explains how Docker enforces CPU and memory ceilings through Linux cgroup v2, how to size JVM memory safely inside containers, and how to trace
OOMKilled(Exit Code 137) crashes.
Based on Linux cgroup v2 (Ubuntu 22.04+, Debian 11+, RHEL 9+), Docker Compose v2, and Java 21 (
eclipse-temurin).
1. Why unbounded containers take down the host
One of the most common mistakes when adopting Docker in production is launching containers with docker run or compose.yaml without explicit resource limits.
By default, a Docker container shares the host OS kernel and hardware with no guardrails. Any process inside that container can request every CPU core and every megabyte of physical RAM on the machine.
flowchart TD
subgraph Host["Host Machine (Host OS - 16GB RAM)"]
subgraph Services["Critical Host Daemons"]
D1["sshd (Remote Access)"]
D2["dockerd (Docker Daemon)"]
D3["kubelet / OS Kernel"]
end
subgraph Containers["Running Containers"]
C1["Payment API Container (No Limit)"]
C2["Notification Service Container"]
C3["DB Proxy Container"]
end
OOM["Linux Host Kernel OOM Killer"]
end
C1 -->|"Large Excel export / memory leak (14GB+)"| OOM
OOM -.->|"SIGKILL after badness() scoring"| D1
OOM -.->|"Collateral kill"| C2
Noisy neighbors and the host OOM Killer
When a single container hits a memory leak or allocates aggressively during a traffic spike, the failure cascades across the entire host:
- Free host memory runs dry: The runaway container consumes all available RAM on the node.
- The host kernel invokes the OOM Killer: To prevent a total kernel panic, Linux evaluates each process’s memory footprint and
oom_scoreto pick a victim. - Collateral
SIGKILLterminations: The OOM Killer doesn’t limit itself to the misbehaving container. It can terminatesshd,dockerd, or a local database daemon. - Unresponsive host: Once remote SSH dies, your only option left is a hard reboot or cloud instance reset.
To eliminate this noisy-neighbor risk, every container needs an isolated resource ceiling before it reaches production.
2. How Docker enforces limits with Linux cgroup v2
Docker implements resource isolation through Linux cgroups (Control Groups). Modern distributions (Ubuntu 22.04+, Debian 11+, RHEL 9+) and current Docker Engine releases default to cgroup v2, which exposes a single unified hierarchy under /sys/fs/cgroup.
flowchart TD
A["Docker CLI / Compose Options"] --> B["Docker Daemon (dockerd) / containerd"]
B --> C["runc (OCI Runtime)"]
C --> D["Linux cgroup v2 pseudo-filesystem"]
subgraph CgroupFiles["/sys/fs/cgroup/system.slice/docker-..."]
D --> E["memory.max (Hard limit)"]
D --> F["memory.high (Soft throttle threshold)"]
D --> G["cpu.max (CFS quota / period)"]
end
Memory limits: --memory, --memory-swap, and --memory-reservation
Each Docker memory flag maps directly to control files in the container’s cgroup v2 directory:
| Docker CLI flag | cgroup v2 file | Behavior and recommendation |
|---|---|---|
--memory, -m | memory.max | Hard physical RAM ceiling. Exceeding it triggers the container’s cgroup OOM Killer. |
--memory-reservation | memory.low / memory.high | Soft baseline. Under host memory pressure, the kernel prioritizes reclaiming from containers above this threshold. |
--memory-swap | memory.swap.max + memory.max | Combined ceiling for physical RAM plus swap space. |
Watch how
--memory-swapcounts memory. Its value represents total memory (RAM + Swap), not swap alone. Setting--memory="1g" --memory-swap="2g"grants 1 GB of RAM and 1 GB of swap (2 GB total).
To disable swap completely, set
--memory-swapequal to--memory. Leaving swap unbounded invites disk I/O thrashing under memory pressure, turning what should be a fast container restart into severe latency stalls.
1
2
3
4
5
6
7
# Cap physical memory at 1 GB and disable swap (recommended production baseline)
docker run -d \
--name order-api \
--memory="1g" \
--memory-swap="1g" \
--memory-reservation="768m" \
my-order-api:latest
CPU limits: --cpus and the CFS scheduler
Unlike memory limits, hitting a CPU limit never kills the container. Instead, the kernel applies CPU throttling using the Completely Fair Scheduler (CFS).
Passing --cpus="1.5" caps the container at 150,000 µs of CPU time (cpu.cfs_quota_us) per 100,000 µs scheduling period (cpu.cfs_period_us, 100 ms by default), regardless of how many physical cores the host has.
In cgroup v2, both values live in a single cpu.max file:
1
2
3
4
# Inspect cgroup v2 CPU quota and period
$ cat /sys/fs/cgroup/system.slice/docker-<CONTAINER_ID>.scope/cpu.max
150000 100000
# Format: [quota_us] [period_us]
1
2
3
4
5
# Allocate up to 1.5 CPU cores
docker run -d \
--name payment-worker \
--cpus="1.5" \
my-worker:latest
Be careful not to set --cpus below your workload’s burst needs during startup or garbage collection. Aggressive CPU throttling stretches GC pauses and inflates p99 tail latency even when average CPU usage looks low.
3. Why a 1 GB heap crashes a 1 GB JVM container
When deploying Spring Boot or other Java services to Docker, I regularly see the same outage pattern:
“I gave the container
--memory=1gand set-Xmx1024m, but the container keeps getting killed whenever traffic picks up.”
The root cause is simple: the Java heap is only one slice of a JVM process’s total memory footprint.
flowchart TD
subgraph ContainerLimit["Docker Container cgroup Limit (e.g., 1024MB)"]
subgraph JVMProcess["Total JVM Process Memory (RSS)"]
H["Java Heap Memory (-Xmx, 70~75%)"]
NH1["Metaspace (Class Metadata)"]
NH2["Thread Stacks (-Xss * Thread Count)"]
NH3["Direct Byte Buffers (Netty/NIO)"]
NH4["JIT CodeCache / C2 Compiler"]
NH5["JVM GC & Native C++ Libraries"]
end
OS["Base Container OS & Shell Overhead"]
end
H -.->|"Exceeds cgroup memory.max"| KILL["cgroup OOM Killer (Exit Code 137)"]
Breaking down JVM native overhead
The actual Resident Set Size (RSS) billed against your container’s cgroup includes every non-heap region:
\[\text{Total Memory} = \text{Heap} + \text{Metaspace} + (\text{Thread Count} \times \text{Stack Size}) + \text{Direct Memory} + \text{CodeCache} + \text{Native Overhead}\]- Metaspace: Native memory holding loaded class and method metadata (typically 128–256 MB for a Spring Boot app).
- Thread stacks: Defaults to 1 MB per thread (
-Xss1m). Tomcat’s default 200 worker threads can claim up to 200 MB on their own. - Direct memory: Off-heap buffers allocated by Netty, Spring WebFlux, or gRPC for socket I/O.
- JIT CodeCache: Compiled native machine code produced by the JIT compiler (usually 64–128 MB).
If you assign -Xmx1024m inside a 1 GB container, native regions add 200–400 MB on top of the heap. The process hits memory.max well before the heap even fills up, and the kernel kills it immediately.
Recommended JVM flags: UseContainerSupport and MaxRAMPercentage
Modern JVMs (JDK 8u191+ and JDK 10+) enable -XX:+UseContainerSupport by default, so the JVM reads cgroup limits instead of host RAM. Rather than hardcoding -Xmx, use percentage-based flags so your image adapts cleanly when you resize the container:
1
2
3
4
5
6
7
8
9
10
11
12
13
# Recommended Dockerfile entrypoint for JVM containers
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY app.jar app.jar
ENV JAVA_OPTS="-XX:+UseContainerSupport \
-XX:MaxRAMPercentage=70.0 \
-XX:InitialRAMPercentage=70.0 \
-XX:+ExitOnOutOfMemoryError \
-Djava.security.egd=file:/dev/./urandom"
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
-XX:MaxRAMPercentage=70.0: Caps the Java heap at 70% of the container’s memory limit, leaving 30% for Metaspace, thread stacks, Netty direct buffers, and OS overhead. On containers with 2 GB or more, you can usually raise this to 75%.-XX:+ExitOnOutOfMemoryError: Terminates the JVM immediately on a Java heapOutOfMemoryErrorso Docker or Kubernetes restarts the container instead of leaving it in a half-broken zombie state.
Avoid percentage-only sizing blindly on very small containers (under 512 MB). At 512 MB, 30% leaves only ~150 MB for all non-heap regions, which a typical Spring Boot service can still outgrow—profile RSS with jcmd <pid> VM.native_memory summary before locking in tight limits.
4. Troubleshooting Exit Code 137 and OOMKilled
When a production container vanishes or enters a restart loop, start by inspecting its exit code.
What Exit Code 137 means
POSIX shells report signal-terminated processes as 128 + Signal Number:
Unlike 143 (128 + 15, SIGTERM), which signals a normal graceful shutdown request, 137 means the OS kernel terminated the process immediately with SIGKILL.
Step 1: Check OOMKilled with docker inspect
1
docker inspect <container_name_or_id> --format '{{json .State}}' | jq
Look at the OOMKilled and ExitCode fields:
1
2
3
4
5
6
7
8
9
10
11
{
"Status": "exited",
"Running": false,
"Paused": false,
"Restarting": false,
"OOMKilled": true,
"Dead": false,
"Pid": 0,
"ExitCode": 137,
"Error": ""
}
When "OOMKilled": true appears alongside "ExitCode": 137, the container crossed its cgroup memory.max ceiling.
Step 2: Confirm the kill in host kernel logs (dmesg)
To see which process was killed and how much memory it held at the exact moment of termination, check dmesg on the Docker host:
1
2
# Search kernel logs for OOM events with human-readable timestamps
sudo dmesg -T | grep -i -E "oom|killed process"
Example kernel output:
1
2
[Mon Jun 2 14:22:15 2026] Memory cgroup out of memory: Killed process 349121 (java) total-vm:2841924kB, anon-rss:1042312kB, file-rss:32140kB, shmem-rss:0kB, UID:1000 pgtables:2412kB oom_score_adj:0
[Mon Jun 2 14:22:15 2026] oom_reaper: reaped process 349121 (java), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB
Memory cgroup out of memory: Confirms the kill happened inside the container’s cgroup rather than due to host-wide memory exhaustion.anon-rss:1042312kB: Shows anonymous memory (heap, stacks, native allocations) hit ~1,017 MB, tripping the 1 GB limit.
Step 3: Monitor cgroup v2 memory pressure events
On cgroup v2 hosts, you can track memory pressure before an OOM kill even happens by reading memory.events:
1
cat /sys/fs/cgroup/system.slice/docker-<CONTAINER_ID>.scope/memory.events
Key counters in the output:
low: Number of times memory exceededmemory.lowand triggered reclaim.high: Number of times the process was throttled for exceedingmemory.high.max: Number of times usage hitmemory.maxand forced synchronous reclaim.oom: Number of times the cgroup OOM Killer was invoked.oom_kill: Number of processes actually killed by the OOM Killer.
5. Production-ready Compose resource template
In practice, I define limits in compose.yaml rather than long docker run strings. Here is a production baseline for a Spring Boot service:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
services:
payment-api:
image: mycompany/payment-api:1.0.0
container_name: payment-api
restart: on-failure:5
environment:
- JAVA_OPTS=-XX:+UseContainerSupport -XX:MaxRAMPercentage=70.0 -XX:+ExitOnOutOfMemoryError
ports:
- "8080:8080"
deploy:
resources:
limits:
cpus: '2.0' # Cap compute at 2 CPU cores
memory: 1536M # Hard memory ceiling (1.5 GB)
reservations:
cpus: '0.5' # Reserve at least 0.5 CPU cores
memory: 1024M # Soft baseline memory (1 GB)
# Match physical memory limit to disable swap
memswap_limit: 1536M
labels:
logging.monitor: "true"
Compose V2 note: With Docker Compose v2.0+,
docker compose upenforcesdeploy.resources.limitsandreservationsdirectly on standalone single-node hosts—you no longer need Docker Swarm mode for them to take effect.
Production resource checklist
Before deploying a container to production, run through these four checks:
- Does every container declare
limits.memory? An uncapped container can take downsshdand other services on the host during a leak. - Is swap explicitly controlled? Match
memswap_limit(--memory-swap) tolimits.memory(--memory) unless you have a deliberate reason to tolerate disk paging latency. - Did you account for non-heap runtime overhead? For JVM services, start with
MaxRAMPercentage=70.0(up to75.0on 2 GB+ containers) so Metaspace, thread stacks, and direct buffers have breathing room. - Did you verify Exit Code 137 with
docker inspectanddmesg? Never assume every137exit is an OOM kill—a manualdocker killor orchestrator timeout afterSIGTERMalso sendsSIGKILL. Confirm"OOMKilled": trueand checkdmesgbefore tuning memory.