How to Use E2B: The Beginner's Guide (First Sandbox, the Kill Lesson, Code Execution for Agents, and Custom Templates)
CodexFuse Team · 2026-11-01T16:11:17.574Z · 16 min read
Learn how to use E2B: get an API key, install the SDK, create your first sandbox, run code and commands safely, and kill sandboxes before they bill you.
Learning how to use E2B takes one evening, and by the end you will have AI-generated code running inside a disposable cloud machine instead of on your laptop. E2B is an AI code sandbox platform: you create an isolated sandbox with one line of code, run arbitrary Python or JavaScript inside it, and kill it when you are done. This e2b tutorial runs the complete beginner arc in one place: the mental-model lesson, the E2B API key setup, installing the right SDK, your first sandbox, code execution, shell commands, file transfers, runtime package installs, the kill lesson (which is really the billing lesson), timeouts and pause, custom templates, the E2B-vs-Daytona comparison, and running an AI agent inside a sandbox. If you have never worked with containers, start with our Docker beginner guide — E2B is not Docker, but the isolation mental model carries over. One naming note before anything else: this guide is about the E2B sandbox company at e2b.dev — not Google's Gemma "E2B" on-device AI model, and not the "2B" e-stim hardware kit that clutters the search results for this exact keyword.
What Is E2B, exactly?
E2B is a cloud platform that gives every AI agent its own isolated computer. That is the company's own positioning — "Every agent gets a machine" — and it is the answer to the oldest question in AI tooling: how to run LLM code safely. The founding problem E2B solves is the same problem every agent hits the moment it writes its first shell command — and it describes exactly what you are renting: a fresh virtual machine with its own filesystem and internet access, created in well under a second, where untrusted or AI-generated code can run without touching your laptop, your server, or your users' data. The founding use case was code interpreting: an LLM writes Python, E2B executes it, and the results come back as text, logs, charts, dataframes, or images. Today the company calls itself "The Enterprise AI Agent Cloud," and sandboxes run shell commands, full dev toolchains, and even headless coding agents.
Two facts anchor everything below. First, the old 2024-era CodeInterpreter API with notebook.exec_cell() — the one every ancient tutorial teaches — has been superseded by the Sandbox API: Sandbox.create() plus runCode(). Old snippets that start pip install e2b-code-interpreter==0.0.10 are museum pieces; the current quickstart was refreshed on 2026-10-30, and every command in this guide was verified against it. Second, sandboxes cost money while they are alive, so the most expensive skill in this guide is not creating a sandbox — it is killing one. Say that to yourself now, because the billing section will prove it.
How Do I Get an E2B API Key?
You get an API key by signing up at e2b.dev and generating one from the dashboard — it takes about two minutes. The key is the only credential between your code and billable compute, so treat it like a password: put it in an environment variable (E2B_API_KEY) or a .env file loaded with dotenv, and never hardcode it in your source code. Hardcoded keys end up in git history, in screenshots, and in pasted Stack Overflow questions, and a leaked E2B key lets anyone spin up sandboxes on your credit card.
The key authenticates the SDK, which reads E2B_API_KEY from your environment automatically. You will not need SSH keys, Docker credentials, or a cloud provider account — the sandbox fleet is entirely E2B's. If you keep your code in git, start with our GitHub beginner guide so the key never gets committed by accident.
Which SDK Do I Install — e2b or the Code Interpreter SDK?
Install the Code Interpreter SDK if you want to execute code; install the core e2b package only if you need shell commands and files. This is the one place where old guides mislead you: the current E2B quickstart (updated 2026-10-30) does not say npm i e2b — it says:
npm i @e2b/code-interpreter dotenv
The documentation states it plainly: "This guide uses the Code Interpreter SDK because the next step calls runCode()… If your project only needs shell commands and files, the core e2b package is enough." The E2B Code Interpreter SDK is the modern name of the product line that old 2024-era guides simply called the code interpreter — if you remember "E2B code interpreter" from those guides, this is where it lives now. Its sandbox also supports commands and files, so for a beginner the interpreter package is the right default. For Python, the current PyPI versions are e2b 2.58.0 (released 2026-10-20) and e2b-code-interpreter 2.11.5 (released 2026-10-26):
pip install e2b-code-interpreter
# or, for the core SDK only:
pip install e2b
Check the installed versions with pip show or npm list before you blame your code for an API mismatch — the SDK moved fast in 2026, and stale tutorials are the number-one source of broken snippets.
How Do I Create My First E2B Sandbox?
You create your first E2B sandbox with Sandbox.create() — a single call that provisions an isolated Debian-based machine in well under a second. The complete first-sandbox arc takes five steps, and you can run them from a plain Node.js or Python script on your laptop:
- Set your key. Export
E2B_API_KEY(or put it in.env). Never paste it into code. - Create the sandbox.
const sbx = await Sandbox.create()in JavaScript, orsbx = Sandbox.create()in Python. - Run code.
sbx.runCode('print("hello world")')in JavaScript, orsbx.run_code('print("hello world")')in Python. - Read the result. The call returns an
Executionobject —execution.textholds the output. - Kill the sandbox.
await sbx.kill()(JS) orsbx.kill()(Python). The kill lesson is the billing lesson: do this every single time.
The whole round trip — create, execute, kill — takes seconds. Notice what you did not do: no Docker image to pull, no VM to provision, no firewall rule to write, no cleanup of a local environment. That is the product in one paragraph.
How Does Code Execution Work in an E2B Sandbox?
Code execution in E2B works through the runCode() / run_code() methods on a sandbox object, and everything you need comes back on one Execution result object. The sandbox runs your code in an isolated process and returns execution.logs (with logs.stdout and logs.stderr), execution.text, execution.results (structured outputs — rendered charts, dataframes, HTML, and PNG images), and execution.error when your code raises. For long-running or streaming workloads, register callbacks — on_stdout, on_stderr, and on_result — so output streams to your terminal as it is produced instead of arriving in one lump at the end.
The same sandbox also runs shell commands, which is how you do everything code execution cannot. The call is:
await sandbox.commands.run('pip install cowsay')
Commands run on the sandbox's Debian system, so apt-get install works too. A mental model that saves debugging time: runCode is for code you want results back from; commands.run is for operating the machine. You will use both in every real agent workflow.
How Do I Upload and Download Files in E2B?
You move files in and out of an E2B sandbox with the files methods on the sandbox object — one file at a time. In JavaScript:
await sbx.files.write('/home/user/analysis.py', code)
const content = await sbx.files.read('/home/user/output.csv')
In Python, files.write() uploads a single file and files.write_files() uploads several at once. The one limitation to internalize early: whole-directory upload and download are not supported — you pass files individually. The standard workaround for a repo is to write a small loop over the file list, or to git clone the repository inside the sandbox with commands.run() and read back only the artifacts you need.
How Do I Install Packages Inside a Sandbox?
You install packages inside a sandbox with the same commands you would use on your own machine — pip install, npm install, or sudo apt-get install via commands.run() — because every E2B sandbox is Debian-based. The critical rule is that anything you install at runtime dies with the sandbox: "When you start a new sandbox instance, the packages are not available." If your agent needs cowsay every time, reinstalling it on every sandbox creation is slow and wasteful.
That is what custom templates are for. A template bakes packages, system dependencies, and configuration into a prebuilt sandbox image, so creation stays fast and your agent always starts from the same environment. Templates are the difference between a demo and a production agent pipeline — they get their own section below.
Why Is the Kill Lesson Really the Billing Lesson?
The kill lesson is the billing lesson because E2B charges per second for every running sandbox: the company's own pricing page says "We charge per second of a running sandbox," and a sandbox you forgot to kill bills you for every second it sits idle. The method is one line — sandbox.kill() — and the habit to build is calling it in a finally block, a context manager, or a cleanup handler so that no exception path can leave a sandbox alive. Current per-second rates on e2b.dev/pricing:
| CPU size | Cost per second | Cost of 1 idle hour |
|---|---|---|
| 1 vCPU | $0.000014 | ≈ $0.05 |
| 2 vCPU | $0.000028 | ≈ $0.10 |
| 4 vCPU | $0.000056 | ≈ $0.20 |
| 6 vCPU | $0.000084 | ≈ $0.30 |
| 8 vCPU | $0.000112 | ≈ $0.40 |
A forgotten 8-vCPU sandbox costs roughly forty cents an hour — invisible for a day, noticeable for a month, and entirely avoidable with one method call. This is why the topic entry for this guide puts the kill lesson in the title: for secure code execution with AI agents, the sandbox is the easy part; the discipline is terminating what you create.
How Long Can an E2B Sandbox Run?
An E2B sandbox can run for a maximum of 1 hour on the Hobby plan and 24 hours on the Pro plan, with the default timeout at 300 seconds. You control the window with the timeoutMs option on Sandbox.create() and can extend it at runtime with setTimeout() / set_timeout() — up to the plan's hard ceiling. Enterprise plans add multi-day sessions and persistent sessions.
What happens at the timeout is now first-class: you choose between "kill" (the sandbox is destroyed) and "pause" (the sandbox's memory and processes are frozen and can be resumed later). Pause is the persistence story E2B added in 2026 — pausing resets the runtime window, and paused state is kept indefinitely, which lets agents checkpoint long jobs instead of re-running them. If you are building anything that outlives a single HTTP request, design for pause rather than hoping you finish before the clock runs out.
How Do I Build a Custom E2B Template?
You build a custom E2B template with the CLI or the SDK: the template is a recipe that preinstalls packages and configuration into a reusable sandbox image. From the CLI it is e2b template init followed by e2b template build. From the SDK you compose a template in code:
const template = Template()
.fromTemplate("code-interpreter-v1")
.pipInstall(["cowsay"])
.npmInstall(["cowsay"])
await Template.build(template, "custom-packages", {
cpuCount: 2,
memoryMB: 2048,
onBuildLogs: defaultBuildLogger(),
})
Then every sandbox you create from it is ready immediately: Sandbox.create("custom-packages"). Current build limits (docs.e2b.dev/template/quickstart, updated 2026-10-30): builds can take up to 1 hour, get 8 vCPUs / 8 GiB RAM / 10 GiB disk on Hobby, and run 20 concurrently on Hobby and Pro plans. Name templates for what is inside them (agent-python-data, not template-3), version them by rebuilding rather than mutating in place, and test the exact creation call your agent will use — a template that builds fine but whose sandbox fails on first use is a template you discover is broken at 2 a.m.
E2B vs Daytona: Which Agent Sandbox Should I Choose?
E2B and Daytona solve the same problem — safe places to run AI-generated code — but with different isolation architectures, and the architecture is what decides the tradeoff. The honest one-page comparison, with third-party sources named because E2B's own pricing for Daytona was not verified for this guide:
| Dimension | E2B | Daytona |
|---|---|---|
| Isolation unit | Firecracker microVM per sandbox, each with its own kernel ("proprietary MicroVM runtime, built on Firecracker… dedicated kernels") | Defaults to containers sharing the host kernel (full VMs optional) |
| Startup | Sub-second; E2B's homepage claims "Full isolation. Container speed." (no official millisecond figure published currently) | Advertises <90ms container starts |
| Pause/resume | Paused sandboxes preserve memory and processes indefinitely (Pro) | VM snapshots/forks |
| Extras | Prebuilt agent templates (OpenCode, Pi), auto-pause, BYOC + E2B Embed self-hosting | GPU sandboxes, VM snapshots/forks |
| Openness | Runtime is Apache-2.0 open source | Core moved to a private codebase in June 2026 |
| Compliance | SOC 2 Type II + HIPAA | Not verified for this guide |
The draw-the-line rule: if your threat model needs kernel-level isolation for untrusted code — which is most agent workloads — E2B's microVM-per-sandbox is the stronger default. If you need GPU sandboxes today or sub-100ms container starts for interactive dev environments, Daytona's container-first design deserves a look. Sources: thedomin.com (2026-10-25) and the bex.co comparison (Oct 2026). Neither comparison was vendor-verified, and Daytona's current pricing was not opened for this guide — verify it on daytona.io before budgeting.
How Do I Run an AI Agent Inside E2B?
You run an AI agent inside E2B by creating a sandbox from one of E2B's prebuilt agent templates and launching the agent with a shell command — the sandbox becomes the agent's entire computer. This is the pattern people mean when they search for secure code execution AI agents: generated code running in a disposable microVM, never on your machine, killable with one call. The vendor docs (docs.e2b.dev/agents/opencode, updated 2026-10-22) give the OpenCode pattern:
// or from the CLI: e2b sbx create opencode
const sbx = await Sandbox.create("opencode", {
envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
})
await sbx.commands.run('opencode run "build me a todo app"')
The same docs family ships a pi template with the Pi coding agent (docs.e2b.dev/agents/pi, same date). This is the graduation arc of the whole guide: first you ran code in a sandbox, then you learned the agent-integration lane — an agent with its own machine, its own filesystem, and its own internet access, fully disposable, billed per second, killable with one call. That is secure code execution for AI agents in one sentence, and it is why E2B counts 100K+ teams, 94 of the Fortune 100 signed up, 2B+ sandboxes started, and 15M+ monthly SDK downloads on its homepage (crawled 2026-11-01).
What Does E2B Cost?
E2B costs nothing to start and scales by concurrency plus per-second compute — the three plans, verified on e2b.dev/pricing for this guide:
| Plan | Price | Concurrent sandboxes | Best for |
|---|---|---|---|
| Hobby | Free + $100 one-time usage credit | 20 | Learning, prototypes, one-agent experiments |
| Pro | $150/month + usage | 100 (expandable to 1,100) | Production agents, 24-hour sessions |
| Enterprise | Custom (starts at $2,000/mo commit) | 500 | Multi-day/persistent sessions, BYOC |
Three pricing habits that survive contact with real invoices: price in per-second rates (see the kill-lesson table), not monthly guesses — if you have never rented compute by the hour, our VPS hosting guide explains the model that sandboxes replace; keep concurrency in mind — a fleet of agents each holding one sandbox multiplies the bill; and always verify current pricing at write time, because this table reflects e2b.dev/pricing as crawled on 2026-11-01 and the company reprices like any startup. E2B is SOC 2 Type II and HIPAA compliant as of 2026, which is why the enterprise tier exists at all.
7 Beginner Mistakes That Cost Time or Money
Every E2B beginner hits some of these. Learn them here instead of in production:
| # | Mistake | What happens | The fix |
|---|---|---|---|
| 1 | Forgetting kill() | Per-second billing accrues on idle sandboxes indefinitely | Kill in a finally block or context manager — every time |
| 2 | Following the old CodeInterpreter API | notebook.exec_cell() snippets no longer match the Sandbox API | Use Sandbox.create() + runCode() from the current SDK |
| 3 | Installing npm i e2b for code execution | The core package has no runCode() — your code fails | Install @e2b/code-interpreter (npm) or e2b-code-interpreter (pip) |
| 4 | Hardcoding the API key | Leaked key = someone else's sandboxes on your bill | E2B_API_KEY env var or .env with dotenv, always |
| 5 | Installing packages on every run | Slow starts, repeated download time on every sandbox | Bake them into a custom template once |
| 6 | Assuming uploads work for directories | Directory transfers silently do not exist — files must be passed individually | Loop over files, or git clone inside the sandbox |
| 7 | Ignoring the timeout | Default 300s kills long jobs; 1h Hobby ceiling surprises you mid-run | Set timeoutMs on create, extend with setTimeout(), or design for pause |
Sources
Every fact in this guide was verified against a page opened on 2026-11-01: E2B quickstart (docs.e2b.dev/quickstart, updated 2026-10-30 — npm i @e2b/code-interpreter dotenv, Sandbox.create(), runCode(), files.write()/files.read()); E2B sandbox docs (docs.e2b.dev/sandbox, updated 2026-10-30 — kill(), timeouts, pause); E2B templates quickstart (docs.e2b.dev/template/quickstart, updated 2026-10-30 — CLI and SDK builds, build limits); E2B pricing (e2b.dev/pricing — per-second rates, Hobby/Pro/Enterprise plans); E2B homepage (e2b.dev, crawled 2026-11-01 — 100K+ teams, 94 of Fortune 100, 2B+ sandboxes, 15M+ monthly SDK downloads, SOC 2 Type II + HIPAA); E2B OpenCode agent docs (docs.e2b.dev/agents/opencode, updated 2026-10-22); E2B Pi agent docs (docs.e2b.dev/agents/pi); PyPI e2b 2.58.0 (released 2026-10-20) and PyPI e2b-code-interpreter 2.11.5 (released 2026-10-26); thedomin.com E2B comparison (2026-10-25 — microVM architecture, openness); bex.co E2B-vs-Daytona comparison (Oct 2026). The sub-200ms boot claim was deliberately excluded: no current E2B page publishes a millisecond figure; it survives only in third-party citations of older docs.
Frequently Asked Questions
Is E2B free?
Yes, to start. The Hobby plan is free and includes a $100 one-time usage credit with 20 concurrent sandboxes, which covers learning and prototypes. You pay per second of running-sandbox time once you outgrow the credit, and the Pro plan is $150/month plus usage.
Is E2B the same as the Gemma E2B model?
No. This guide is about E2B, the cloud-sandbox company at e2b.dev. "E2B" also names Google's Gemma 3n E2B on-device AI model (~2B effective parameters) and an unrelated hardware kit — all three pollute the search results for "e2b," which is why you should always add "sandbox" or "e2b.dev" to your query.
Do I need Docker to use E2B?
No. E2B sandboxes are Firecracker microVMs managed entirely by E2B — there is nothing to pull, build, or run locally. The Docker mental model helps (isolation, images, ephemeral containers) but no Docker knowledge or installation is required.
What is the difference between the e2b and e2b-code-interpreter packages?
The core e2b package gives you sandboxes with shell commands and files. The e2b-code-interpreter package (npm: @e2b/code-interpreter) adds code execution via runCode() — and its sandbox supports commands and files too, so it is the right default for beginners.
What happens if I forget to kill my sandbox?
It keeps billing you per second until it hits the timeout (default 300s, max 1 hour on Hobby / 24 hours on Pro) — and if you raised the timeout, longer. Always call sandbox.kill() in a finally block, or let auto-pause freeze the sandbox instead of paying for idle time.