Every coding agent you have used this year — Claude Code, Codex, OpenWorker, the dozen others — does the same thing when it gets to work: it runs shell commands. It installs packages, edits files, runs tests, and sometimes runs a command you did not expect and would not have approved. When that agent lives in a Docker container, the usual reassurance is "it is sandboxed." That reassurance is doing a lot of work it cannot support.

A container shares the host kernel. It gets its own filesystem view, its own process tree, and its own network — but the kernel underneath is yours, and the container runs as root by default. Docker's own documentation says so plainly: "The default user within a container is root (uid = 0)." A root process in a container that also holds a handful of Linux capabilities — Docker grants 14 by default, including the ability to change file ownership, bypass permission checks, and bind privileged ports — is one misconfiguration away from the host. Mount the Docker socket into that container, as a hundred tutorials tell you to do so the agent can "manage its own containers," and there is no "away" left at all: the socket is the daemon's API, and the daemon is root.

This tutorial is the fix, end to end. You will see the problem with your own eyes, apply a hardened run command and test every control in it, bake the same controls into an image and a Compose file so you never have to remember the flags, then add the two bigger layers — rootless mode and gVisor — for code you genuinely do not trust. A final audit step scores your setup against the CIS Docker Benchmark so you can see what is left.

What you'll need#

  • Docker 24 or newer. Check with docker --version. This tutorial was verified against Docker 29.1.3. Docker Desktop on macOS or Windows works for steps 1–5 and 9; steps 6 and 7 need Linux.
  • A terminal and about 40 minutes. Steps 1–5 take 15 minutes; rootless mode and gVisor take the rest.
  • A test image. The steps use alpine:3.21 and python:3.13-alpine — small, official, and pinned by tag or digest wherever it matters.
  • No cloud account, no API key, no subscription. Everything runs on your machine.

One note on scope: this tutorial hardens the container and the daemon around it. It does not cover image scanning, supply-chain signing, or Kubernetes policy — those are separate jobs, and each deserves its own tutorial. What it does cover is the layer most agent setups get wrong first: the container the agent actually runs in.

1. See the problem#

Before changing anything, look at what a default container actually is. Run a plain container and ask who you are inside it:

docker run --rm alpine:3.21 id
uid=0(root) gid=0(root) groups=0(root)

Root. Not a service account, not a sandbox user — root, with the default capability set Docker grants every container. Now check what that root can do to the filesystem it was given:

docker run --rm alpine:3.21 sh -c 'touch /pwned && echo "wrote to the root filesystem"'
wrote to the root filesystem

The container's root filesystem is writable, and anything the agent runs can write anywhere in it — including dropping a binary into /usr/local/bin that the next command in the same container will happily execute. That is the default. Now the dangerous one. A common pattern in agent setups is mounting the Docker socket so the agent can build and run things itself:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock alpine:3.21 \
  sh -c 'apk add --no-cache curl >/dev/null 2>&1; curl -s --unix-socket /var/run/docker.sock http://localhost/version'

If that prints the daemon's version JSON, the container is not sandboxed at all: it is talking to the Docker daemon as a client, with no authentication, and the daemon runs as root on your host. From there it is one API call to start a new container with --privileged and a mount of your entire home directory. That is not a theoretical chain — it is the standard "docker socket escape," and it works because the socket is designed to be a root-equivalent API. The rule for the rest of this tutorial is absolute: never mount /var/run/docker.sock into a container your agent can write to. If an agent tool demands the socket, that tool runs outside the agent's container, on the host, behind its own authentication — or it does not run.

The second thing to internalize: escapes are not hypothetical anymore. The November research on Docker Model Runner showed a container with no extra capabilities, flags, mounts, or privileges reaching the host through an internal service — and Anthropic's Siren evaluation measured agents escaping weak sandboxes in 20–33% of trials. Your agent does not need to be malicious to escape. It needs to be curious, or confused, or given a prompt that tells it to be.

