Resource limits for memory, CPU and PIDs

Intermediate · 5 min

Containers have no limits by default. How --memory, --cpus, --cpu-shares and --pids-limit map to cgroups, what an OOM kill looks like, and CPU throttling.

Before thisdocker run and the container lifecycleInspecting containers: inspect, top, stats and events

Datadog · 5 min

Resource limits for memory, CPU and PIDs

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DatadogReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • By default a container may use all of the host's memory, CPU and process slots. One leaking or runaway container can starve every other one.
  • `--memory` sets the cgroup's hard memory limit. Exceeding it triggers the OOM killer inside the container, which shows up as exit code 137 and `OOMKilled: true` in docker inspect.
  • `--memory-swap` is memory plus swap combined. Set it equal to `--memory` to forbid swap. Left unset, the container may use as much swap as memory.
  • `--cpus=1.5` is a hard quota, 150 ms of CPU time per 100 ms period. A busy multi-threaded process can use it up early in the period and get throttled, which shows as latency.
  • `--cpu-shares` is a relative weight that only matters under contention. On cgroup v2 it is converted to `cpu.weight`, where 1024 shares become 100.
  • `--pids-limit` caps processes and threads. Without it, a fork bomb or thread leak can exhaust the host's PID space.
  • Runtimes must see the limit. Modern JVMs and Go 1.25+ read cgroup limits; for others, size heaps and worker counts to the container, not the host.

No limits by default

Start a container with no flags and it may use every byte of the host’s memory, every core, and as many processes as the kernel allows. Usually that’s fine, until one container leaks memory and the kernel’s OOM killer starts picking victims across the whole host, or a batch job pins every core while your web service waits.

Every container already runs in its own cgroup, as the Linux lesson on cgroups v2 explains. Docker’s limit flags just write values into that cgroup. Think of the cgroup as a separate electricity meter for each tenant, and the limits as the breaker on each meter: one tenant’s faulty heater trips their own breaker, not the whole building’s.

Memory

docker run -d --name api --memory 512m --memory-swap 512m registry.example.com/api:1.4.2

--memory (-m) becomes the cgroup’s memory.max, a hard limit. When the processes in the container can’t get below it, the kernel’s OOM killer kills one of them, usually the main process, and the container exits:

docker inspect --format '{{.State.ExitCode}} {{.State.OOMKilled}}' api
# 137 true

137 is 128 plus signal 9, SIGKILL. OOMKilled: true tells you it was the memory limit rather than someone running docker kill. That line is from Docker’s documentation, not a live run here.

Swap is the subtle part. --memory-swap is the total of memory and swap. The resource constraints page lists the cases:

--memory --memory-swap Result
300m unset 300 MB memory plus up to 300 MB swap
300m 300m no swap
300m 1g 300 MB memory plus 700 MB swap
300m -1 unlimited swap

On cgroup v2 the value has to be split, because v2 limits swap separately. runc’s conversion, in the opencontainers/cgroups library, writes memory.swap.max as memory-swap minus memory. A container that swaps is slow in ways that are hard to diagnose, so for latency-sensitive services set them equal.

Two more flags. --memory-reservation is a soft floor the kernel tries to protect under memory pressure, not a limit. --oom-kill-disable stops the OOM killer for the container, and the docs warn to use it only together with --memory: without a limit, a leaking container then pushes the OOM killer onto the host’s other processes.

Memory counted against the limit includes page cache the container causes, which the kernel reclaims before killing anything. A container reading large files can sit close to its limit without being in danger.

CPU

Two different mechanisms, often confused.

--cpus is a hard quota. --cpus=1.5 writes 150000 100000 to cpu.max: at most 150 ms of CPU time in every 100 ms period, across all its threads. It applies even when the host is idle.

--cpu-shares is a relative weight, used only when containers compete. The default is 1024. On cgroup v2 there are no shares, so runc converts the number to cpu.weight (1 to 10000, default 100). The current opencontainers/cgroups library does this with a curve fitted so the defaults line up. I ran its formula in Python:

