Docker Tutorial · Production Practices · Lesson 23 of 26
Memory and CPU Limits
Limit memory and CPU so one container can't starve the host, and recognise out-of-memory kills.
Limits
--memory 256msets a hard memory limit; exceeding it gets the process OOMKilled (exit code 137).--cpus 1.5limits CPU time to 1.5 cores' worth; exceeding it throttles rather than kills.--pids-limit 200stops fork bombs.
Applications must know their limits: runtimes that size heaps or worker counts from the host's memory or CPU count can exceed a container's limit. Modern JVMs, Node and Go read cgroup limits; check yours.
trap 'docker rm -f rc-oom > /dev/null 2>&1' EXIT
docker run --name rc-oom --memory 64m --memory-swap 64m alpine:3.24 sh -c 'echo allocating...; tail /dev/zero' > /dev/null 2>&1 || true
docker inspect rc-oom --format 'exit code {{.State.ExitCode}}, OOMKilled={{.State.OOMKilled}}'
echo "memory limit seen inside: $(docker run --rm --memory 64m alpine:3.24 cat /sys/fs/cgroup/memory.max) bytes"
echo "cpu quota seen inside: $(docker run --rm --cpus 1.5 alpine:3.24 cat /sys/fs/cgroup/cpu.max)"
Output
exit code 137, OOMKilled=true memory limit seen inside: 67108864 bytes cpu quota seen inside: 150000 100000
Run this on your computer — see “Get Started” for setup.
See Resource constraints.
Test yourself
A container exceeds its --cpus limit. What happens?
It is killedIt is throttled (slowed down), not killedDocker restarts itThe host crashes
Show answer
Answer: It is throttled (slowed down), not killed
CPU is compressible; memory isn't, which is why memory overuse ends in OOM kills.