Vijendra Rana

Search

Search articles, series and snippets

Agent sandboxes - how they work and how to build your own

By · · 15 min read · AI Infra, Agents

#docker #firecracker #gvisor #ai-agents #security

Why AI agents need a box to run code in, how containers, gVisor and microVMs isolate them, what Docker Sandboxes, E2B, Daytona, Modal, Vercel and Cloudflare offer, and how to build a custom sandbox.

On this page

An agent that can only talk is safe and not very useful. The moment it can run npm install, execute the Python it just wrote, or open a browser, it becomes useful and dangerous at the same time. The code it runs was written by a model, shaped by whatever text it read along the way, and nobody reviewed it before it executed.

So agents get a box. A sandbox is a place where the agent can do real work, install packages, break things and try again, without touching your laptop, your production servers or your secrets.

This post explains how those boxes work inside, what is on the market today (including Docker’s new Sandboxes), and how to build one yourself.

Why an agent needs a box

Here is the loop every coding or data agent runs. The model decides on a tool call, the tool runs somewhere, and the result goes back into the context.

The agent loop. Everything in the dashed box runs code nobody reviewed.

Without a sandbox, “shell command” means your shell. Three things can go wrong:

  • Mistakes. The agent runs rm -rf on the wrong path, or upgrades a global package that breaks every other project.
  • Prompt injection. A README, issue or web page tells the agent to send ~/.aws/credentials somewhere. The model cannot reliably tell your instructions from instructions hidden in data.
  • Noisy neighbours. On a shared platform, one user’s agent should never see another user’s files, or eat all the CPU.

A good sandbox answers each one: a private filesystem for mistakes, locked-down network and secrets for injection, and hard isolation plus resource limits for neighbours.

How sandboxes work inside

Every sandbox answers one question: when code inside makes a system call, which kernel handles it? There are four common answers, from weakest to strongest.

1. OS-level sandbox (same kernel, fewer rights). The process runs directly on your machine, but the kernel restricts it. macOS Seatbelt profiles, Linux Landlock, seccomp and bubblewrap fall here. Local coding agents use this to keep writes inside the project folder and to block network access. It is cheap and instant, but the agent still talks to your real kernel.

2. Containers (same kernel, separate view). Namespaces give the process its own view of files, processes, users and network. Cgroups cap CPU and memory. It is still your host kernel underneath, so a kernel bug can be an escape route. Fine for trusted code, risky for untrusted code on shared hosts.

3. gVisor (a kernel in user space). gVisor puts a user-space kernel called the Sentry between the program and the host. The program’s system calls go to the Sentry, which implements Linux itself and only makes a small, filtered set of calls to the real kernel. Startup is close to a process start. Some syscall-heavy workloads run slower, and a few rare syscalls are not supported.

4. MicroVMs (a real kernel per sandbox). Firecracker, Cloud Hypervisor and similar tools boot a tiny virtual machine with its own Linux kernel, protected by hardware virtualization (KVM). The program can do anything to its own kernel and still sit behind the hypervisor. Firecracker boots in around 125 ms and adds only a few megabytes of overhead, and snapshots make resume even faster.

Where a system call goes in each model. Fewer shared layers means a smaller attack surface.

The parts around the box

Isolation is the headline, but a usable sandbox has five more pieces.

PieceWhat it doesTypical approach
ImageWhat is installed when the box startsAn OCI image or a template built from a Dockerfile
FilesystemWhere the agent’s work livesCopy-in, a mounted folder (virtiofs), or a clone of a repo
NetworkWhat the agent can reachDefault deny, plus an allowlist enforced by an egress proxy
SecretsHow the agent calls APIsA proxy injects the real token outside the box; the agent sees a placeholder
LifecycleStart, pause, resume, fork, destroyWarm pools, memory snapshots, and hard timeouts

The lifecycle part is what makes agent sandboxes different from normal VMs. Agents are bursty: they think for ten seconds, run a command for two, and think again. Platforms snapshot an idle sandbox and resume it later, sometimes with memory intact, and some can fork a running sandbox so an agent can try several approaches in parallel.

A typical sandbox lifecycle

Docker Sandboxes, up close

Docker’s answer is Docker Sandboxes, driven by a standalone CLI called sbx. The first preview ran agents in containers inside Docker Desktop. The current version gives each sandbox its own microVM, and it no longer needs Docker Desktop.

It is aimed at coding agents on your own machine. One command starts an agent in a box with your project:

