cloudflare-sandbox

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Sandboxes SDK

Cloudflare Sandboxes SDK

Status: Production Ready (Open Beta) Last Updated: 2025-12-10 Dependencies:
cloudflare-worker-base
,
cloudflare-durable-objects
(recommended for understanding) Latest Versions:
@cloudflare/sandbox@0.6.3
, Docker image:
cloudflare/sandbox:0.6.3-python
⚠️ BREAKING CHANGE (v0.6.0): Python is no longer included in the default image. Use
cloudflare/sandbox:<version>-python
for Python support (~1.3GB with data science packages). The lean variant (~600-800MB) excludes Python.

状态:生产就绪(公开测试版) 最后更新:2025-12-10 依赖项
cloudflare-worker-base
cloudflare-durable-objects
(建议了解相关内容) 最新版本
@cloudflare/sandbox@0.6.3
,Docker镜像:
cloudflare/sandbox:0.6.3-python
⚠️ 重大变更(v0.6.0): 默认镜像不再包含Python。如需Python支持,请使用
cloudflare/sandbox:<version>-python
(包含数据科学包,约1.3GB)。精简版镜像(约600-800MB)不含Python。

Quick Start (15 Minutes)

快速开始(15分钟)

1. Install SDK and Setup Wrangler

1. 安装SDK并配置Wrangler

bash
bun add @cloudflare/sandbox@latest  # preferred
bash
bun add @cloudflare/sandbox@latest  # 推荐方式

or: bun add @cloudflare/sandbox@latest

或:bun add @cloudflare/sandbox@latest


**wrangler.jsonc:**
```jsonc
{
  "name": "my-sandbox-worker",
  "main": "src/index.ts",
  "compatibility_flags": ["nodejs_compat"],
  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python",
    "instance_type": "lite"
  }],
  "durable_objects": {
    "bindings": [{
      "class_name": "Sandbox",
      "name": "Sandbox"
    }]
  },
  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}
Why this matters:
  • nodejs_compat
    enables Node.js APIs required by SDK
  • containers
    defines the Ubuntu container image
  • durable_objects
    binding enables persistent routing
  • migrations
    registers the Sandbox class

**wrangler.jsonc:**
```jsonc
{
  "name": "my-sandbox-worker",
  "main": "src/index.ts",
  "compatibility_flags": ["nodejs_compat"],
  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python",
    "instance_type": "lite"
  }],
  "durable_objects": {
    "bindings": [{
      "class_name": "Sandbox",
      "name": "Sandbox"
    }]
  },
  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}
配置说明:
  • nodejs_compat
    启用SDK所需的Node.js API
  • containers
    定义Ubuntu容器镜像
  • durable_objects
    绑定实现持久化路由
  • migrations
    注册Sandbox类

2. Create Your First Sandbox Worker

2. 创建第一个Sandbox Worker

typescript
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';

type Env = {
  Sandbox: DurableObjectNamespace<Sandbox>;
};

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Get sandbox instance (creates if doesn't exist)
    const sandbox = getSandbox(env.Sandbox, 'my-first-sandbox');

    // Execute Python code
    const result = await sandbox.exec('python3 -c "print(2 + 2)"');

    return Response.json({
      output: result.stdout,
      success: result.success,
      exitCode: result.exitCode
    });
  }
};
CRITICAL:
  • MUST export
    { Sandbox }
    from
    @cloudflare/sandbox
    in your Worker
  • Sandbox ID determines routing (same ID = same container)
  • First request creates container (~2-3 min cold start)
  • Subsequent requests are fast (<1s)
typescript
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';

type Env = {
  Sandbox: DurableObjectNamespace<Sandbox>;
};

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // 获取沙箱实例(不存在则创建)
    const sandbox = getSandbox(env.Sandbox, 'my-first-sandbox');

    // 执行Python代码
    const result = await sandbox.exec('python3 -c "print(2 + 2)"');

    return Response.json({
      output: result.stdout,
      success: result.success,
      exitCode: result.exitCode
    });
  }
};
关键注意事项:
  • 必须导出
    { Sandbox }
    @cloudflare/sandbox
    到你的Worker中
  • Sandbox ID决定路由(相同ID对应同一个容器)
  • 首次请求会创建容器(冷启动约2-3分钟)
  • 后续请求响应快速(<1秒)

3. Deploy and Test

3. 部署并测试

