Sub topic 10
Read-only root filesystems and resource limits
This chapter assumes you can already run containers with docker run, read a Dockerfile, and use basic Linux commands. You should know that a container is a process on the host kernel, as covered in the chapters on the threat model and isolation primitives. You should also have seen cgroups described as the kernel feature that meters resource use.
Two runtime controls limit the damage after an attacker gets code running inside a container. A read-only root filesystem stops the attacker from changing the container's files. Resource limits stop one container from starving the host and its neighbors.
Why make the root filesystem read-only
A container's filesystem is a stack of read-only image layers with a thin writable layer on top. By default, any process in the container can write anywhere in that top layer. An attacker who gets code execution can use this to:
- Drop a second-stage tool, such as a reverse shell, a miner, or a scanner.
- Overwrite application files or scripts so the change survives until the container is replaced.
- Edit configuration files, such as
/etc/passwdor shell startup files, to maintain access.
Most applications don't need to write to their own code or system directories. The --read-only flag mounts the container's root filesystem read-only, so any write outside a mount you chose fails with Read-only file system.
This does not make the container safe. The attacker can still run code that is already in the image, and can still use memory and any writable mounts. It makes the attack harder and noisier, and it forces you to list exactly where the application writes.
Giving the application the writable space it needs
Real applications still need some scratch space. You provide it through explicit mounts instead of leaving the whole filesystem open.
| Mount type | Flag | Lives in | Survives container removal | Typical use |
|---|---|---|---|---|
| tmpfs | `--tmpfs /tmp` | Host RAM | No | Temp files, sockets, PID files |
| Named volume | `-v appdata:/var/lib/app` | Docker-managed host directory | Yes | Databases, uploads |
| Read-only bind mount | `-v ./conf:/etc/app:ro` | Host directory | Yes (host files) | Configuration |
The tmpfs option string matters. Set the options explicitly so you don't depend on defaults:
docker run -d --name web \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,nodev,size=64m \
myapp:1.0noexecstops anything in/tmpfrom being executed directly. This blocks the common "download and run" step.nosuidignores setuid bits.nodevignores device files.size=64mcaps how much RAM the mount can use.
Some software legitimately executes files from its temp directory, such as certain JIT compilers and native module loaders. If you hit an error caused by noexec, give that program a dedicated tmpfs path instead of dropping noexec everywhere.
Finding out what your application writes
Don't guess which paths need to be writable. Run the container normally first, exercise it, then ask Docker what changed in the writable layer:
docker run -d --name probe myapp:1.0
# ...use the application for a while...
docker diff probedocker diff prints one line per path: A for added, C for changed, D for deleted. Paths such as /tmp/... or /var/cache/app are candidates for tmpfs. Paths holding real data belong on a volume. Then restart with --read-only and check the logs for Read-only file system errors. Common culprits are web servers writing PID files and caches (nginx writes under /var/cache/nginx and /var/run), and runtimes writing under $HOME.
You can see the behavior directly with a throwaway container:
docker run --rm --read-only --tmpfs /tmp alpine:3.20 \
sh -c 'touch /tmp/ok && echo "tmp write ok"; touch /etc/blocked'The first write succeeds. The second prints touch: /etc/blocked: Read-only file system.
Why resource limits matter
By default a container can use as much CPU, memory, and process slots as the host will give it. This is a security problem as well as a stability problem. A compromised or buggy container can exhaust host memory and trigger the kernel's OOM killer against unrelated processes. It can also run a fork bomb that fills the process table, or pin every CPU core and starve its neighbors. These are denial-of-service attacks that need no special privileges. Docker enforces limits through cgroups, so a limit applies to the container's whole process tree.
Memory
docker run -d --memory 256m --memory-swap 256m --memory-reservation 128m myapp:1.0--memoryis a hard cap. If the container exceeds it, the kernel kills a process in it.--memory-swapis the combined memory plus swap limit. Setting it equal to--memorygives the container no swap. Without it, Docker lets the container use swap up to the same amount as the memory limit (when the host has swap enabled), which hides memory pressure and slows the host.--memory-reservationis a soft limit that the kernel enforces only when the host is under memory pressure.
Test the hard limit and see the result:
docker run --rm --memory 64m --memory-swap 64m python:3.12-alpine \
python -c "x = b'a' * (200 * 1024 * 1024); print('allocated')"
echo "exit code: $?"The process is killed and the exit code is 137 (128 plus signal 9). For a named container, confirm the cause with:
docker inspect --format '{{.State.OOMKilled}}' webCPU
--cpus 0.5limits the container to half of one CPU's worth of time, enforced as a quota per scheduling period. The container is throttled, not killed.--cpu-shares 512sets a relative weight (the default is 1024). It matters only when CPUs are contended, so it is not a cap.--cpuset-cpus 0,1pins the container to specific cores.
Process count and file descriptors
docker run -d --pids-limit 100 --ulimit nofile=1024:2048 myapp:1.0--pids-limit stops fork bombs by capping the number of processes and threads. Set it above what the application legitimately needs, since threads count. --ulimit nofile caps open file descriptors (soft limit and hard limit).
The combined run command
This is the full hardened command from the earlier chapters, with each flag's role labeled:
docker run -d --name web \
--user 10001:10001 \
--cap-drop ALL \
--security-opt no-new-privileges \
--read-only --tmpfs /tmp \
--memory 256m --cpus 0.5 --pids-limit 100 \
myapp:1.0The same settings in Docker Compose:
services:
web:
image: myapp:1.0
user: "10001:10001"
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
mem_limit: 256m
cpus: 0.5
pids_limit: 100Check that Docker applied the limits instead of assuming it did:
docker inspect --format 'ro={{.HostConfig.ReadonlyRootfs}} mem={{.HostConfig.Memory}} pids={{.HostConfig.PidsLimit}}' web
docker stats --no-stream webdocker stats shows live memory use against the limit, which helps you pick values from measurement instead of guesses.
Edge cases and common errors
- tmpfs counts against memory. Files in a tmpfs live in RAM and are charged to the container's memory cgroup. A 64 MB tmpfs filled to the top uses 64 MB of your
--memorybudget. Size tmpfs mounts with this in mind. - Limits that are too tight cause restarts. If a container is killed with exit code 137 and
OOMKilledistrue, raise the limit or fix the leak. Measure peak use under realistic load before setting it. - Runtimes may not respect the limit by default. Current JVMs detect container limits, but you may still need to set heap size (for example
-XX:MaxRAMPercentage=75). Node.js often needs--max-old-space-sizeset below the container limit. If the runtime thinks it has the whole host's memory, the kernel kills it before it garbage-collects. - Disk is not limited by default.
--read-onlyhelps here, because a read-only root plus a size-capped tmpfs bounds writes. Volumes are not capped. Unbounded container logs can also fill the disk, so set log rotation, for example--log-opt max-size=10m --log-opt max-file=3with the defaultjson-filedriver. - Read-only is not enough on its own. Writable volumes, a mounted Docker socket, or a
--privilegedcontainer can bypass what the read-only root protects. Combine it with the non-root user and capability controls from earlier chapters. - Don't remount as a workaround. If the application fails, find the specific path and give it a tmpfs or volume. Removing
--read-onlyto make an error disappear removes the protection.
Exercises
Exercise
A container started with --read-only fails at startup with "Read-only file system" when writing /var/run/app.pid. What is the safest fix, and why not remove --read-only?
Show answer
Add a tmpfs mount for the directory that needs writes, for example --tmpfs /var/run:rw,noexec,nosuid,nodev,size=1m. This gives the application the one writable location it needs, held in memory and discarded on stop. Removing --read-only would reopen the whole root filesystem to an attacker, so use targeted writable mounts instead.
Exercise
You run a container with --memory 128m and it exits with code 137. Name two commands or checks you would use to confirm the cause, and two ways to respond.
Show answer
Run docker inspect --format '{{.State.OOMKilled}}' <name> to see whether the kernel OOM-killed it, and watch docker stats <name> under load to see peak memory use. Respond by raising the limit to fit measured peak use, or by fixing the leak or lowering the runtime's own heap size (for example the JVM or Node.js heap setting) so it stays below the container limit.
Exercise
Why should you set --memory-swap equal to --memory for a hardened container, and what does --pids-limit protect against?
Show answer
Setting them equal gives the container no swap, so it cannot hide memory growth by swapping and slowing the host. The limit is then enforced as a clear OOM kill. --pids-limit caps the number of processes and threads in the container, which stops fork bombs from exhausting the host's process table.