Production-grade guide to agent sandboxing covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Sandboxing
Agent sandboxing confines AI agent execution to an isolated environment so that untrusted code, dynamic prompts, or tool use cannot compromise the host process or access privileged resources. It matters whenever agents receive dynamic inputs, invoke code execution, interact with external systems, or operate in multi-tenant settings. Without sandboxing, a single malicious or buggy agent can read secrets, exfiltrate data, or corrupt shared state.
The most immediate step is to ensure the agent process starts inside a confined namespace rather than directly on the host. The docker run command exposes a set of well‑documented flags that enforce isolation without requiring a custom SDK.
docker run \
--rm \
--security-opt apparmor=default \
--cap-drop ALL \
--read-only \
--tmpfs /tmp:rw,noexec \
--network none \
--memory 512m \
--cpus 1 \
my-agent-image:latest
--security-opt apparmor=default loads the default AppArmor profile, preventing the agent from opening most file paths outside /tmp, /proc, /sys, and its own home directory.--cap-drop ALL removes all Linux capabilities from the process. The agent starts with no extra privileges and must explicitly request any it needs.--read-only mounts the root filesystem as read‑only. Any write attempt fails immediately unless a --tmpfs or --volume bind is added.--tmpfs /tmp:rw,noexec provides a small, volatile writable area. The noexec flag prevents binaries placed in /tmp from executing, a common sandbox escape vector.--network none disables all network interfaces. If the agent needs outbound access, a user‑defined bridge with restricted egress can be attached later.--memory 512m and --cpus 1 impose cgroup limits that the kernel enforces. The agent cannot exceed these bounds regardless of the code it runs.If the image includes an entrypoint script that starts the agent, the same flags apply. The agent process (PID 1 inside the container) inherits the sandbox configuration.
Beyond the read‑only root, you can bind‑mount only the paths the agent legitimately needs:
docker run \
--rm \
--read-only \
--tmpfs /tmp:rw,noexec \
--volume /path/on/host:/agent/data:ro \
my-agent-image
The :ro suffix on the bind‑mount keeps the agent’s data directory immutable. Writes are rejected unless a second writable mount is provided, and even then, the --tmpfs area remains the safest place for temporary files.
When network access is required, prefer a user‑defined bridge with egress filtering over the default docker0. Attach the container with --network my-bridge and use iptables or nftables to allow only the outbound ports the agent actually needs. Never run an agent with --network host unless you are certain the agent’s codebase cannot be compromised.
Resource limits prevent a poorly behaved agent from consuming all host CPU, memory, or I/O throughput.
docker run \
--rm \
--memory 512m \
--memory-swap -1 \
--cpus 1 \
my-agent-image
--memory 512m caps RSS and swap usage at 512 MiB. The kernel OOM‑kills the container if it exceeds the limit.--memory-swap -1 disables swap entirely, ensuring the agent cannot defer memory pressure to swap space.--cpus 1 limits the container to one full CPU core (or a fraction, e.g., --cpus 0.5 for half a core). The kernel schedules the container’s threads against the specified quota.If the agent attempts a CPU‑intensive loop or a memory‑leaking pattern, Docker logs an event and the kernel terminates the process. The exit code is 137 (SIGKILL) when the OOM killer acts.
docker run \
--rm \
--pids-limit 256 \
--ulimit nofile=1024:2048 \
my-agent-image
--pids-limit 256 restricts the number of PIDs the container can create. This caps fork bombs and prevents the agent from spawning unbounded subprocesses.--ulimit nofile=1024:2048 sets the open‑file descriptor limit. The soft limit (1024) can be raised up to the hard limit (2048) by the process, but no further.These constraints are enforced by the kernel’s cgroup subsystem and are visible via docker stats or cgroup-stats.
When a sandboxed agent misbehaves, you need visibility into its state without breaking isolation.
docker ps -a --filter name=my-agent
docker inspect my-agent-container --format '{{.State.Status}} {{.State.ExitCode}}'
The --filter name= selects the container by a predictable naming scheme (e.g., created via --name my-agent). The inspect command returns the full JSON state, including OOM kill reasons, restart counts, and the cgroup configuration that was active at runtime.
docker logs my-agent-container 2>&1
Stdout and stderr from the agent are captured in the container’s journal. If the agent writes to a file inside /tmp (the only writable area), those writes appear in the log stream as well.
For deeper tracing, attach strace at container creation time:
docker run \
--rm \
--security-opt apparmor=default \
--cap-add SYS_PTRACE \
-it my-agent-image strace -f -e trace=execve,openat,write java -jar agent.jar
The --cap-add SYS_PTRACE flag grants the tracing capability, but it is generally avoided in high‑security sandboxes because it bypasses some permission checks. Use it only in development or debugging contexts.
Agents sometimes detect the confined environment and attempt to escape. Typical patterns include:
/tmp and invoking it with sh /tmp/payload. The noexec flag on --tmpfs prevents this.mount --bind or ioctl to remount the root filesystem as read‑write. AppArmor and seccomp profiles block most mount syscalls for unprivileged processes.--security-opt seccomp=unconfined only when necessary.When an escape is attempted, Docker logs an event such as Error: mount denied by AppArmor profile or Operation not permitted. These messages appear in docker logs and in the daemon’s journal (journalctl -u docker).
Granting --cap-add NET_ADMIN or --cap-add SYS_PTRACE to an agent container opens significant attack surface. If the agent code parses or crafts network packets, it can manipulate host networking state. If the agent uses ptrace on host processes, it can read arbitrary memory.
A frequent confusion is between --cap-drop ALL and --cap-add ALL. The former removes every capability; the latter adds them all. Omitting --cap-drop ALL leaves the container with a default set of capabilities (typically 8–10 on a standard Docker daemon), which may include NET_RAW, SETUID, and FSETID. Always pair --cap-drop ALL with explicit --cap-add entries only for the minimum required operations (e.g., --cap-add NET_BIND_SERVICE if the agent must bind to a port below 1024).
--read-only with bind‑mounts that have rbind propagation. If a volume is mounted with rbind and the propagation type is private, writes to the host path may not be reflected inside the container, and vice‑versa. The container appears to have a read‑only view, but the host path may have been modified by another process, leading to inconsistent state.--cpuset-cpus. Specifying --cpuset-cpus 0-3 without --cpus can result in the container receiving less than the intended share, or the kernel rounding the set to a single CPU, silently throttling the agent.openat or write will cause the container to fail on startup with Error: failed to create container: Cannot allocate memory or a generic permission denied, even though the host has ample resources. The error text offers no clue that the profile is the cause unless you inspect the container’s logs with --log-level debug.--tmpfs vs. --volume with tmpfs type. Both create in‑memory filesystems, but --tmpfs is automatically cleaned when the container stops, while a tmpfs‑type volume persists in the Docker daemon’s state until explicitly removed. Using a named volume with driver: tmpfs can lead to leftover data if the container is deleted without docker volume rm.--network none vs. --isolate-own-namespace. --network none removes all interfaces, including loopback. Some agents that rely on 127.0.0.1 for internal communication (e.g., health checks or local servers) will bind failures. --isolate-own-namespace (a containerd‑level flag) creates a new network namespace but retains the loopback interface; it is not exposed through the docker CLI and requires a containerd configuration change.In one observed case, an agent container was deployed with --read-only and --tmpfs /tmp:rw,noexec. The agent’s runtime attempted to extract a compressed archive into /tmp/agent-cache and then chmod +x the extracted binary. The chmod succeeded (the process owns the file), but execution failed with Exec format error because noexec prevented the kernel from loading the binary. The team added --tmpfs /tmp:rw,exec and the issue resolved. The lesson: noexec is a safety net, but if the agent’s workflow requires running binaries, the flag must be balanced against the threat model.
Another production incident involved an agent that hit the --pids-limit 256 ceiling during a recursive tree‑search algorithm. The container was OOM‑killed not because of memory, but because the PID allocator refused new forks, and the kernel’s oom killer targeted the main process. The fix was to increase the limit to 4096 and profile the agent’s fork rate, demonstrating that PID limits, like memory limits, should be set from observed workload patterns rather than arbitrary values.
--network none, --cap-drop ALL), filesystem hardening (--read-only, --tmpfs), and resource cgroups (--memory, --cpus, --pids-limit) each address a distinct risk vector.This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy