Back when I first deployed microservices for an e-commerce project, I once spent two whole days tracking down a memory leak inside a container. The incident hit right during peak hours. The entire production server suddenly froze, and even SSH stopped responding.
After rebooting the server and digging through the logs, the culprit finally surfaced: a small image-resizing service was leaking memory. It chewed through all 16GB of the host’s RAM and took down the database running on the same node with it. If I had configured resource limits from the start, the incident would have stopped at a simple container restart instead of crashing the entire system.
By default, Docker places no barriers on CPU or RAM usage for containers. That’s convenient for local development, but it’s a massive risk in production. Below, we’ll dive straight into setting up proper resource limits, explaining why containers die unexpectedly, and stopping OOM Killer errors in their tracks.
Quick Start: Limit CPU and RAM in 5 Minutes
If you need to apply limits right away to a container heading to production, simply add the --cpus, --memory, and --memory-swap flags to your docker run command:
docker run -d \
--name payment-api \
--cpus="1.5" \
--memory="512m" \
--memory-swap="512m" \
--memory-reservation="384m" \
--restart=unless-stopped \
my-registry/payment-api:1.2.0
What does each parameter do?
--cpus="1.5": Caps CPU usage at the equivalent of 1.5 host CPU cores.--memory="512m": Sets a hard limit of 512MB for RAM.--memory-swap="512m": Set to the exact same value as--memoryto completely disable disk swap. This prevents your app from slowing to a crawl due to disk I/O when running low on RAM.--memory-reservation="384m": Sets a soft limit. When the host runs short on RAM, Docker prioritizes forcing the container to release memory down to this threshold.
For teams using Docker Compose (v2 and above) or Docker Stack, the equivalent configuration in docker-compose.yml looks like this:
services:
payment-api:
image: my-registry/payment-api:1.2.0
deploy:
resources:
limits:
cpus: '1.5'
memory: 512M
reservations:
cpus: '0.5'
memory: 384M
Once the container is running, immediately verify that the limits have taken effect with:
docker stats --no-stream payment-api
Deep Dive: The Problem, Causes, and How OOM Killer Works
The “Noisy Neighbor” Problem with Uncapped Resources
Multiple containers running on the same physical server or VPS actually share the same Linux kernel. They draw from the same pool of hardware resources through a mechanism called cgroups (Control Groups).
It only takes one container hitting an infinite loop or a memory leak to consume 100% of the host’s CPU and RAM. Operations teams call this the Noisy Neighbor effect. As a result, critical services sitting right next to it—like your database or Redis—get starved of resources, causing response times to spike from 2ms to several seconds and triggering widespread timeouts.
Why Does OOM Killer (Exit Code 137) Happen?
When total available RAM on the host hits rock bottom, the Linux Kernel steps in to protect itself using the OOM Killer (Out Of Memory Killer). The kernel assigns an OOM score to each running process. Whichever process is hogging the most RAM gets singled out and terminated to free up memory and prevent a kernel panic.
A container terminated by the OOM Killer (or one that exceeds its configured --memory ceiling) stops with Exit Code 137. The number 137 corresponds to the SIGKILL signal (128 + 9). The three most common causes are:
- Memory leaks in code: Global variables that keep growing indefinitely, or database connections and file streams that aren’t closed after each request.
- Traffic spikes: A 5–10x surge in requests spawns more concurrent workers or threads than your estimated RAM budget can handle.
- The default swap trap: If you set
--memory="512m"but forget--memory-swap, Docker automatically allocates an extra 512MB of swap (1GB total). Your app has actually overflowed its RAM and is thrashing the disk, sending I/O wait sky-high while you assume everything is fine.
CPU Limiting Mechanics: Hard Limit vs. Relative Weight
Unlike RAM (where hitting the ceiling results in an immediate kill), CPU is a compressible resource. If a container demands more CPU than allocated, the system simply throttles it (CPU throttling). Your app will slow down, not crash.
--cpus="1.5": A real-time hard limit. Even if other cores on the host are 100% idle, this container will never use more than 1.5 cores.--cpu-shares(default is 1024): Sets a relative priority weight during CPU contention. When the host is idle, the container can freely use all available CPU. During a bottleneck, a container with--cpu-shares=2048receives twice as much CPU time as one left at 1024.
Advanced: Optimizing Your Production Configuration
Be Careful with the –oom-kill-disable Flag
Docker provides the --oom-kill-disable flag to stop the OOM Killer from terminating a container when it hits its RAM limit. However, never enable this flag unless you have also set --memory. Without a RAM ceiling and with OOM Killer disabled, a single leaking process will bring down the entire host machine. This flag is only meant for special cases (such as certain databases that need to flush buffers to disk before shutting down) and must always be paired with an explicit memory limit.
Cap Process Counts with –pids-limit
Many engineers focus only on CPU and RAM while overlooking the risk of fork bombs or runaway thread creation. Every spawned thread consumes kernel memory. You should also cap the maximum number of processes inside your container:
docker run -d \
--name worker-service \
--cpus="1.0" \
--memory="512m" \
--pids-limit=200 \
my-registry/worker:latest
The Trap with Java (JVM) and Node.js Applications
Plenty of developers carefully set --memory="1g", only to watch their Java or Node.js apps get OOM Killed anyway. The reason is that older runtimes (like Java prior to 8u191) or default V8/Node.js configurations sometimes look at the host’s total physical RAM (say, 32GB) instead of the cgroup limit (1GB). Consequently, the runtime confidently allocates a heap size larger than 1GB and gets killed by the kernel immediately.
The definitive fix is to enforce memory limits directly at the runtime layer:
- For Java (JVM): Use the
-XX:MaxRAMPercentage=75.0flag so the JVM allocates at most 75% of the container’s RAM to the heap, leaving the remaining 25% for non-heap memory and OS overhead. - For Node.js: Pass the environment variable
NODE_OPTIONS="--max-old-space-size=384"(in MB) if the container is capped at 512MB of RAM.
Practical Tips for Operating and Debugging OOM Errors
Here are the four quick checks I always run when troubleshooting an incident in production:
- Confirm the exact cause of container termination: Don’t guess—inspect the stopped container’s metadata directly with:
docker inspect payment-api --format='OOMKilled={{.State.OOMKilled}} ExitCode={{.State.ExitCode}}'If you see
OOMKilled=true ExitCode=137, it’s 100% certain the container hit its RAM limit and was killed by the kernel. - Check the host’s kernel logs: To pinpoint the exact timestamp and which process inside the container the OOM Killer targeted, run:
dmesg -T | grep -i -E "oom|killed process" - Leave 20–30% RAM headroom: Never set
--memoryrazor-close to your app’s normal usage. Monitor it through Prometheus/cAdvisor or Grafana for a few days, then multiply the peak usage by 1.3. For example, if your app peaks at 350MB, a hard limit of around 450MB–512MB is ideal. - Set an early alert at 80%: Configure an alert whenever a container stays above 80% of its
--memorylimit for 5 consecutive minutes. Catching it early at 80% gives you time to capture a heap dump or profile your code for leaks before the container crashes completely at 100%.
Setting resource limits for containers is non-negotiable before shipping any service to production. It contains the blast radius when bugs occur and helps you calculate infrastructure costs accurately. By configuring --cpus and --memory properly, disabling swap where appropriate, and constraining runtime heap sizes, you’ll save yourself plenty of sleepless nights dealing with frozen servers.