bash
npm run deploy
curl https://your-worker.workers.dev
Expected output:
json
{
  "output": "4\n",
  "success": true,
  "exitCode": 0
}
bash
npm run deploy
curl https://your-worker.workers.dev
预期输出:
json
{
  "output": "4\n",
  "success": true,
  "exitCode": 0
}

Secure Installation

安全安装

Sandbox SDK packages grant container access — verify before installing to prevent unauthorized code execution. Follow supply chain security best practices:
  • Block post-install scripts
    npm config set ignore-scripts true
    (or Bun: disabled by default)
  • Cooldown period — Wait 7 days for new package versions to be vetted by the community
  • Audit before installing — Run
    socket package score npm <pkg>
    or use
    socket npm install <pkg>
    to check packages
Load the
dependency-upgrade
skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.

Sandbox SDK包提供容器访问权限——安装前请验证包的安全性,防止未授权代码执行。遵循供应链安全最佳实践:
  • 阻止安装后脚本 ——
    npm config set ignore-scripts true
    (Bun默认已禁用)
  • 等待冷却期 —— 新包版本发布后等待7天,待社区验证后再安装
  • 安装前审计 —— 运行
    socket package score npm <pkg>
    或使用
    socket npm install <pkg>
    检查包安全性
加载
dependency-upgrade
技能以获取完整安全配置,包括Socket CLI集成、冷却期设置、锁文件验证和CI强制执行。

Architecture (Understanding the 3-Layer Model)

架构(理解三层模型)

How Sandboxes Work

沙箱工作原理

┌─────────────────────────────────────────┐
│  Your Worker (Layer 1)                  │
│  - Handles HTTP requests                │
│  - Calls getSandbox()                   │
│  - Uses sandbox.exec(), writeFile(), etc│
└──────────────┬──────────────────────────┘
               │ RPC via Durable Object
┌──────────────▼──────────────────────────┐
│  Durable Object (Layer 2)               │
│  - Routes by sandbox ID                 │
│  - Maintains persistent identity        │
│  - Geographic stickiness                │
└──────────────┬──────────────────────────┘
               │ Container API
┌──────────────▼──────────────────────────┐
│  Ubuntu Container (Layer 3)             │
│  - Full Linux environment               │
│  - Python 3.11, Node 20, Git, etc.      │
│  - Filesystem: /workspace, /tmp, /home  │
│  - Process isolation (VM-based)         │
└─────────────────────────────────────────┘
Key Insight: Workers handle API logic (fast), Durable Objects route requests (persistent identity), Containers execute code (full capabilities).

┌─────────────────────────────────────────┐
│  你的Worker(第一层)                  │
│  - 处理HTTP请求                        │
│  - 调用getSandbox()                   │
│  - 使用sandbox.exec()、writeFile()等方法│
└──────────────┬──────────────────────────┘
               │ 通过Durable Object进行RPC调用
┌──────────────▼──────────────────────────┐
│  Durable Object(第二层)               │
│  - 按沙箱ID路由请求                     │
│  - 维护持久化身份标识                   │
│  - 地理位置粘性                        │
└──────────────┬──────────────────────────┘
               │ 容器API
┌──────────────▼──────────────────────────┐
│  Ubuntu容器(第三层)                   │
│  - 完整Linux环境                       │
│  - 包含Python 3.11、Node 20、Git等工具 │
│  - 文件系统:/workspace、/tmp、/home    │
│  - 基于VM的进程隔离                    │
└─────────────────────────────────────────┘
核心要点:Worker处理API逻辑(快速响应),Durable Object负责请求路由(持久化身份),容器执行代码(完整功能)。

Critical Container Lifecycle (Most Important Section!)

关键容器生命周期(最重要的部分!)

Container States

容器状态

┌─────────┐  First request  ┌────────┐  ~10 min idle  ┌──────┐
│ Not     │ ───────────────>│ Active │ ─────────────> │ Idle │
│ Created │                 │        │                │      │
└─────────┘                 └───┬────┘                └──┬───┘
                                │ ^                      │
                                │ │ New request          │
                                │ └──────────────────────┘
                                │                         │
                                ▼                         ▼
                            Files persist          ALL FILES DELETED
                            Processes run          ALL PROCESSES KILLED
                            State maintained       ALL STATE RESET
