Background commands are useful for starting web services, long-running tasks, or processes whose output needs to be read in phases.
Start a background command
After you set a command to run in the background, the SDK returns the process object immediately. You can then access ports, reconnect to the process, or stop it later.
TypeScript example:
import { Sandbox } from "e2b";
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
});
try {
const process = await sandbox.commands.run("python3 -m http.server 8000", {
background: true,
timeoutMs: 10 * 60 * 1000,
});
const host = sandbox.getHost(8000);
console.log(`https://${host}`);
const running = await sandbox.commands.list();
console.log(running);
await process.kill();
} finally {
await sandbox.kill();
}Python example:
import os
from e2b import Sandbox
sandbox = Sandbox.create(
"code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
process = sandbox.commands.run(
"python3 -m http.server 8000",
background=True,
timeout=10 * 60,
)
host = sandbox.get_host(8000)
print(f"https://{host}")
running = sandbox.commands.list()
print(running)
process.kill()
finally:
sandbox.kill()Connect to and stop processes
If you know the process ID, you can connect to a running process through sandbox.commands.connect(). To stop a process, call kill() on the process object or use sandbox.commands.kill().
Across SDK versions, process ID field names and connection parameter names may differ. Check the structure returned by sandbox.commands.list() first, then call connect() or kill() according to your SDK type definitions. If the background command was started in the current call, prefer storing the returned process object and calling process.kill().
Recommendations
Before exposing a service process, confirm which port it listens on, then get the access URL with
sandbox.getHost(port).Background processes do not stop automatically when the SDK call returns, but they are still subject to command execution timeout. The E2B SDK command timeout is usually 60 seconds by default. For long-running services or tasks, set an explicit timeout such as
timeoutMsin TypeScript ortimeoutin Python, and stop the process or terminate the sandbox when the task is finished.For tasks that need continuous output reading, prefer background processes plus reconnecting instead of blocking the main flow with a long synchronous timeout.
If a service exposes an external access URL, add authentication on the application side or use one-time task URLs to avoid exposing sensitive interfaces.