Sub topic 4
Running an Agent in a Hardened Container
This chapter assumes you know basic Docker usage (images, containers, volumes), Linux users and file permissions, and what an LLM-based coding agent does. It covers the default settings a container needs to change before you can trust it as a boundary for an agent that runs shell commands.
Why defaults are not enough
A default docker run container is isolated from the host by namespaces and cgroups. It still has a writable root filesystem, runs as root inside the container unless the image says otherwise, keeps a set of Linux capabilities, has full outbound network access, and has no limit on memory or process count.
An agent that runs shell commands will eventually run something you did not intend. The cause may be a model mistake, a malicious instruction hidden in a file it read, or a dependency install script. Hardening reduces what that command can do. Each flag below removes one capability the agent rarely needs.
The hardened command
docker run --rm -it \
--user 1000:1000 \
--read-only \
--tmpfs /tmp \
--cap-drop=ALL \
--security-opt no-new-privileges \
--pids-limit 256 \
--memory 2g \
--cpus 2 \
--network none \
-v "$PWD":/workspace \
-w /workspace \
python:3.12-slim bashThis starts a shell in a container as an unprivileged user. Only the current project directory is writable. The container has no network.
What each flag does
| Flag | Effect | What it prevents |
|---|---|---|
| `--rm` | Deletes the container on exit | Leftover state between runs |
| `--user 1000:1000` | Runs as a non-root UID and GID | Root-owned file writes and root-only operations inside the container |
| `--read-only` | Mounts the root filesystem read-only | Modifying installed tools or system files |
| `--tmpfs /tmp` | Provides a writable in-memory `/tmp` | Programs failing because they cannot write temp files |
| `--cap-drop=ALL` | Removes all Linux capabilities | Operations such as changing file ownership, binding low ports, or raw network access |
| `--security-opt no-new-privileges` | Blocks privilege gain through setuid binaries | A process becoming more privileged than its parent |
| `--pids-limit 256` | Caps the number of processes | Fork bombs |
| `--memory 2g` | Caps memory | A runaway process starving the host |
| `--cpus 2` | Caps CPU time | A busy loop consuming all cores |
| `--network none` | Removes all network interfaces except loopback | Data exfiltration and downloading payloads |
| `-v "$PWD":/workspace` | Mounts the project | Nothing. This is the one deliberate hole |
Running as a non-root user
Running as UID 1000 means that if a process escapes into a file or kernel interface, it does so without root privileges. It also affects the mounted project. Files the agent creates in /workspace are owned by UID 1000 on the host. If your host user has a different UID, the agent may fail to write, or you may end up with files you cannot edit. Check with id -u and pass your own values, for example --user "$(id -u):$(id -g)".
Read-only root and tmpfs
With --read-only, any write outside the mounted volumes and tmpfs mounts fails. This stops the agent from altering installed binaries or libraries. It also breaks tools that write to their home directory, such as pip caches or shell history. Give those tools a writable location explicitly.
docker run --rm -it \
--read-only \
--tmpfs /tmp \
--tmpfs /home/agent:uid=1000,gid=1000 \
--env HOME=/home/agent \
--user 1000:1000 \
python:3.12-slim bashA tmpfs lives in memory and disappears when the container stops. It also counts against the memory limit, so a very large tmpfs can trigger an out-of-memory kill. You can bound it with --tmpfs /tmp:size=256m.
Capabilities and no-new-privileges
Linux splits root's powers into capabilities, such as CHOWN or NET_RAW. Docker grants a default subset. --cap-drop=ALL removes them all. If a specific tool fails, add back only the one it needs with --cap-add, and note why.
no-new-privileges sets a kernel flag that stops execve from granting extra privileges, for example through a setuid binary such as sudo. Together with a non-root user, it closes the common route from a normal user to root inside the container.
Limits and network
--pids-limit, --memory, and --cpus use cgroups to bound resources. When a container exceeds its memory limit, the kernel kills a process in it. Your agent harness should treat exit code 137 as a likely out-of-memory or kill signal and report it.
--network none is the strictest option. A real agent often needs to install packages or call a model API, and no network blocks both. The network chapter covers controlled egress. For now, you can create an internal network where containers talk to each other but not to the outside:
docker network create --internal agent-net
docker run --rm -it --network agent-net python:3.12-slim bashThe same settings in Docker Compose
Compose is useful when the agent runs as a long-lived service next to other containers.
services:
agent:
image: python:3.12-slim
user: "1000:1000"
working_dir: /workspace
command: ["sleep", "infinity"]
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
pids_limit: 256
mem_limit: 2g
volumes:
- ./project:/workspace
networks:
- sandbox
networks:
sandbox:
internal: trueThe internal: true network has no route to the outside world. You then run commands with docker compose exec agent <command>.
Calling the sandbox from code
If your own program launches the container, avoid building a shell string from the agent's output. Pass an argument list so that quotes, semicolons, and $() in the command are not interpreted by a host shell. Set a timeout on the whole run.
import subprocess
from pathlib import Path
def run_in_sandbox(project_dir: str, command: list[str], timeout: int = 60) -> subprocess.CompletedProcess:
project = Path(project_dir).resolve()
docker_cmd = [
"docker", "run", "--rm",
"--user", "1000:1000",
"--read-only",
"--tmpfs", "/tmp",
"--cap-drop=ALL",
"--security-opt", "no-new-privileges",
"--pids-limit", "128",
"--memory", "1g",
"--network", "none",
"-v", f"{project}:/workspace",
"-w", "/workspace",
"python:3.12-slim",
*command,
]
return subprocess.run(docker_cmd, capture_output=True, text=True, timeout=timeout)
result = run_in_sandbox(".", ["python", "-c", "print('hello from the sandbox')"])
print(result.stdout)Two details matter here. First, Path(...).resolve() turns the path into an absolute path, which -v requires. Second, when subprocess.run hits the timeout, it kills the docker client process. The container may keep running. For stronger cleanup, give the container a name with --name and run docker rm -f <name> in a finally block.
Common errors
- Permission denied in
/workspace. The container user's UID does not match the owner of the host directory. Pass your own UID and GID. - Read-only file system. A tool wrote outside the mount. Find the path in the error message and add a tmpfs or a volume for it.
- Exit code 137. The process was killed, usually by the memory limit. Raise
--memoryonly after checking what used the memory. pip installorgit clonefails. With--network nonethis is expected. Install dependencies while building the image, not while the agent runs.- Operation not permitted. A tool needs a capability you dropped. Identify the one capability and add only that.
What this still does not give you
A hardened container still shares the host kernel. A kernel vulnerability can let code in the container reach the host, and no flag in this chapter changes that. The writable project mount is also fully exposed: the agent can delete or rewrite every file in it. Later chapters cover stronger boundaries such as gVisor and microVMs, and how to review changes safely.
Exercise
A container started with --read-only --user 1000:1000 --network none -v "$PWD":/workspace fails when the agent runs pip install requests with the error "Read-only file system". Name two separate reasons the install cannot succeed with these flags, and one change that lets the agent use requests safely.
Show answer
First, pip writes to the read-only root filesystem (site-packages and its cache), and an unprivileged user could not write system directories anyway. Second, --network none means pip cannot reach the package index. A safe fix is to install requests while building the image, so the dependency is already present and read-only at run time, and keep the network disabled.
Exercise
Why does the Python wrapper pass the command as a list instead of building one string, and why is a finally block with docker rm -f still useful after a timeout?
Show answer
A list is passed to the process directly with no host shell, so characters like ; or $() in the agent's command cannot run on the host. On timeout, subprocess.run kills only the docker client, so the container can keep running. Removing it by name in finally ensures the container stops.