┌─────────┐  首次请求  ┌────────┐  闲置约10分钟  ┌──────┐
│  未创建 │ ───────────>│ 活跃   │ ─────────────> │ 闲置 │
│         │             │        │                │      │
└─────────┘             └───┬────┘                └──┬───┘
                            │ ^                      │
                            │ │ 新请求               │
                            │ └──────────────────────┘
                            │                         │
                            ▼                         ▼
                        文件持久化              所有文件被删除
                        进程持续运行            所有进程被终止
                        状态保持不变            所有状态重置

The #1 Gotcha: Ephemeral by Default

头号陷阱:默认临时特性

While Container is Active (~10 min after last request):
  • ✅ Files in
    /workspace
    ,
    /tmp
    ,
    /home
    persist
  • ✅ Background processes keep running
  • ✅ Shell environment variables remain
  • ✅ Session working directories preserved
When Container Goes Idle (after inactivity):
  • ALL files deleted (entire filesystem reset)
  • ALL processes terminated
  • ALL shell state lost
  • ⚠️ Next request creates fresh container from scratch
This is NOT like a traditional server. Sandboxes are ephemeral by design.
容器活跃期间(最后一次请求后约10分钟):
  • /workspace
    /tmp
    /home
    中的文件会持久化
  • ✅ 后台进程保持运行
  • ✅ Shell环境变量保留
  • ✅ 会话工作目录被保存
容器进入闲置状态后(无活动后):
  • 所有文件被删除(整个文件系统重置)
  • 所有进程被终止
  • 所有Shell状态丢失
  • ⚠️ 下一次请求会从头创建全新容器
这与传统服务器不同。沙箱设计为临时特性。

Handling Persistence

处理持久化

For Important Data: Use external storage
typescript
// Save to R2 before container goes idle
await sandbox.writeFile('/workspace/data.txt', content);
const fileData = await sandbox.readFile('/workspace/data.txt');
await env.R2.put('backup/data.txt', fileData);

// Restore on next request
const restored = await env.R2.get('backup/data.txt');
if (restored) {
  await sandbox.writeFile('/workspace/data.txt', await restored.text());
}
For Build Artifacts: Accept ephemerality or use caching
typescript
// Check if setup needed (handles cold starts)
const exists = await sandbox.readdir('/workspace/project').catch(() => null);
if (!exists) {
  await sandbox.gitCheckout(repoUrl, '/workspace/project');
  await sandbox.exec('npm install', { cwd: '/workspace/project' });
}
// Now safe to run build
await sandbox.exec('npm run build', { cwd: '/workspace/project' });

重要数据:使用外部存储
typescript
// 容器闲置前保存到R2
await sandbox.writeFile('/workspace/data.txt', content);
const fileData = await sandbox.readFile('/workspace/data.txt');
await env.R2.put('backup/data.txt', fileData);

// 下一次请求时恢复
const restored = await env.R2.get('backup/data.txt');
if (restored) {
  await sandbox.writeFile('/workspace/data.txt', await restored.text());
}
构建产物:接受临时特性或使用缓存
typescript
// 检查是否需要初始化(处理冷启动)
const exists = await sandbox.readdir('/workspace/project').catch(() => null);
if (!exists) {
  await sandbox.gitCheckout(repoUrl, '/workspace/project');
  await sandbox.exec('npm install', { cwd: '/workspace/project' });
}
// 现在可以安全执行构建
await sandbox.exec('npm run build', { cwd: '/workspace/project' });

Session Management (Game-Changer for Chat Agents)

会话管理(聊天Agent的关键功能)

What Are Sessions?

什么是会话?

Sessions are bash shell contexts within one sandbox. Think terminal tabs.
Key Properties:
  • Each session has separate working directory
  • Sessions share same filesystem
  • Working directory persists across commands in same session
  • Perfect for multi-step workflows
会话是单个沙箱内的bash Shell上下文,可以理解为终端标签页。
核心特性
  • 每个会话有独立的工作目录
  • 会话共享同一文件系统
  • 同一会话中的命令会保留工作目录
  • 完美适用于多步骤工作流

Pattern: Chat-Based Coding Agent

模式:基于聊天的编码Agent

typescript
type ConversationState = {
  sandboxId: string;
  sessionId: string;
};

// First message: Create sandbox and session
const sandboxId = `user-${userId}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
const sessionId = await sandbox.createSession();

// Store in conversation state (database, KV, etc.)
await env.KV.put(`conversation:${conversationId}`, JSON.stringify({
  sandboxId,
  sessionId
}));

// Later messages: Reuse same session
const state = await env.KV.get(`conversation:${conversationId}`);
const { sandboxId, sessionId } = JSON.parse(state);
const sandbox = getSandbox(env.Sandbox, sandboxId);

// Commands run in same context
await sandbox.exec('cd /workspace/project', { session: sessionId });
await sandbox.exec('ls -la', { session: sessionId }); // Still in /workspace/project
await sandbox.exec('git status', { session: sessionId }); // Still in /workspace/project
typescript
type ConversationState = {
  sandboxId: string;
  sessionId: string;
};

// 第一条消息:创建沙箱和会话
const sandboxId = `user-${userId}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
const sessionId = await sandbox.createSession();

// 存储到对话状态(数据库、KV等)
await env.KV.put(`conversation:${conversationId}`, JSON.stringify({
  sandboxId,
  sessionId
}));

// 后续消息:复用同一会话
const state = await env.KV.get(`conversation:${conversationId}`);
const { sandboxId, sessionId } = JSON.parse(state);
const sandbox = getSandbox(env.Sandbox, sandboxId);

// 命令在同一上下文执行
await sandbox.exec('cd /workspace/project', { session: sessionId });
await sandbox.exec('ls -la', { session: sessionId }); // 仍处于/workspace/project目录
await sandbox.exec('git status', { session: sessionId }); // 仍处于/workspace/project目录

Without Sessions (Common Mistake)

不使用会话的常见错误

typescript
// ❌ WRONG: Each command runs in separate session
await sandbox.exec('cd /workspace/project');
await sandbox.exec('ls'); // NOT in /workspace/project (different session)
typescript
// ❌ 错误:每个命令在独立会话中执行
await sandbox.exec('cd /workspace/project');
await sandbox.exec('ls'); // 不在/workspace/project目录(不同会话)

Pattern: Parallel Execution

模式:并行执行

typescript
const session1 = await sandbox.createSession();
const session2 = await sandbox.createSession();

// Run different tasks simultaneously
await Promise.all([
  sandbox.exec('python train_model.py', { session: session1 }),
  sandbox.exec('node generate_reports.js', { session: session2 })
]);

typescript
const session1 = await sandbox.createSession();
const session2 = await sandbox.createSession();

// 同时运行不同任务
await Promise.all([
  sandbox.exec('python train_model.py', { session: session1 }),
  sandbox.exec('node generate_reports.js', { session: session2 })
]);

Sandbox Naming Strategies

沙箱命名策略

Per-User Sandboxes (Persistent Workspace)

按用户分配沙箱(持久化工作区)

typescript
const sandbox = getSandbox(env.Sandbox, `user-${userId}`);
Pros: User's work persists while actively using (10 min idle time) Cons: Geographic lock-in (first request determines location) Use Cases: Interactive notebooks, IDEs, persistent workspaces
typescript
const sandbox = getSandbox(env.Sandbox, `user-${userId}`);
优点:用户在活跃使用期间(闲置10分钟内)的工作会持久化 缺点:地理位置锁定(首次请求决定位置) 适用场景:交互式笔记本、IDE、持久化工作区

Per-Session Sandboxes (Fresh Each Time)

按会话分配沙箱(每次全新创建)

typescript
const sandboxId = `session-${Date.now()}-${crypto.randomUUID()}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
// Always destroy after use
await sandbox.destroy();
Pros: Clean environment, no state pollution Cons: No persistence between requests Use Cases: One-shot code execution, CI/CD, testing
typescript
const sandboxId = `session-${Date.now()}-${crypto.randomUUID()}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
// 使用后务必销毁
await sandbox.destroy();
优点:环境干净,无状态污染 缺点:请求间无持久化 适用场景:一次性代码执行、CI/CD、测试

Per-Task Sandboxes (Idempotent & Traceable)

按任务分配沙箱(幂等且可追踪)

typescript
const sandbox = getSandbox(env.Sandbox, `build-${repoName}-${commitSha}`);
Pros: Reproducible, debuggable, cacheable Cons: Need explicit cleanup strategy Use Cases: Build systems, data pipelines, automated workflows

typescript
const sandbox = getSandbox(env.Sandbox, `build-${repoName}-${commitSha}`);
优点:可重现、可调试、可缓存 缺点:需要明确的清理策略 适用场景:构建系统、数据管道、自动化工作流

Core API Reference

核心API参考

The Sandbox SDK provides methods for command execution, file operations, Git operations, code interpretation (Jupyter-like), background processes, and cleanup.
📖 Load
references/api-reference.md
when you need detailed API method signatures, parameter options, or implementation examples for:
  • Executing commands with options (cwd, timeout, env vars, sessions)
  • File operations (read/write/mkdir/rm/readdir)
  • Git operations (gitCheckout, git commands)
  • Code interpreter (createCodeContext, runCode)
  • Background processes (spawn, isProcessRunning, killProcess)
  • Sandbox cleanup (destroy)

Sandbox SDK提供命令执行、文件操作、Git操作、代码解释(类Jupyter)、后台进程和清理等方法。
📖 加载
references/api-reference.md
获取详细的API方法签名、参数选项或实现示例,包括:
  • 带选项的命令执行(工作目录、超时、环境变量、会话)
  • 文件操作(读/写/创建目录/删除/列出目录)
  • Git操作(gitCheckout、Git命令)
  • 代码解释器(createCodeContext、runCode)
  • 后台进程(spawn、isProcessRunning、killProcess)
  • 沙箱清理(destroy)

Critical Rules

关键规则

Always Do

必须遵守

Check exit codes -
if (!result.success) { handle error }
Use sessions for multi-step workflows - Preserve working directory ✅ Handle cold starts - Check if files exist before assuming they're there ✅ Set timeouts - Prevent hanging on long operations ✅ Destroy ephemeral sandboxes - Cleanup temp/session-based sandboxes ✅ Use external storage for persistence - R2/KV/D1 for important data ✅ Validate user input - Sanitize before exec() to prevent command injection ✅ Export Sandbox class -
export { Sandbox } from '@cloudflare/sandbox'
检查退出码 -
if (!result.success) { 处理错误 }
多步骤工作流使用会话 - 保留工作目录 ✅ 处理冷启动 - 运行命令前检查文件是否存在 ✅ 设置超时 - 防止长时间操作挂起 ✅ 销毁临时沙箱 - 清理临时/会话型沙箱 ✅ 使用外部存储实现持久化 - 重要数据存储到R2/KV/D1 ✅ 验证用户输入 - 执行exec()前进行 sanitize 处理,防止命令注入 ✅ 导出Sandbox类 -
export { Sandbox } from '@cloudflare/sandbox'

Never Do

禁止操作

Assume files persist after idle - Container resets after ~10 min ❌ Ignore exit codes - Always check
result.success
or
result.exitCode
Chain commands without sessions -
cd /dir
then
ls
won't work ❌ Execute unsanitized user input - Use code interpreter or validate thoroughly ❌ Forget nodejs_compat flag - Required in wrangler.jsonc ❌ Skip migrations - Durable Objects need migration entries ❌ Use .workers.dev for preview URLs - Need custom domain ❌ Create unlimited sandboxes - Destroy ephemeral ones to avoid leaks

假设闲置后文件仍存在 - 容器约10分钟后重置 ❌ 忽略退出码 - 务必检查
result.success
result.exitCode
无会话链式执行命令 -
cd /dir
后执行
ls
不会生效 ❌ 执行未 sanitize 的用户输入 - 使用代码解释器或彻底验证输入 ❌ 忘记nodejs_compat标志 - wrangler.jsonc中必须配置 ❌ 跳过迁移配置 - Durable Objects需要迁移条目 ❌ 使用.workers.dev作为预览URL - 需要自定义域名 ❌ 创建无限沙箱 - 销毁临时沙箱避免资源泄漏

Known Issues Prevention

已知问题预防

This skill prevents 10 documented issues:
本技能可预防10个已记录的问题:

Issue #1: Missing nodejs_compat Flag

问题#1:缺少nodejs_compat标志

Error:
ReferenceError: fetch is not defined
or
Buffer is not defined
Source: https://developers.cloudflare.com/sandbox/get-started/ Why It Happens: SDK requires Node.js APIs not available in standard Workers Prevention: Add
"compatibility_flags": ["nodejs_compat"]
to wrangler.jsonc
错误
ReferenceError: fetch is not defined
Buffer is not defined
来源https://developers.cloudflare.com/sandbox/get-started/ 原因:SDK需要标准Worker中未提供的Node.js API 预防:在wrangler.jsonc中添加
"compatibility_flags": ["nodejs_compat"]

Issue #2: Missing Migrations

问题#2:缺少迁移配置

Error:
Error: Class 'Sandbox' not found
Source: https://developers.cloudflare.com/durable-objects/ Why It Happens: Durable Objects must be registered via migrations Prevention: Include migrations array in wrangler.jsonc
错误
Error: Class 'Sandbox' not found
来源https://developers.cloudflare.com/durable-objects/ 原因:Durable Objects必须通过迁移注册 预防:在wrangler.jsonc中包含migrations数组

Issue #3: Assuming File Persistence

问题#3:假设文件持久化

Error: Files disappear after inactivity Source: https://developers.cloudflare.com/sandbox/concepts/sandboxes/ Why It Happens: Containers go idle after ~10 min, all state reset Prevention: Use external storage (R2/KV) or check existence on each request
错误:闲置后文件消失 来源https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器闲置约10分钟后所有状态重置 预防:使用外部存储(R2/KV)或每次请求时检查文件存在性

Issue #4: Session Directory Confusion

问题#4:会话目录混淆

Error: Commands execute in wrong directory Source: https://developers.cloudflare.com/sandbox/concepts/sessions/ Why It Happens: Each exec() uses new session unless explicitly specified Prevention: Create session with
createSession()
, pass to all related commands
错误:命令在错误目录执行 来源https://developers.cloudflare.com/sandbox/concepts/sessions/ 原因:除非明确指定,否则每个exec()使用新会话 预防:使用
createSession()
创建会话,并传递给所有相关命令

Issue #5: Ignoring Exit Codes

问题#5:忽略退出码

Error: Assuming command succeeded when it failed Source: Shell best practices Why It Happens: Not checking
result.success
or
result.exitCode
Prevention: Always check:
if (!result.success) throw new Error(result.stderr)
错误:假设命令成功但实际失败 来源:Shell最佳实践 原因:未检查
result.success
result.exitCode
预防:务必检查:
if (!result.success) throw new Error(result.stderr)

Issue #6: Not Handling Cold Starts

问题#6:未处理冷启动

Error: Commands fail because dependencies aren't installed Source: https://developers.cloudflare.com/sandbox/concepts/sandboxes/ Why It Happens: Container resets after idle period Prevention: Check if setup needed before running commands
错误:因依赖未安装导致命令失败 来源https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器闲置后重置 预防:运行命令前检查是否需要初始化

Issue #7: Docker Not Running (Local Dev)

问题#7:Docker未运行(本地开发)

Error:
Failed to build container
during local development Source: https://developers.cloudflare.com/sandbox/get-started/ Why It Happens: Local dev requires Docker daemon Prevention: Ensure Docker Desktop is running before
npm run dev
错误:本地开发期间
Failed to build container
来源https://developers.cloudflare.com/sandbox/get-started/ 原因:本地开发需要Docker守护进程 预防:运行
npm run dev
前确保Docker Desktop已启动

Issue #8: Version Mismatch (Package vs Docker Image)

问题#8:版本不匹配(包与Docker镜像)

Error: API methods not available or behaving unexpectedly Source: GitHub issues Why It Happens: npm package version doesn't match Docker image version Prevention: Keep
@cloudflare/sandbox
package and
cloudflare/sandbox
image in sync
错误:API方法不可用或行为异常 来源:GitHub issues 原因:npm包版本与Docker镜像版本不一致 预防:保持
@cloudflare/sandbox
包和
cloudflare/sandbox
镜像版本同步

Issue #9: Not Cleaning Up Ephemeral Sandboxes

问题#9:未清理临时沙箱

Error: Resource exhaustion, unexpected costs Source: Resource management best practices Why It Happens: Creating sandboxes without destroying them Prevention:
await sandbox.destroy()
in finally block for temp sandboxes
错误:资源耗尽、意外成本 来源:资源管理最佳实践 原因:创建沙箱后未销毁 预防:临时沙箱在finally块中执行
await sandbox.destroy()

Issue #10: Command Injection Vulnerability

问题#10:命令注入漏洞

Error: Security breach from unsanitized user input Source: Security best practices Why It Happens: Passing user input directly to
exec()
Prevention: Use code interpreter API or validate/sanitize input thoroughly

错误:未 sanitize 的用户输入导致安全 breach 来源:安全最佳实践 原因:直接将用户输入传递给
exec()
预防:使用代码解释器API或彻底验证/ sanitize 输入

wrangler.jsonc Example

wrangler.jsonc示例

