A template packages stable system dependencies, language runtimes, toolchains, and base code into a reusable runtime environment. Build it once, then create multiple independent sandboxes from it; updating the template does not affect sandboxes that are already running.
Write user data, temporary files, and frequently changing application state at runtime. Do not bake secrets or tokens into a template; inject them through environment variables when creating a sandbox.
Prerequisites
-
An E2B-compatible image reachable by the sandbox. You can use an official image from Build Custom Image Templates to try the flow first.
-
The connection parameters
E2B_API_KEY,E2B_API_URL, andE2B_DOMAIN. The SDK reads these three environment variables automatically, so the examples below do not pass them into method calls. For details, see E2B SDK Connection Parameters.
Install the Python SDK:
python3 -m venv .venv
source .venv/bin/activate
pip install e2b==2.31.0 python-dotenv
Create a .env file:
E2B_API_KEY=e2b_xxx
FROM_IMAGE="fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/code-interpreter-v1:v0.0.44"
E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com
Build a template and create a sandbox
The following example builds a template from an image and creates a sandbox with the returned template ID.
import os
import time
from dotenv import load_dotenv
from e2b import Sandbox, Template, default_build_logger
load_dotenv()
# The SDK reads E2B_API_KEY / E2B_API_URL / E2B_DOMAIN automatically.
# Define the template from an image and build it.
build = Template.build(
Template().from_image(os.environ["FROM_IMAGE"]),
name=f"template-{int(time.time())}",
cpu_count=2,
memory_mb=2048,
on_build_logs=default_build_logger(),
)
# Create a sandbox from the template that was just built.
sandbox = Sandbox.create(template=build.template_id, timeout=900)
try:
print(f"template_id: {build.template_id}")
print(f"sandbox_id: {sandbox.sandbox_id}")
finally:
sandbox.kill()
TypeScript example:
import { Sandbox, Template, defaultBuildLogger } from "e2b";
// The SDK reads E2B_API_KEY / E2B_API_URL / E2B_DOMAIN automatically.
// Define the template from an image and build it.
const build = await Template.build(
Template().fromImage(process.env.FROM_IMAGE),
`template-${Date.now()}`,
{ cpuCount: 2, memoryMB: 2048, onBuildLogs: defaultBuildLogger() },
);
// Create a sandbox from the template that was just built.
const sandbox = await Sandbox.create(build.templateId, { timeoutMs: 900_000 });
try {
console.log(`template_id: ${build.templateId}`);
console.log(`sandbox_id: ${sandbox.sandboxId}`);
} finally {
await sandbox.kill();
}
Next steps
-
Official Templates — create a sandbox directly, without building.
-
Build Custom Image Templates — custom images, build parameters, and the template build flow.
-
Template Names and Versioning — manage runtime environments and versions with names and tags.