Docker · Containers in practice

How do you apply CPU and memory limits to containers?

Hardresource limitscgroupsoomUpdated Oct 2026
Quiz this track

Short answer

Use --memory, --cpus and --pids-limit to constrain a container through cgroups. Set limits from measured usage, and make sure the runtime inside the container is aware of the limit.

Without limits, one container can consume host resources and degrade its neighbours. With limits, the kernel enforces a ceiling. Memory over the limit triggers the OOM killer, which usually kills the main process and leaves exit code 137.

sh
docker run -d --memory=512m --memory-swap=512m --cpus=1.5 --pids-limit=256 api:1.0.0
docker stats --no-stream
docker inspect -f "{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}" api-1
Setting memory-swap equal to memory disables swap for the container, making the limit predictable.

What to consider

  • CPU limits are enforced as a quota over a period, which can cause throttling
  • Memory limits include page cache and can be exceeded by a burst of file I/O
  • A pids limit protects the host from fork bombs
  • The JVM, Node and Go runtimes need to see the cgroup limit to size heaps correctly
  • Requests and limits mean different things in Kubernetes

Set limits from observed usage plus headroom, not from a guess. Too low a memory limit produces OOM kills under load; too low a CPU quota produces latency spikes from throttling even when the host is idle.

A container with no memory limit can be killed by the host OOM killer anyway. Explicit limits make the failure mode predictable and keep one service from taking down its neighbours.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What does exit code 137 usually mean?
  2. 2Why can CPU limits cause latency even on an idle host?
  3. 3What is the difference between a request and a limit in Kubernetes?
  4. 4Why does a JVM need to be told about the container memory limit?

Say it in the interview

I set memory, CPU and pids limits through cgroups based on measured usage plus headroom. Memory overage leads to an OOM kill, so I also make sure runtimes like the JVM or Node see the cgroup limit and size their heaps accordingly. CPU quotas can throttle a container even on an idle host, so I watch throttling metrics rather than only average utilization.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.