jsonc
{
  "name": "my-sandbox-app",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-29",
  "compatibility_flags": ["nodejs_compat"], // ← REQUIRED

  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python", // ← Use -python for Python support
    "instance_type": "lite"
  }],

  "durable_objects": {
    "bindings": [{"class_name": "Sandbox", "name": "Sandbox"}]
  },

  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}

jsonc
{
  "name": "my-sandbox-app",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-29",
  "compatibility_flags": ["nodejs_compat"], // ← 必填

  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python", // ← 需要Python支持请使用-python后缀
    "instance_type": "lite"
  }],

  "durable_objects": {
    "bindings": [{"class_name": "Sandbox", "name": "Sandbox"}]
  },

  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}

Common Patterns

常见模式

Four production-ready patterns for building with Cloudflare Sandboxes: one-shot code execution, persistent user workspaces, CI/CD pipelines, and AI agent integration.
📖 Load
references/patterns.md
when you need complete implementation examples for:
  1. One-Shot Code Execution - API endpoints, code playgrounds, learning platforms
  2. Persistent User Workspace - Interactive environments, notebooks, IDEs
  3. CI/CD Build Pipeline - Build systems, testing pipelines, deployment automation
  4. AI Agent with Claude Code - Automated refactoring, code generation, AI development

使用Cloudflare Sandboxes构建的四种生产就绪模式:一次性代码执行、持久化用户工作区、CI/CD管道和AI Agent集成。
📖 加载
references/patterns.md
获取完整实现示例,包括:
  1. 一次性代码执行 - API端点、代码游乐场、学习平台
  2. 持久化用户工作区 - 交互式环境、笔记本、IDE
  3. CI/CD构建管道 - 构建系统、测试管道、部署自动化
  4. 集成Claude Code的AI Agent - 自动重构、代码生成、AI开发

Using Bundled Resources

使用捆绑资源

Scripts (scripts/)

脚本(scripts/)

  • setup-sandbox-binding.sh
    - Interactive wrangler.jsonc configuration
  • test-sandbox.ts
    - Validation script to test sandbox setup
Example Usage:
bash
undefined
  • setup-sandbox-binding.sh
    - 交互式wrangler.jsonc配置脚本
  • test-sandbox.ts
    - 验证沙箱设置的测试脚本
示例用法:
bash
undefined

Setup wrangler config

配置wrangler

./scripts/setup-sandbox-binding.sh
./scripts/setup-sandbox-binding.sh

Test sandbox

测试沙箱

bunx tsx scripts/test-sandbox.ts
undefined
bunx tsx scripts/test-sandbox.ts
undefined

References (references/)

参考文档(references/)

  • references/persistence-guide.md
    - Deep dive on container lifecycle and persistence
  • references/session-management.md
    - Advanced session patterns and best practices
  • references/common-errors.md
    - Complete list of errors with solutions
  • references/naming-strategies.md
    - Choosing sandbox IDs for different use cases
When Claude should load these:
  • Load
    persistence-guide.md
    when debugging state issues or cold starts
  • Load
    session-management.md
    when building multi-step workflows or chat agents
  • Load
    common-errors.md
    when encountering specific errors
  • Load
    naming-strategies.md
    when designing sandbox architecture

  • references/persistence-guide.md
    - 容器生命周期和持久化深度指南
  • references/session-management.md
    - 高级会话模式和最佳实践
  • references/common-errors.md
    - 完整错误列表及解决方案
  • references/naming-strategies.md
    - 不同场景下的沙箱ID选择策略
Claude应加载这些文档的场景:
  • 调试状态问题或冷启动时加载
    persistence-guide.md
  • 构建多步骤工作流或聊天Agent时加载
    session-management.md
  • 遇到特定错误时加载
    common-errors.md
  • 设计沙箱架构时加载
    naming-strategies.md

Advanced Topics

高级主题

📖 Load
references/advanced.md
for production patterns:
  • Geographic distribution strategies for global apps
  • Error handling wrapper functions
  • Security hardening and input validation

📖 加载
references/advanced.md
获取生产模式:
  • 全球应用的地理分布策略
  • 错误处理包装函数
  • 安全加固和输入验证

Official Resources

官方资源

Package:
@cloudflare/sandbox@0.6.3
| Docker:
cloudflare/sandbox:0.6.3-python
@cloudflare/sandbox@0.6.3
| Docker镜像
cloudflare/sandbox:0.6.3-python