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.

Create a free account to save this page, take notes and track your progress. Sign in

Limits

  • --memory 256m sets a hard memory limit; exceeding it gets the process OOMKilled (exit code 137).
  • --cpus 1.5 limits CPU time to 1.5 cores' worth; exceeding it throttles rather than kills.
  • --pids-limit 200 stops 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.

Hit a memory limit and read limits from inside
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.

Test yourself

A container exceeds its --cpus limit. What happens?

  1. It is killed
  2. It is throttled (slowed down), not killed
  3. Docker restarts it
  4. The 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.

Was this page helpful?