--cpu-shares cpu.weight
256 35
512 59
1024 100
2048 174
4096 303

Older runc versions used a straight line that turned the default 1024 into 39, so a container with default shares ranked below a plain systemd service. If you read old advice about shares misbehaving on cgroup v2, that is why.

Throttling

The quota is shared by every thread. A Java or Go service with 16 threads on a big host can burn a 200 ms quota (--cpus=2) in the first 12.5 ms of a period, then sit frozen for the remaining 87.5 ms. Average CPU looks low, and tail latency is terrible. The evidence is in the container’s cpu.stat: nr_throttled and throttled_usec climbing. The fixes are to give it more quota, reduce its thread count, or use shares or --cpuset-cpus (pinning to specific cores) instead of a quota.

PIDs

docker run --pids-limit 200 ...

writes pids.max, a cap on processes and threads. Docker sets none by default. A fork bomb, or a bug that leaks threads, inside one container can otherwise exhaust the host’s PID space and stop anything, including sshd, from starting a process. Set it generously, a few hundred for most services, and you lose nothing.

Setting and changing limits

In Compose, either the container-level keys or the deploy block, which docker compose also applies:

services:
  api:
    image: registry.example.com/api:1.4.2
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: "1.5"
          pids: 200
        reservations:
          memory: 256M

On a running container, docker update --memory 1g --memory-swap 1g --cpus 2 api changes limits without a restart. docker stats shows usage against them, covered in monitoring containers.

Make the runtime agree

A limit the runtime doesn’t know about produces confusing failures. A JVM that sizes its heap from host memory gets OOM-killed instead of throwing OutOfMemoryError. Modern JVMs read cgroup limits by default, and since Go 1.25 the default GOMAXPROCS follows the container’s CPU limit. For Node.js, Python worker pools and anything else, set heap sizes and worker counts from the container’s limits explicitly. And tools like free and top inside a container report the host’s totals, which the docs warn about for swap in particular.

About the video

The embed is all of Datadog’s “Container Security Fundamentals - cgroups”, November 2023, 5 minutes 8 seconds. The description says it hardens Docker containers by using cgroups to restrict the resources given to them. It has no chapters, so I judged it from that description and the series it belongs to. It frames limits as a security control against denial of service, which complements this lesson’s operational view. It doesn’t cover swap semantics, the shares conversion or throttling. YouTube reports no audio language, so English was judged from the channel and English captions. Krish Dinesh’s video in deeper goes deep on CPU quotas and throttling, and WittCode’s short one on memory limits and swap.

What was run: runc’s share-to-weight and swap conversion functions were read from the opencontainers/cgroups source and the weight formula evaluated in Python, together with the older linear formula. Moby’s daemon reference was checked for a default PIDs limit (there is none). No containers were run, since no daemon was available. Flag semantics are from Docker’s resource constraints page, checked 2026-11-28.

Where this fits

Limits stop a container from hurting others. When one is misbehaving inside its limits, you need to get in and look: debugging a running container.

Check yourself

  1. 01A container exits with code 137 and nobody ran docker stop. What do you check first?

    docker inspect --format '{{.State.OOMKilled}}' on it. 137 is 128 + 9, a SIGKILL; if OOMKilled is true, the container hit its memory limit and the kernel's OOM killer ended it.

  2. 02You set --memory 512m and nothing else on a host with swap. How much memory plus swap can the container use?

    Up to 1 GB in total: 512 MB of memory plus as much swap again, because --memory-swap unset means swap equal to the memory limit. Set --memory-swap 512m to forbid swap.

  3. 03A service with --cpus=2 on a 16-core host shows 30% average CPU but slow p99 latency. What might be happening?

    CPU throttling. Its many threads use the 200 ms quota early in each 100 ms period and then wait for the next period. Check nr_throttled and throttled_usec in the container's cpu.stat.

  4. 04Two containers have --cpu-shares 512 and 1024 on an otherwise idle host. Does the first get half as much CPU?

    Not while the host is idle. Shares only apply under contention; with spare CPU either container can use all it needs.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark