6.3.4.1 Container Memory Limits
A focused guide to Container Memory Limits, connecting core concepts with practical Docker and container operations.
Container memory limits constrain the maximum amount of memory a container's processes are allowed to use, with the container's main process being forcibly killed if it attempts to exceed this limit, providing a hard boundary that prevents one container from exhausting the host's available memory.
Setting a Memory Limit
The --memory flag specifies the maximum memory a container can use.
docker run -d --memory=512m myapp:1.0
If this container's processes collectively attempt to use more than 512MB, the kernel's out-of-memory killer terminates the offending process within the container.
Setting a Soft Memory Reservation
A memory reservation provides a softer, lower target the container is encouraged to stay within under memory pressure, without strictly enforcing it the way the hard limit does.
docker run -d --memory=1g --memory-reservation=768m myapp:1.0
Under contention for memory among multiple containers, the host favors reclaiming memory from containers exceeding their reservation, while the hard --memory limit remains the absolute ceiling.
Recognizing a Memory Limit Violation
A container killed for exceeding its memory limit typically exits with a recognizable status code, distinguishing this specific cause from other kinds of failures.
docker inspect myapp --format '{{.State.ExitCode}} {{.State.OOMKilled}}'
OOMKilled reporting true directly confirms the container was killed specifically due to exceeding its memory limit.
Choosing an Appropriate Memory Limit
A memory limit set too low causes the application to be killed and restarted repeatedly under entirely normal operating conditions; one set too high provides little actual protection against a genuine memory issue — measuring actual typical usage helps inform a sensible value.
docker stats myapp
Why Container Memory Limits Matter
A correctly sized memory limit protects the host and other containers from a single misbehaving or leaking application consuming unbounded memory, while still allowing the application enough headroom to operate normally under its actual, typical memory needs.