Resource Limits
By default a container may use all the CPU and memory of the host. One runaway process (a memory leak, an infinite loop) can then starve every other container, or the host itself. Docker uses Linux cgroups to cap what each container gets.
docker run -d --name api \
--memory 512m --memory-swap 512m \
--cpus 1.5 \
--pids-limit 200 \
shop-api:1.4
docker stats --no-streamSample output:
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O PIDS
8b1f0c2d3e4a api 37.42% 203.1MiB / 512MiB 39.67% 1.2MB / 880kB 23| Option | Meaning |
|---|---|
--memory 512m (-m) |
hard memory limit; going over triggers the kernel's OOM killer |
--memory-swap 512m |
memory + swap total; equal to --memory means "no swap" |
--memory-reservation 256m |
soft limit used when the host is under memory pressure |
--cpus 1.5 |
at most 1.5 CPUs' worth of time per scheduling period |
--cpu-shares 512 |
relative weight (default 1024) that only matters when CPUs are contended |
--cpuset-cpus 0,1 |
pin to specific cores |
--pids-limit 200 |
maximum number of processes/threads (stops fork bombs) |
In Compose:
services:
api:
image: shop-api:1.4
mem_limit: 512m
cpus: 1.5
pids_limit: 200
# or, in the Swarm/deploy style also understood by Compose:
deploy:
resources:
limits: {cpus: "1.5", memory: 512M}
reservations: {memory: 256M}Memory: hitting the limit
When a container's memory usage reaches its limit and nothing can be reclaimed, the kernel kills a process in it, usually the main one. The container exits with code 137 and docker inspect shows "OOMKilled": true.
def run_with_limit(limit_mb, usage_per_minute):
used = 0
for minute, delta in enumerate(usage_per_minute, start=1):
used += delta
bar = "#" * (used // 32)
if used > limit_mb:
print(f"min {minute:>2}: {used:>4} MB {bar} > limit {limit_mb} MB")
print("OOM killer: process killed -> Exited (137), State.OOMKilled = true")
return
print(f"min {minute:>2}: {used:>4} MB {bar}")
print("finished within the limit")
leaky = [180, 40, 60, 60, 80, 90, 100] # a memory leak: usage keeps growing
run_with_limit(512, leaky)min 1: 180 MB #####
min 2: 220 MB ######
min 3: 280 MB ########
min 4: 340 MB ##########
min 5: 420 MB #############
min 6: 510 MB ###############
min 7: 610 MB ################### > limit 512 MB
OOM killer: process killed -> Exited (137), State.OOMKilled = true
Language runtimes need to know about the limit, or they size their heaps from the host's memory:
- Java 10+ reads cgroup limits automatically; tune with
-XX:MaxRAMPercentage=75. - Node.js sets its default heap size from the available memory; on older versions set
--max-old-space-size. - Go 1.19+ honours
GOMEMLIMIT(set it a little below the container limit).
CPU: quotas and shares
--cpus 1.5 is implemented as a CFS quota: in every 100 ms period, the container may use 150 ms of CPU time spread across cores. If it uses that up early, it is throttled until the next period. That shows up as latency spikes, not crashes.
--cpu-shares works differently: it only matters when containers compete. Each gets CPU time in proportion to its shares, and an idle container's share is handed to the others.
PERIOD_US = 100_000
def quota(cpus):
return int(cpus * PERIOD_US)
for cpus in [0.5, 1, 1.5, 4]:
print(f"--cpus {cpus:<4} -> cpu.max = '{quota(cpus)} {PERIOD_US}' ({quota(cpus) / 1000:.0f} ms per 100 ms)")
def share(host_cpus, containers):
busy = {name: s for name, (s, wants) in containers.items() if wants}
total = sum(busy.values())
print(f"\n{host_cpus} CPUs, contended by {sorted(busy)}:")
for name, (shares, wants) in containers.items():
got = host_cpus * shares / total if wants else 0
print(f" {name:<8} shares={shares:<5} gets {got:.2f} CPUs")
share(4, {"api": (1024, True), "worker": (512, True), "batch": (512, True)})
share(4, {"api": (1024, True), "worker": (512, True), "batch": (512, False)})--cpus 0.5 -> cpu.max = '50000 100000' (50 ms per 100 ms)
--cpus 1 -> cpu.max = '100000 100000' (100 ms per 100 ms)
--cpus 1.5 -> cpu.max = '150000 100000' (150 ms per 100 ms)
--cpus 4 -> cpu.max = '400000 100000' (400 ms per 100 ms)
4 CPUs, contended by ['api', 'batch', 'worker']:
api shares=1024 gets 2.00 CPUs
worker shares=512 gets 1.00 CPUs
batch shares=512 gets 1.00 CPUs
4 CPUs, contended by ['api', 'worker']:
api shares=1024 gets 2.67 CPUs
worker shares=512 gets 1.33 CPUs
batch shares=512 gets 0.00 CPUs
When batch goes idle, its CPU time is redistributed in the same 2:1 ratio between api and worker. Shares are a fairness tool; --cpus is a hard ceiling.
Choosing limits
- Measure normal usage with
docker stats(or your monitoring) under realistic load. - Set the memory limit comfortably above the observed peak, say 1.5x. Too tight and you get random OOM kills; none at all and one leak can take down the host.
- Prefer a CPU limit only when you need predictability (shared hosts, noisy neighbours); throttling can hurt latency.
- Always set
--pids-limiton untrusted workloads.
Note: Docker Desktop's VM has its own CPU and memory limit (in Settings). Containers can never use more than the VM has, regardless of their own limits.
Test yourself
A container with --memory 256m exits with code 137 and OOMKilled: true. What happened?
- Docker stopped it after 256 minutes
- It exceeded its memory limit and the kernel's OOM killer killed it
- The image is corrupted
- It ran out of disk
What does --cpus 0.5 mean?
- The container may use one core at half clock speed
- The container may use 50 ms of CPU time per 100 ms period, across all cores
- It gets 50% of the shares
- It may only use core 0
Containers A (1024 shares) and B (512 shares) both want all the CPU on a 3-CPU host. How much does A get?
- 1.5 CPUs
- 2 CPUs
- 3 CPUs
- 1 CPU