sbx login
sbx run claude ~/my-project      # or: sbx run codex, sbx run gemini ...

What happens inside, based on Docker’s architecture docs:

  • A microVM per sandbox, each with its own kernel and its own Docker engine. The agent can build images and run docker compose without ever touching your host’s Docker socket. Sandboxes do not share images or layers with each other.
  • Your project is mounted, not copied. The folder is passed through with virtiofs at the same absolute path, so edits show up on both sides instantly. With --clone, your repo is mounted read-only and the agent works in a private clone.
  • All outbound traffic goes through a proxy on the host. By default every outbound TCP connection is blocked, UDP and ICMP included, until a policy allows the destination.
  • Credentials never enter the VM. You store secrets with sbx secret set. The agent sees a placeholder, and the host proxy swaps in the real token only on requests that policy allows.
  • Inside, the agent has sudo, package managers and Docker. That is the point: full freedom in the box, a hard wall around it.
Docker Sandboxes: freedom inside the microVM, policy at the edge

Day-to-day commands:

sbx ls                                   # list sandboxes
sbx exec -it my-sandbox bash             # shell into one
sbx run --publish 8080:3000 --name web claude   # expose a dev server
sbx policy allow network api.github.com  # open one host
sbx policy log                           # what was reached, what was blocked
sbx stop my-sandbox                      # stop, keep the VM
sbx rm my-sandbox                        # delete the VM and everything in it

To reuse a setup, save a sandbox as a template and start new ones from it:

sbx template save my-sandbox my-template:v1
sbx run -t my-template:v1 claude

For a reproducible setup in source control, Docker has kits: a YAML descriptor plus a Dockerfile that declare tools to install, files to add, startup hooks and the network rules and credential injection the kit needs. Kits can be combined, so a “Node + Postgres + GitHub” setup can be three small kits. The format is still moving, so check the kit authoring docs for the current syntax.

What else is on the market

Docker Sandboxes runs on your machine. Most other options are cloud APIs you call from your agent backend. They all follow the same pattern: create a sandbox, run commands or code, read files, destroy it. The differences are the isolation model, how long a sandbox can live, and how state is kept.

OptionIsolationWhere it runsGood fit
Docker Sandboxes (sbx)MicroVM per sandbox, private Docker engineYour laptop or workstationRunning Claude Code, Codex and others locally with full autonomy
E2BFirecracker microVMs, pause keeps memory and diskCloud, open source coreCode interpreters and short agent tasks; forking running sandboxes
DaytonaHardened containers by default, VMs optionalCloud, or self-hosted (AGPL)Long-lived dev workspaces, fast starts from snapshots
Modal SandboxesgVisorCloudTeams already on Modal; GPU work next to the sandbox
Vercel SandboxFirecracker microVMs, snapshot and restoreCloudRunning untrusted code from apps already on Vercel
Cloudflare Sandbox SDKContainers on Cloudflare Containers, driven from Workers and Durable ObjectsCloudflare’s edgeAgents built on Workers; state backed up to R2
Fly MachinesFirecracker microVMsCloudBuild-your-own platforms that want raw fast VMs
OS-level sandboxes (Seatbelt, Landlock, bubblewrap)Same kernel, restricted rightsYour machineLightweight guard rails for local agents, no VM needed

A few honest notes:

  • Cold start numbers are marketing. Vendors and third-party benchmarks report anything from under 100 ms to around a second, and they rarely measure the same thing. Test with your own image.
  • Session limits differ a lot. Some plans cap a sandbox at minutes, others at a day. Long-running agents need pause and resume, not one long session.
  • Pricing is usually per vCPU-second and GiB-second, so idle sandboxes cost money unless they are paused.
A rough way to pick

Building your own sandbox

Managed services are the right call for most teams. Building your own makes sense when data cannot leave your network, when you need a custom runtime, or when you run enough sandboxes that the bill justifies the work.

The shape is the same as every product above: an API that hands out sandboxes from a warm pool, an isolated runtime, a proxy at the network edge, and a reaper that cleans up.

The moving parts of a self-built sandbox service

Step 1: a hardened container with gVisor

The quickest real isolation is Docker plus gVisor. Install gVisor, register the runsc runtime, and every container you start with --runtime=runsc gets the user-space kernel instead of your host kernel.

# register gVisor with Docker (after installing runsc)
sudo runsc install
sudo systemctl restart docker

Then start each sandbox with nothing it does not need:

