Browse topics

Memory, CPU and process limits

Version
29
Review
Draft

Summary#

Containers have no resource limits by default. --memory caps memory, --cpus caps CPU time and --pids-limit caps the number of tasks. docker update can change limits on an existing Linux container.

Syntax#

sh
docker run --memory 512m --cpus 1.5 --pids-limit 200 IMAGE
docker run --memory 512m --memory-swap 512m IMAGE
docker update --memory 1g --memory-swap 1g CONTAINER
docker stats --no-stream CONTAINER

Example#

The example uses a local alpine:3 image. It reads files exposed by a Linux daemon host using cgroup v2.

sh
(
  set -eu
  name="dlr-docker-commands-limits-$$"
  trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT

  docker run --pull never --detach --name "$name" --cgroupns private \
    --memory 64m --memory-swap 64m --cpus 0.5 --pids-limit 32 \
    alpine:3 sleep 60 >/dev/null

  docker inspect --format \
    'memory={{.HostConfig.Memory}} nanocpus={{.HostConfig.NanoCpus}} pids={{.HostConfig.PidsLimit}}' \
    "$name"
  docker exec "$name" cat \
    /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max /sys/fs/cgroup/pids.max

  docker update --memory 128m --memory-swap 128m "$name" >/dev/null
  echo "after update:"
  docker exec "$name" cat /sys/fs/cgroup/memory.max
)

Expected output#

Text
memory=67108864 nanocpus=500000000 pids=32
67108864
50000 100000
32
after update:
134217728

Common mistakes#

--memory-swap sets the combined memory and swap limit when --memory is also set. If --memory-swap is unset, a container with --memory 512m may use another 512 MiB of swap when the host provides it. Set both to the same value to prevent swap use.

Version applicability#

Checked with Docker Engine 29 on cgroup v2. Some limits depend on kernel support, which docker info warns about. On Docker Desktop, containers are also bounded by the resources of its Linux VM.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0