Layered diagram: an AI agent above a container, a controls layer with a shield and a forbidden sign, and the host below
AI-generated illustration for AI Frontier Post.

2. The hardened run command#

Here is the whole lockdown in one command. Run your agent's container like this from now on, and adapt the values to the task:

docker run --rm -it \
  --user 1000:1000 \
  --cap-drop=ALL \
  --security-opt=no-new-privileges:true \
  --read-only --tmpfs /tmp \
  --pids-limit 128 \
  --memory=512m --memory-swap=512m \
  --cpus=1.0 \
  --network none \
  -v "$PWD/workspace:/workspace:ro" \
  -w /workspace \
  alpine:3.21 sh

Every flag earns its place. Here is what each one does, and what breaks without it:

FlagWhat it doesWhat it stops
--user 1000:1000Runs the container's first process as uid 1000 instead of rootEverything that assumes container root: package installs to system paths, overwriting binaries, reading root-owned files
--cap-drop=ALLRemoves all 14 default Linux capabilitiesMounting filesystems, raw sockets, changing ownership, killing host processes, binding privileged ports
--security-opt=no-new-privileges:trueBlocks setuid binaries from gaining privileges inside the containerA setuid helper or a binary the agent downloads escalating back to root
--read-only --tmpfs /tmpMounts the root filesystem read-only; gives the container one writable scratch directoryPersistence: malware or a careless agent writing itself into the image's system paths
--pids-limit 128Caps the container at 128 processesFork bombs and runaway agent loops eating the host's process table
--memory=512m --memory-swap=512mHard-caps RAM at 512 MB with no swap headroomA memory-hungry agent or a leak starving the host
--cpus=1.0Limits the container to one CPUA runaway build or a crypto miner saturating the machine
--network noneRemoves networking entirelyExfiltration, downloading payloads, and reaching internal services — use a named network instead when the task needs the internet
-v …:/workspace:roMounts your project read-onlyThe agent rewriting your repo outside its scratch area (give it a separate writable mount for its output)

Three judgment calls in that command deserve a word. First, --network none is the strictest option and the right default for local work — an agent editing code and running tests does not need the internet. When it does (installing packages, calling an API), replace it with a named network you control, and keep the container off the default bridge where it can see your other containers by name. Second, the workspace is mounted read-only here on purpose: the agent's scratch work goes to /tmp (the tmpfs) or to a second, writable mount you add deliberately for output. That split — read-only inputs, one writable output directory — is the single most useful habit in this tutorial. Third, --cap-drop=ALL will break exactly one legitimate thing some agents do: binding to a port below 1024. If your agent serves something, serve it on a high port (8000, not 80) and map it on the host — do not add capabilities back to fix a port number.

Verify the daemon recorded every control before you trust it. Create the container, inspect it, then delete it:

docker create --name check --read-only --tmpfs /tmp --cap-drop=ALL \
  --security-opt=no-new-privileges:true --user 1000:1000 \
  --pids-limit 128 --memory=512m --network none alpine:3.21 id
docker inspect --format 'User={{.Config.User}} RO={{.HostConfig.ReadonlyRootfs}} Caps={{.HostConfig.CapDrop}} SecOpt={{.HostConfig.SecurityOpt}} Net={{.HostConfig.NetworkMode}}' check
docker rm check
User=1000:1000 RO=true Caps=[ALL] SecOpt=[no-new-privileges:true] Net=none

If any field comes back empty or wrong, the flag was misspelled or dropped — fix it before the agent runs, not after. This create-and-inspect check is worth making a habit: it is the fastest way to catch a flag that silently did nothing.

3. Prove each control bites#

A control you have never seen fail is a hope, not a control. Run each of these against the hardened command and confirm the failure. If any of them succeeds, something in your setup is not what you think it is.

Read-only filesystem. The agent cannot write to system paths, but its scratch directory still works:

docker run --rm --read-only --tmpfs /tmp alpine:3.21 sh -c 'touch /etc/evil; echo "exit=$?"; touch /tmp/ok && echo "tmpfs write OK"'
touch: /etc/evil: Read-only file system
exit=1
tmpfs write OK

Dropped capabilities. Mounting — the classic first step of an escape — is refused:

docker run --rm --cap-drop=ALL alpine:3.21 sh -c 'mount -t tmpfs tmpfs /mnt; echo "exit=$?"'
mount: permission denied (are you root?)
exit=1

Non-root user. The process inside is unprivileged, and it stays that way:

docker run --rm --user 1000:1000 alpine:3.21 id
uid=1000 gid=1000 groups=1000

No network. Nothing leaves the container:

docker run --rm --network none alpine:3.21 sh -c 'ping -c1 -W2 8.8.8.8; echo "exit=$?"'
ping: bad address '8.8.8.8'
exit=1

Process and memory limits. A fork bomb stalls at the process cap instead of taking the host with it, and a process that grabs more memory than its allowance is killed by the kernel's out-of-memory killer:

docker run --rm --pids-limit 32 alpine:3.21 sh -c 'i=0; while [ $i -lt 200 ]; do sleep 60 & i=$((i+1)); done; echo "spawned $i sleepers"'
sh: can't fork: Resource temporarily unavailable
spawned 32 sleepers
docker run --rm --memory=64m python:3.13-alpine python3 -c "b = bytearray(200*1024*1024)"
Killed

The 200 MB allocation against a 64 MB limit ends with the process killed, not with your laptop swapping to a halt. Keep these five probes somewhere — a shell script in your dotfiles, a note in the repo — and run them whenever you change the flags. They are your regression test for the sandbox.

4. Bake it into a Dockerfile#

Flags typed by hand get forgotten. Put the same decisions into the image, so every container built from it starts hardened. This is a minimal agent-workspace image: Python, one pinned dependency, and a tiny health-checked server that stands in for whatever your agent actually runs.

# syntax=docker/dockerfile:1
FROM python:3.13-alpine@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
# 1. Create the non-root user FIRST so every layer after this is owned correctly
RUN adduser -D -u 1000 appuser
WORKDIR /workspace
# 2. Dependencies before code, so rebuilds stay cached
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
# 3. Code in last, owned by the app user (never root-owned files in the image)
COPY --chown=appuser:appuser server.py ./
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget -q -O /dev/null http://127.0.0.1:8000/health || exit 1
CMD ["python", "server.py"]

Three things in that file do the heavy lifting. The base image is pinned by digest, not just by tag — a tag can be re-pointed, a digest cannot, so the image you audited is the image you build. The user is created before anything is copied, and the code is copied with --chown, so no file in the image is owned by root; an agent that finds a writable root-owned file and uses it to escalate has nothing to find. And USER appuser is the last word: even if someone runs this image with no flags at all, the process inside is unprivileged.

The supporting files are small. requirements.txt pins the one dependency:

httpx==0.28.1

And server.py is a standard-library HTTP server with a health endpoint, so the HEALTHCHECK has something real to probe:

"""Minimal agent-workspace stub: serves a health endpoint on :8000."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/health":
            body = json.dumps({"status": "ok"}).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()
    def log_message(self, *args):
        pass

if __name__ == "__main__":
    HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()

Build it and confirm what got baked in:

docker build -t agent-workspace:1.0 .
docker image inspect agent-workspace:1.0 --format 'User={{.Config.User}} Healthcheck={{.Config.Healthcheck.Test}}'
User=1000:1000 Healthcheck=[CMD-SHELL wget -q -O /dev/null http://127.0.0.1:8000/health || exit 1]

Two Dockerfile rules to carry with you. First, never put a secret in the image: no API key in an ENV line, no token copied in with the code. Pass secrets at runtime with --env-file or your orchestrator's secret store, and scope them to the one container that needs them. Second, keep the image small and boring: a minimal base, pinned versions, no package manager cache left behind (--no-cache-dir), no shell tools the agent does not need. Every binary in the image is a tool an escaped process can pick up.

5. The same lockdown in Compose#

If you run your agent with Compose, the flags from step 2 translate one-to-one into service options. Save this as docker-compose.yml next to the Dockerfile:

services:
  agent:
    build: .
    image: agent-workspace:1.0
    read_only: true
    tmpfs:
      - /tmp
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    user: "1000:1000"
    pids_limit: 128
    mem_limit: 512m
    cpus: 1.0
    networks:
      - agent-net
    volumes:
      - ./workspace:/workspace:ro
    ports:
      - "127.0.0.1:8000:8000"
networks:
  agent-net:
    driver: bridge

Three details matter here. The port is bound to 127.0.0.1 only — never publish an agent's port on all interfaces, or anyone on your network can reach it. The workspace volume is read-only, matching the split from step 2. And the container gets its own named network instead of the default bridge, so it cannot resolve your other containers by name. Validate the file before you run it — Compose resolves every option and reports mistakes without starting anything:

docker compose config
services:
  agent:
    cap_drop:
      - ALL
    cpus: 1
    mem_limit: "536870912"
    pids_limit: 128
    read_only: true
    security_opt:
      - no-new-privileges:true
    tmpfs:
      - /tmp
    user: 1000:1000
    ...

Then start it, confirm the health endpoint answers, and confirm the health check reports healthy:

docker compose up -d --build
curl -s http://127.0.0.1:8000/health
docker compose ps
{"status": "ok"}

From here on, this Compose file is the agent's sandbox definition. When you want to give the agent something new — network access, a writable output directory, a second capability — you add it here, deliberately, with a comment saying why. The file is the audit trail.

6. Go rootless#

Everything so far hardens the container. Rootless mode hardens the daemon: it runs the Docker daemon and all its containers as your own user, inside a user namespace, so a daemon vulnerability or a container escape lands in an unprivileged account instead of root. Docker documents it as the mitigation for exactly the class of bugs this tutorial is about. It is Linux-only, and it is worth the 10 minutes.

First, the prerequisites. You need the uidmap package (it provides newuidmap and newgidmap), and your user needs at least 65,536 subordinate UIDs and GIDs:

sudo apt-get install -y uidmap
grep "^$(whoami):" /etc/subuid /etc/subgid
testuser:231072:65536

If that grep comes back empty, add the range yourself — 65,536 IDs starting somewhere unused:

echo "$(whoami):100000:65536" | sudo tee -a /etc/subuid /etc/subgid

If the rootful daemon is running, stop it first — you cannot run both daemons on the same socket:

sudo systemctl disable --now docker.service docker.socket
sudo rm /var/run/docker.sock

Then install the rootless daemon. If you installed Docker from the DEB or RPM packages, the setup script is already on your machine:

dockerd-rootless-setuptool.sh install
[INFO] Creating /home/testuser/.config/systemd/user/docker.service
[INFO] Installed docker.service successfully.
[INFO] To control docker.service, run: `systemctl --user (start|stop|restart) docker.service`
[INFO] To run docker.service on system startup, run: `sudo loginctl enable-linger testuser`
[INFO] Creating CLI context "rootless"
[INFO] Using CLI context "rootless"
[INFO] Make sure the following environment variable(s) are set (or add them to ~/.bashrc):
[INFO] export DOCKER_HOST=unix:///run/user/1000/docker.sock

If the script is not present, install the extras package (sudo apt-get install -y docker-ce-rootless-extras) or use the standalone installer (curl -fsSL https://get.docker.com/rootless | sh). Confirm you are talking to the rootless daemon:

export DOCKER_HOST=unix:///run/user/1000/docker.sock
docker info --format '{{.SecurityOptions}}'
[seccomp Profile: builtin rootless cgroupns]

The word rootless in that list is the confirmation. From here, every command in this tutorial works the same — the flags, the Dockerfile, the Compose file — but the daemon behind them is unprivileged. Two things to know before you commit: a few features need the rootful daemon, so check the known-limitations section of the rootless docs against your workflow before switching, and anything that used to reach the daemon at /var/run/docker.sock now needs the new DOCKER_HOST (or the rootless CLI context the installer created for you). Your agent's containers do not get a choice in the matter: they run rootless whether they like it or not.

7. gVisor for code you don't trust#

Steps 1–6 assume the agent is yours and mostly well-behaved. Sometimes it is not: you are running code a model wrote that you have not read, executing an untrusted repository, or letting an agent install packages from the open internet. For that, add a second kernel. gVisor is a userspace kernel (the "Sentry") that sits between the container and your host kernel and intercepts every system call. An escape now has to break the Sentry first — a much smaller, purpose-built attack surface than the full Linux kernel. It needs Linux 5.6 or newer, on x86_64 or ARM64.

Install it from the release tarball. Download the latest release, verify the checksum, and register the runtime with Docker:

(
  set -e
  ARCH=$(uname -m)
  URL=https://storage.googleapis.com/gvisor/releases/release/latest/${ARCH}
  wget ${URL}/gvisor.tar.zstd ${URL}/gvisor.tar.zstd.sha512
  sha512sum -c gvisor.tar.zstd.sha512
  sudo tar --zstd -xf gvisor.tar.zstd -C /usr/local/bin
  rm -f gvisor.tar.zstd gvisor.tar.zstd.sha512
)
sudo /usr/local/bin/runsc install
sudo systemctl reload docker

That last pair of commands is what does the work: runsc install writes the runtime into Docker's daemon config (/etc/docker/daemon.json gains a runtimes entry pointing at /usr/local/bin/runsc), and reloading the daemon picks it up. Confirm the runtime is registered, then run a container under it:

docker run --rm --runtime=runsc hello-world

From here, add --runtime=runsc to the hardened command from step 2 whenever the workload is untrusted — or set it as the default runtime in daemon.json for a machine that only runs agents. The cost is performance: every system call takes a trip through the Sentry, so syscall-heavy work (compiling, heavy I/O) runs noticeably slower. That is the trade, stated plainly: use the normal runtime for your own code, gVisor for code you have not vetted. Read the production guide on gvisor.dev before running it for anything that matters.

Nested boxes labeled Host, Daemon, and Container with a magnifying glass and a checklist beside them
AI-generated illustration for AI Frontier Post.

8. Audit yourself with Docker Bench#

You have applied the controls; now score them. Docker Bench for Security is Docker's own script that checks your host and containers against the CIS Docker Benchmark (v1.6.0) — dozens of automated checks, each with a pass, warn, or note and a remediation. Clone it, build it, and run it with the command from its README:

git clone https://github.com/docker/docker-bench-security.git
cd docker-bench-security
docker build --no-cache -t docker-bench-security .
docker run --rm --net host --pid host --userns host --cap-add audit_control \
  -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
  -v /etc:/etc:ro \
  -v /usr/bin/containerd:/usr/bin/containerd:ro \
  -v /usr/bin/runc:/usr/bin/runc:ro \
  -v /usr/lib/systemd:/usr/lib/systemd:ro \
  -v /var/lib:/var/lib:ro \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  --label docker_bench_security \
  docker-bench-security

Read that command before you run it: the audit container is deliberately given enormous privilege — host network and PID namespaces, the host filesystem, and the Docker socket — because parts of the benchmark inspect the host itself. That is the one place in this tutorial where the socket mount is acceptable: a trusted, read-only audit you run yourself, once, and then delete. Do not leave the bench image lying around with that command in your shell history next to agent credentials.

The output groups checks by section: host configuration, daemon configuration, daemon files, container images, container runtime, and Docker security operations. Expect warns on a normal workstation — the benchmark is written for production servers, and some checks (audit rules, separate partitions, live-restore settings) are judgment calls on a laptop. What you are looking for is the container-runtime section after you apply this tutorial: no privileged containers, no containers with the socket mounted, health checks present, no excessive capabilities, read-only root filesystems. Fix the warns that apply to you, note the ones that do not, and re-run the bench after any change to the setup. You can also run a single section — sh docker-bench-security.sh -c container_runtime — when you only changed container settings.

9. Lock down Docker Desktop and Model Runner#

If you run Docker Desktop on macOS or Windows, one November finding deserves its own step. Docker Model Runner — the feature that serves local models inside Docker Desktop, enabled by default since version 4.46.0 — exposed an unauthenticated API reachable from any container on the machine, at model-runner.docker.internal. Its /engines/_configure endpoint accepted runtime flags that were appended straight onto the command line of the llama-server process running on the host. A container with no extra capabilities, flags, mounts, or privileges could inject a flag that made the host process write files — including overwriting the Docker Desktop VM's data disk — and under non-default configurations the researchers chained that write through Docker Extensions to code execution on the host. The flaw is CVE-2026-28400 (ZDI-26-150), rated CVSS 7.5, reported in November 2025 and analyzed in full by the Zero Day Initiative on November 18, 2026. The same research found two companion escapes: a macOS sandbox misconfiguration (ZDI-26-451, CVSS 8.8) and a WSL2 boundary issue on Windows (ZDI-26-258, CVSS 8.2). There is no reported exploitation in the wild; it was coordinated disclosure.

Do three things. First, update Docker Desktop to 4.61.0 or newer: the fix (Model Runner v1.0.16) puts runtime flags behind a strict allowlist with path validation and removes the --trust-remote-code flag that could have let a remote model escape the container. Second, if you do not use Model Runner, turn it off — in Docker Desktop, Settings → AI → Model Runner. A service you do not run cannot be abused. Third, if your plan includes it, turn on Enhanced Container Isolation: it blocks containers from reaching Model Runner at all. Then verify you are on the fixed version:

docker version --format 'Desktop {{.Server.Version}}'

The general lesson is the one this whole tutorial is built on: the dangerous services are the helpful ones you did not know were listening. Model Runner was unauthenticated because it was "internal." Internal to a machine that runs arbitrary containers is not internal at all. Whenever you install a new Docker feature, extension, or agent tool, ask what it listens on and who can reach it — then check with docker ps and your own eyes.

Which approach should you use?#

SituationUseWhy
Your own coding agent on your own machine, editing your own codeHardened flags (steps 2–5)Cheap, fast, and closes the escapes that matter for a trusted agent. This is the default — start here.
Agents run all day on a shared machine or a serverFlags + rootless mode (step 6)The daemon itself stops being root, so a daemon bug or a container escape lands in an unprivileged account.
Running code the model wrote that you have not read, or a repo you do not trustFlags + gVisor (step 7)A second kernel between the container and your host. Slower, but the right price for untrusted code.
Maximum isolation, or agents that handle real secretsA microVM per agentReal hardware virtualization (see the OpenShell and smolvm tutorials in Related articles). Heavier, and the strongest boundary Docker-era tooling offers.
You just want to know where you standDocker Bench (step 8)Run it, fix the container-runtime warns, and re-run it after every change.

The honest limits: no container setup is a guarantee. Kernel bugs exist, gVisor has had its own vulnerabilities, and a determined attacker with a zero-day can cross layers that stop ordinary accidents and curious agents. What this tutorial buys you is the realistic outcome: the agent that misreads a prompt, the dependency that phones home, and the known escape from November all stop at a wall instead of walking onto your host. Stack the layers, audit with the bench, and keep the flags in a file instead of in your head.

The takeaway#

Run your agent as uid 1000, with no capabilities, a read-only filesystem, no new privileges, no network it does not need, and hard limits on processes, memory, and CPU — and never give it the Docker socket. Put those decisions in a Dockerfile and a Compose file so they survive your memory. Add rootless mode when the machine is shared, gVisor when the code is untrusted, and the bench when you want proof. The container was never a security boundary on its own; with these layers, it does not have to be.