docker run -d --name sbx-42 \
  --runtime=runsc \
  --network none \
  --read-only --tmpfs /tmp --tmpfs /workspace:exec \
  --cpus 1 --memory 1g --pids-limit 256 \
  --cap-drop ALL --security-opt no-new-privileges \
  --user 1000:1000 \
  my-agent-image sleep infinity

Each flag closes a door: gVisor for the kernel, no network by default, a read-only root with scratch space only where the agent works, CPU, memory and process limits against runaway loops, and no Linux capabilities or root user.

Step 2: a small API around it

The agent backend should never run docker itself. Give it three calls: create, exec, destroy. A minimal version in TypeScript:

import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { randomUUID } from 'node:crypto'
 
const run = promisify(execFile)
const LIMIT_MS = 30_000
 
export async function createSandbox() {
  const id = `sbx-${randomUUID().slice(0, 8)}`
  await run('docker', [
    'run', '-d', '--name', id, '--runtime=runsc', '--network', 'none',
    '--read-only', '--tmpfs', '/tmp', '--tmpfs', '/workspace:exec',
    '--cpus', '1', '--memory', '1g', '--pids-limit', '256',
    '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '1000:1000',
    'my-agent-image', 'sleep', 'infinity',
  ])
  return id
}
 
export async function exec(id: string, command: string) {
  try {
    const { stdout, stderr } = await run(
      'docker', ['exec', '-w', '/workspace', id, 'sh', '-c', command],
      { timeout: LIMIT_MS, maxBuffer: 1024 * 1024 },
    )
    return { exitCode: 0, stdout, stderr }
  } catch (e: any) {
    return { exitCode: e.code ?? 1, stdout: e.stdout ?? '', stderr: e.stderr ?? String(e) }
  }
}
 
export async function destroySandbox(id: string) {
  await run('docker', ['rm', '-f', id])
}

Expose exec to the model as a tool, return the exit code and trimmed output as the observation, and always call destroySandbox in a finally block. Note that the command string only runs inside the box: execFile passes arguments without a host shell, so the model’s text never reaches your shell.

Step 3: controlled network access

--network none is safe but too strict: agents need package registries and a few APIs. Instead of opening the network, put the sandbox on an internal network whose only exit is a proxy you control:

  • Allow a short list of hosts, such as registry.npmjs.org, pypi.org and api.github.com. Deny everything else and log it.
  • Keep real tokens in the proxy. The sandbox sends a placeholder, and the proxy replaces it on requests to the right host. A prompt-injected agent can then only use a token where you already allowed it.
  • Block cloud metadata addresses such as 169.254.169.254 explicitly. That address hands out cloud credentials to anything that asks.

This is the same design Docker Sandboxes uses with its host proxy, and it is worth copying even if you change everything else.

Step 4: when you need microVMs

gVisor is a good default. Move to Firecracker when you need a real Linux kernel (kernel modules, unusual syscalls, Docker inside the sandbox) or a stronger boundary for hostile multi-tenant code. The usual path:

  • Build a root filesystem from your image and a small guest kernel.
  • Start VMs through Firecracker’s jailer, which wraps each VM process in its own chroot, cgroup and seccomp filter.
  • Keep a pool of booted VMs, or restore them from a snapshot, so the agent does not wait for a boot.
  • Use Kata Containers or firecracker-containerd if you want to keep OCI images and container tooling on top.

This is a real infrastructure project. If you get here, compare the cost against E2B or Vercel Sandbox, which run the same technology for you.

Step 5: the boring parts that matter

  • Hard limits everywhere. A wall-clock timeout per command and per sandbox, an output size cap, and a reaper that kills anything orphaned.
  • One sandbox per task, never shared between users. Reuse warm boxes only after a full reset.
  • Audit logs. Record every command, file write and network attempt. You will want them the first time an agent does something surprising.
  • Snapshots for long tasks. Pause idle sandboxes instead of keeping them running.

Wrapping up

The sandbox is what turns an agent from a chatbot into a worker you can trust with real tasks. The isolation choice (container, gVisor or microVM) sets how hard the walls are. The network proxy and credential handling decide what a hijacked agent can actually do. And the lifecycle features, warm pools, snapshots and forks, decide whether it feels fast.

For local coding agents, try Docker Sandboxes: sbx run claude in a project folder gives you the full stack in one command. For agents you ship to users, start with a managed API, and build your own only when your constraints or your bill make the case.

Further reading