通过 SDK 创建第一个云沙箱

更新时间:
复制 MD 格式

完成函数计算云沙箱的最小可用配置,通过 Python SDK、TypeScript SDK 或 E2B CLI 创建一个 code-interpreter-v1 沙箱并验证环境可用性。

前置条件

  • 已拥有阿里云账号,并具备函数计算相关操作权限。

  • 本机可访问北京地域的云沙箱服务。

  • 已安装 Python 3.10 或更高版本(Python SDK)。

  • 已安装 Node.js 18 或更高版本(TypeScript SDK)。

  • 如需使用 CLI,已安装 E2B CLI。macOS 可使用 brew install e2b,也可使用 npm i -g @e2b/cli

完成 FC3.0 SLR 授权

打开函数计算控制台,切换到北京地域。如果是新用户,第一次访问时会出现 SLR(Service Linked Role,服务关联角色)授权弹窗,确认授权即可。

说明

如果已经是 FC3.0 用户并且完成过 SLR 授权,可以跳过此步骤。

创建 API Key

  1. 进入函数计算控制台,切换到北京地域,打开左侧导航的云沙箱 > API Keys

  2. 创建一个 API Key 并及时保存。

API Key 只会完整展示一次,建议写入本地环境变量、CI/CD 密钥或密钥管理服务,不要直接写入代码仓库。

配置模板日志

创建 API Key 后,进入左侧导航的沙箱模板 > 官方模板,为后续要使用的模板完成日志配置,例如 code-interpreter-v1。

说明

强烈建议为模板配置日志。日志对线上问题排查、沙箱启动失败诊断、命令执行异常分析都很重要。

配置环境变量

export E2B_API_KEY=e2b_xxx
export E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
export E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com

SDK 示例

Python

安装依赖:

python3 -m venv .venv
source .venv/bin/activate
pip install e2b-code-interpreter

创建 quickstart.py

import os
from e2b_code_interpreter import Sandbox


def require_env(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"缺少环境变量: {name}")
    return value


api_key = require_env("E2B_API_KEY")

conn_opts = {
    "domain": require_env("E2B_DOMAIN"),
}

template = "code-interpreter-v1"
sandbox = None

try:
    print("Creating sandbox...")
    sandbox = Sandbox.create(
        template=template,
        api_key=api_key,
        **conn_opts,
    )

    result = sandbox.commands.run("ls -lh /")
    print("ls output:")
    print(result.stdout.strip())

    hello = sandbox.commands.run("python3 -c \"print('hello from sandbox')\"")
    print("python output:")
    print(hello.stdout.strip())
finally:
    if sandbox is not None:
        print("Closing sandbox...")
        sandbox.kill()

运行:

python quickstart.py

如果能看到 / 目录列表和 hello from sandbox,说明 SDK、API Key、域名和内置模板都已可用。

TypeScript

安装依赖:

npm init -y
npm install e2b @e2b/code-interpreter dotenv
npm install -D tsx typescript @types/node

创建 quickstart.ts

import 'dotenv/config';
import { Sandbox } from '@e2b/code-interpreter';

async function main() {
  const sbx = await Sandbox.create({
    template: 'code-interpreter-v1',
    apiKey: process.env.E2B_API_KEY,
    apiUrl: process.env.E2B_API_URL,
    domain: process.env.E2B_DOMAIN,
    timeoutMs: 300_000,
  });

  try {
    console.log(`sandbox created: ${sbx.sandboxId}`);

    const result = await sbx.commands.run('ls -lh /');
    console.log('ls output:');
    console.log(result.stdout.trim());

    const hello = await sbx.commands.run("python3 -c \"print('hello from sandbox')\"");
    console.log('python output:');
    console.log(hello.stdout.trim());
  } finally {
    await sbx.kill();
    console.log('sandbox destroyed');
  }
}

main();

运行:

npx tsx quickstart.ts

如果能看到 / 目录列表和 hello from sandbox,说明 SDK、API Key、域名和内置模板都已可用。

Python 与 TypeScript SDK 的主要差异

方面

Python SDK

TypeScript SDK

包名

e2b / e2b-code-interpreter

e2b / @e2b/code-interpreter

异步模式

同步调用

全异步(必须 await)

命名风格

snake_case(sandbox_id

camelCase(sandboxId

环境加载

os.environ.get()

dotenv/config 自动加载

超时参数

timeout(秒)

timeoutMs(毫秒)

运行方式

python3 xx.py

npx tsx xx.ts

E2B CLI 示例

除上述环境变量外,E2B CLI 还需要设置 E2B_ACCESS_TOKEN,当前服务中其值与 E2B_API_KEY 相同:

export E2B_ACCESS_TOKEN=$E2B_API_KEY

查看模板列表:

e2b template list

示例输出:

Access  Template ID           Template Name         vCPUs  RAM MiB  Created at  Disk size MiB  names                buildStatus
Public  z736qq9k2qtazlr1u80z  base                      2     2048  5/29/2026          10240  base                 ready
Public  27y6ril28g82jzzxgqec  code-interpreter-v1       2     2048  5/29/2026          10240  code-interpreter-v1  ready

创建并连接沙箱:

e2b sandbox create code-interpreter-v1

进入沙箱终端后执行:

python3 -c 'print("Hello, World!")'
exit

退出终端后,CLI 会关闭终端连接。生产代码中仍建议显式销毁不再使用的沙箱。

使用建议

  • 及时释放资源:每次创建沙箱后都要在 finally 或退出逻辑中销毁资源,避免空闲沙箱持续占用配额。

  • 安全管理密钥:API Key 只通过环境变量、CI 密钥或密钥管理服务注入,不要提交到 Git。

  • 生产环境配置超时和重试:生产任务建议设置明确的 timeout、必要时通过 set_timeout / setTimeout 续期,并配置重试和日志采集策略。

  • 渐进式验证自定义模板:自定义模板优先做小步验证:先启动沙箱并运行 envpython --versionwhich <command> 等基础命令,再接入业务代码。

常见问题

提示未授权或无法创建资源

先确认 FC3.0 SLR 授权是否完成,再确认当前账号是否有函数计算和云沙箱相关权限。

提示 API Key 无效

确认 E2B_API_KEY 没有多余空格,并且没有把控制台里被截断展示的值当成完整密钥使用。

CLI 能访问但 SDK 不能访问

确认 SDK 代码同时传入了 api_url/apiUrldomain,并且值分别为:

https://api.cn-beijing.e2b.fc.aliyuncs.com
cn-beijing.e2b.fc.aliyuncs.com

沙箱创建后命令执行失败

先运行基础命令定位问题:

sandbox.commands.run("pwd && whoami && python3 --version")

如果基础命令可用,再检查模板是否已包含业务命令所需的依赖。

如何调整沙箱存活时间

创建沙箱时可以设置初始存活时间。Python SDK 使用 timeout 参数(单位:秒),例如 Sandbox.create(timeout=60, ...);TypeScript SDK 使用 timeoutMs 参数(单位:毫秒),例如 Sandbox.create({ timeoutMs: 60_000, ... })。如果不传超时参数,默认存活时间为 300 秒。

沙箱创建后也支持 E2B 官方 SDK 中的 sandbox.set_timeout() 续期行为,它会把沙箱的剩余存活时间重置为传入值,而不是在当前剩余时间上累加。例如沙箱还剩 120 秒时调用 sandbox.set_timeout(600),新的剩余存活时间是 600 秒,不是 720 秒。任务完成后仍建议主动调用 sandbox.kill() 释放资源。