Sub topic 6
Limiting CPU, memory, and process count
This chapter assumes you can use Docker from the command line, know what a Linux process is, and have read the earlier chapters on container hardening. A coding agent runs commands you did not write. A runaway test loop, a fork bomb, or a build that eats all memory can freeze the host. Resource limits make that failure local to the sandbox.
What the limits protect
Containers share the host kernel. Without limits, a container can use as much CPU, memory, and process slots as the host will give it. Docker enforces limits through cgroups (control groups), a kernel feature that caps resource use per group of processes.
| Resource | Docker flag | What happens at the limit |
|---|---|---|
| Memory | `--memory 2g` | The kernel kills a process in the container (OOM kill) |
| CPU | `--cpus 2` | The container is throttled and runs slower |
| Process count | `--pids-limit 256` | New `fork` calls fail with an error |
Applying the limits
This is the hardened command from the previous chapter, with the resource flags in focus:
docker run --rm -it \
--memory 2g \
--memory-swap 2g \
--cpus 2 \
--pids-limit 256 \
--ulimit nofile=1024:1024 \
python:3.12-slim bashEach flag does a specific job:
--memory 2gcaps RAM. Setting--memory-swapto the same value disables swap for the container. Without it, the container may use swap on top of the memory limit and slow the whole host.--cpus 2allows the equivalent of two CPU cores. The container can spread this across more cores, but total use stays at two cores.--pids-limit 256caps the number of processes and threads. This stops a fork bomb, a program that copies itself until the system has no process slots left.--ulimit nofile=1024:1024caps open file descriptors, so a leaking program cannot exhaust them.
Choosing values
Start from what a normal task needs and add headroom. A Python test suite may need 1 GB and one core. A compiler or a JavaScript build can need 4 GB and many processes. If limits are too tight, the agent sees confusing failures such as Killed or Resource temporarily unavailable, and may waste time trying to fix them. Measure first with docker stats.
docker stats --no-streamSeeing a limit work
Run this in a container started with --pids-limit 20. It tries to start 100 sleeping processes.
import subprocess
procs = []
try:
for i in range(100):
procs.append(subprocess.Popen(["sleep", "30"]))
except OSError as err:
print(f"Stopped after {len(procs)} processes: {err}")
finally:
for p in procs:
p.kill()The loop stops with an error well before 100, and the host is unaffected.
Common errors
- Setting
--memorywithout--memory-swap. The container can then use swap and degrade the host. - Forgetting a time limit. CPU and memory caps do not stop an infinite loop that uses little of either. Pair them with the
timeoutargument in your wrapper, as insubprocess.run(..., timeout=60). - Expecting disk limits. These flags do not cap disk writes. A writable mount can still be filled, so use a read-only root filesystem, a size-limited
--tmpfs /tmp:size=256m, and a small project mount. - Assuming limits stop attacks. They stop accidents and denial of service. They do not prevent data theft or kernel exploits.
Exercise
An agent runs a build inside a container started with --memory 1g and no --memory-swap. The build slows the whole host badly but is not killed. What is the likely cause and the fix?
Show answer
Without --memory-swap, the container can use swap in addition to its 1 GB of RAM, so it keeps running while the host swaps heavily. Set --memory-swap 1g (equal to --memory) to disable swap for the container, so the kernel kills the build at the limit instead.
Exercise
Which flag stops a fork bomb, and what does the failing process see?
Show answer
--pids-limit. Once the container reaches the limit, new fork or thread-creation calls fail with an error such as "Resource temporarily unavailable". The host keeps its process slots.