2.3.2.2 Cgroup Memory Limits
A focused guide to Cgroup Memory Limits, connecting core concepts with practical Docker and container operations.
Cgroup memory limits cap how much physical and swap memory a container's processes can use, with the kernel intervening directly — typically by terminating a process — when that limit is exceeded, rather than allowing the container to consume memory needed by the rest of the system.
Setting a Hard Memory Ceiling
A memory limit defines the maximum amount of memory a container's processes can collectively use, enforced continuously by the kernel for the entire time the container runs.
docker run -d --memory=512m --name myapp myapp:1.0
If the processes inside this container collectively attempt to use more than 512 megabytes, the kernel intervenes rather than allowing the limit to be exceeded.
What Happens When the Limit Is Exceeded
When a container hits its memory limit, the kernel's out-of-memory killer typically selects a process within that container's cgroup to terminate, which usually results in the container's main process being killed and the container exiting.
docker run --memory=64m --rm alpine sh -c "yes | tr \\\n x | head -c 200000000 > /dev/null"
docker inspect myapp --format '{{.State.OOMKilled}}'
If the container was terminated due to exceeding its memory limit, this inspection reports true, distinguishing an out-of-memory termination from other kinds of failure.
Swap Memory Limits
A separate, related setting controls how much swap space a container can use in addition to physical memory, which can be set independently to prevent a container from relying heavily on swap, which is typically much slower than physical memory.
docker run --memory=512m --memory-swap=512m myapp:1.0
Setting the swap limit equal to the memory limit effectively disables additional swap usage beyond the physical memory limit itself.
Choosing Appropriate Memory Limits
Setting a memory limit too low causes a healthy application to be killed unexpectedly under normal load; setting it far higher than needed wastes capacity that could be allocated to other containers — observing actual usage under realistic load is the most reliable way to choose an appropriate value.
docker stats myapp --no-stream
Why Memory Limits Matter
Memory limits are one of the most consequential resource controls to configure correctly, since exceeding them results in the container being terminated outright, rather than merely slowing down as can happen with CPU contention.