mcpField
C
cloudflare-sandbox

cloudflare-sandbox

github.com/jackspace云与 DevOps1641 次安装12 周前更新
代码仓库

关于 cloudflare-sandbox

cloudflare-sandbox 是面向使用 Cloudflare Workers 构建沙箱工作流的 SDK 技能指南,介绍容器命令执行、会话和文件操作,并重点说明容器空闲后的临时性及持久化处理。

主要功能

  1. 01在容器中执行命令
  2. 02管理 shell 会话和工作目录
  3. 03读写文件并检出 Git 仓库
  4. 04运行代码解释器和后台进程
  5. 05说明容器生命周期与数据持久化

适用场景

  1. 01为编码 Agent 提供临时执行环境
  2. 02在同一会话中完成多步命令任务
  3. 03运行构建、测试或数据处理任务
  4. 04处理沙箱冷启动和外部存储备份

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill cloudflare-sandbox

安装后在 Claude Code 中输入/cloudflare-sandbox确认已加载。

附带文件README.mdSKILL.json

详细介绍

Cloudflare Sandboxes SDK

状态:生产就绪(公开测试版) 最后更新:2025-10-29 依赖项:cloudflare-worker-base、cloudflare-durable-objects(建议了解) 最新版本:@cloudflare/[email protected],Docker 镜像:cloudflare/sandbox:0.4.12


快速入门(15 分钟)

1. 安装 SDK 并设置 Wrangler
npm install @cloudflare/sandbox@latest

wrangler.jsonc:

{
  "name": "my-sandbox-worker",
  "main": "src/index.ts",
  "compatibility_flags": ["nodejs_compat"],
  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.4.12",
    "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. 创建首个 Sandbox Worker
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
    });
  }
};

重要:

  • Worker 中必须导出来自 @cloudflare/sandbox 的 { Sandbox }
  • Sandbox ID 决定路由(相同 ID = 相同容器)
  • 首个请求会创建容器(冷启动约需 2-3 分钟)
  • 后续请求速度很快(<1 秒)
3. 部署并测试
npm run deploy
curl https://your-worker.workers.dev

预期输出:

{
  "output": "4\n",
  "success": true,
  "exitCode": 0
}

架构(了解三层模型)

Sandbox 的工作方式
┌─────────────────────────────────────────┐
│  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)         │
└─────────────────────────────────────────┘

关键要点:Worker 负责处理 API 逻辑(快速),Durable Objects 负责路由请求(持久身份),容器负责执行代码(功能完整)。


容器生命周期须知(最重要的部分!)

容器状态
┌─────────┐  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 分钟内):

  • ✅ /workspace、/tmp、/home 中的文件会保留
  • ✅ 后台进程会继续运行
  • ✅ Shell 环境变量会保留
  • ✅ 会话工作目录会保留

容器进入空闲状态时(不活动后):

  • ❌ 所有文件都会被删除(整个文件系统会重置)
  • ❌ 所有进程都会终止
  • ❌ 所有 Shell 状态都会丢失
  • ⚠️ 下一个请求会从头创建一个全新的容器

这与传统服务器不同。Sandbox 从设计上就是临时的。

处理持久化

重要数据:使用外部存储

// 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());
}

构建产物:接受临时性,或使用缓存

// 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' });

会话管理(聊天 Agent 的游戏规则改变者)

什么是会话?

会话是一个 Sandbox 内的 bash Shell 上下文。可以把它想成终端标签页。

主要属性:

  • 每个会话都有独立的工作目录
  • 会话共用同一文件系统
  • 同一会话中的工作目录会在各条命令间保留
  • 非常适合多步骤工作流
模式:基于聊天的编码 Agent
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
不使用会话(常见错误)
// ❌ WRONG: Each command runs in separate session
await sandbox.exec('cd /workspace/project');
await sandbox.exec('ls'); // NOT in /workspace/project (different session)
模式:并行执行
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 })
]);

Sandbox 命名策略

按用户创建 Sandbox(持久工作区)
const sandbox = getSandbox(env.Sandbox, `user-${userId}`);

优点:用户在积极使用时,工作会保留(空闲时间为 10 分钟) 缺点:受地理位置限制(首个请求决定位置) 使用场景:交互式笔记本、IDE、持久工作区

按会话创建 Sandbox(每次都是全新的)
const sandboxId = `session-${Date.now()}-${crypto.randomUUID()}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
// Always destroy after use
await sandbox.destroy();

优点:环境干净,不会污染状态 缺点:请求之间不保留状态 使用场景:一次性代码执行、CI/CD、测试

按任务创建 Sandbox(幂等且可追踪)
const sandbox = getSandbox(env.Sandbox, `build-${repoName}-${commitSha}`);

优点:可复现、可调试、可缓存 缺点:需要明确的清理策略 使用场景:构建系统、数据管道、自动化工作流


核心 API 参考

获取 Sandbox
import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.Sandbox, 'unique-sandbox-id');
// Creates new sandbox if doesn't exist, or gets existing one
执行命令
// Basic execution
const result = await sandbox.exec('python3 script.py');
console.log(result.stdout);   // Standard output
console.log(result.stderr);   // Standard error
console.log(result.exitCode); // Exit code (0 = success)
console.log(result.success);  // Boolean (exitCode === 0)

// With options
const result = await sandbox.exec('npm install', {
  cwd: '/workspace/project',        // Working directory
  timeout: 120000,                   // Timeout in ms (default: 30s)
  session: sessionId,                // Session ID
  env: { NODE_ENV: 'production' }   // Environment variables
});

// Always check exit codes!
if (!result.success) {
  throw new Error(`Command failed: ${result.stderr}`);
}
文件操作
// Write file
await sandbox.writeFile('/workspace/data.txt', 'content');

// Read file
const content = await sandbox.readFile('/workspace/data.txt');

// Create directory
await sandbox.mkdir('/workspace/project', { recursive: true });

// List directory
const files = await sandbox.readdir('/workspace');
console.log(files); // ['data.txt', 'project']

// Delete file/directory
await sandbox.rm('/workspace/data.txt');
await sandbox.rm('/workspace/project', { recursive: true });
Git 操作
// Clone repository (optimized, faster than exec('git clone'))
await sandbox.gitCheckout(
  'https://github.com/user/repo',
  '/workspace/repo'
);

// Now use standard git commands
await sandbox.exec('git status', { cwd: '/workspace/repo' });
await sandbox.exec('git diff', { cwd: '/workspace/repo' });
代码解释器(类似 Jupyter)
// Create Python context
const ctx = await sandbox.createCodeContext({ language: 'python' });

// Execute code - last expression auto-returned
const result = await sandbox.runCode(`
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df['a'].sum()  # This value is automatically returned
`, { context: ctx });

console.log(result.results[0].text); // "6"
console.log(result.logs); // Output from print() statements
console.log(result.error); // Any errors
后台进程
// Start long-running process
const proc = await sandbox.spawn('python server.py');
console.log(proc.pid);

// Check if still running
const running = await sandbox.isProcessRunning(proc.pid);

// Kill process
await sandbox.killProcess(proc.pid);
清理
// Destroy sandbox permanently
await sandbox.destroy();
// All files deleted, container removed, cannot be recovered

重要规则

始终要做

✅ 检查退出代码 - if (!result.success) { handle error } ✅ 多步工作流使用会话 - 保留工作目录 ✅ 处理冷启动 - 先检查文件是否存在,不要直接假设文件已就位 ✅ 设置超时 - 避免长时间操作一直挂起 ✅ 销毁临时沙箱 - 清理临时/基于会话的沙箱 ✅ 使用外部存储实现持久化 - 重要数据存放在 R2/KV/D1 中 ✅ 验证用户输入 - 在调用 exec() 前进行清理,防止命令注入 ✅ 导出 Sandbox 类 - export { Sandbox } from '@cloudflare/sandbox'

绝不要做

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


已知问题预防

此技能可预防 10 个已记录的问题:

问题 #1:缺少 nodejs_compat 标志

错误:ReferenceError: fetch is not defined 或 Buffer is not defined 来源:https://developers.cloudflare.com/sandbox/get-started/ 原因:SDK 需要标准 Workers 中不可用的 Node.js API 预防措施:在 wrangler.jsonc 中添加 "compatibility_flags": ["nodejs_compat"]

问题 #2:缺少迁移

错误:Error: Class 'Sandbox' not found 来源:https://developers.cloudflare.com/durable-objects/ 原因:必须通过迁移注册 Durable Objects 预防措施:在 wrangler.jsonc 中加入 migrations 数组

问题 #3:误以为文件会持久保留

错误:闲置后文件消失 来源:https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器在闲置约 10 分钟后停止运行,所有状态都会重置 预防措施:使用外部存储(R2/KV),或在每次请求时检查文件是否存在

问题 #4:会话目录混淆

错误:命令在错误的目录中执行 来源:https://developers.cloudflare.com/sandbox/concepts/sessions/ 原因:除非明确指定会话,否则每次 exec() 都会使用新会话 预防措施:使用 createSession() 创建会话,并将其传递给所有相关命令

问题 #5:忽略退出代码

错误:命令失败却误以为成功 来源:Shell 最佳实践 原因:未检查 result.success 或 result.exitCode 预防措施:始终检查:if (!result.success) throw new Error(result.stderr)

问题 #6:未处理冷启动

错误:由于未安装依赖项,命令执行失败 来源:https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器在闲置一段时间后会重置 预防措施:执行命令前先检查是否需要进行设置

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

错误:本地开发期间出现 Failed to build container 来源:https://developers.cloudflare.com/sandbox/get-started/ 原因:本地开发需要 Docker 守护进程 预防措施:执行 npm run dev 前确保 Docker Desktop 正在运行

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

错误:API 方法不可用或行为异常 来源:GitHub 问题 原因:npm 包版本与 Docker 镜像版本不匹配 预防措施:确保 @cloudflare/sandbox 包与 cloudflare/sandbox 镜像版本同步

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

错误:资源耗尽、产生意外费用 来源:资源管理最佳实践 原因:创建沙箱后未销毁 预防措施:在 finally 块中对临时沙箱调用 await sandbox.destroy()

问题 #10:命令注入漏洞

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


配置文件参考

wrangler.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.4.12",
    "instance_type": "lite"
  }],

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

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

  "env": {
    "ANTHROPIC_API_KEY": {
      "description": "Optional: For AI features"
    }
  },

  "observability": {
    "enabled": true
  }
}

这些设置的用途:

  • nodejs_compat:SDK 正常运行所必需
  • containers.image:指定版本可确保一致性
  • instance_type: "lite":最小实例;如需更多资源,可升级到 "large"
  • migrations:注册 Sandbox Durable Object 类
  • observability:启用日志记录以便调试
Dockerfile(可选 — 用于本地开发)

仅在扩展基础镜像时需要:

FROM cloudflare/sandbox:0.4.12

# Install additional tools
RUN apt-get update && apt-get install -y \
    ffmpeg \
    imagemagick \
    && rm -rf /var/lib/apt/lists/*

# Expose port for preview URLs (local dev only)
EXPOSE 8080

常见模式

模式 1:一次性代码执行
export default {
  async fetch(request: Request, env: Env) {
    const { code, language } = await request.json();

    // Create ephemeral sandbox
    const sandboxId = `exec-${Date.now()}-${crypto.randomUUID()}`;
    const sandbox = getSandbox(env.Sandbox, sandboxId);

    try {
      // Create code context
      const ctx = await sandbox.createCodeContext({ language });

      // Execute code safely
      const result = await sandbox.runCode(code, {
        context: ctx,
        timeout: 10000
      });

      return Response.json({
        result: result.results?.[0]?.text,
        logs: result.logs,
        error: result.error
      });
    } finally {
      // Always cleanup
      await sandbox.destroy();
    }
  }
};

适用场景:代码执行 API 端点、代码练习场、学习平台

模式 2:持久化用户工作区
export default {
  async fetch(request: Request, env: Env) {
    const userId = request.headers.get('X-User-ID');
    const { command, sessionId: existingSession } = await request.json();

    // User-specific sandbox (persists while active)
    const sandbox = getSandbox(env.Sandbox, `user-${userId}`);

    // Get or create session
    let sessionId = existingSession;
    if (!sessionId) {
      sessionId = await sandbox.createSession();
    }

    // Execute command in persistent context
    const result = await sandbox.exec(command, {
      session: sessionId,
      timeout: 30000
    });

    return Response.json({
      sessionId, // Return for next request
      output: result.stdout,
      error: result.stderr,
      success: result.success
    });
  }
};

适用场景:交互式编码环境、笔记本、IDE、开发工作区

模式 3:CI/CD 构建流水线
async function runBuild(repoUrl: string, commit: string, env: Env) {
  const sandboxId = `build-${repoUrl.split('/').pop()}-${commit}`;
  const sandbox = getSandbox(env.Sandbox, sandboxId);

  try {
    // Clone repository
    await sandbox.gitCheckout(repoUrl, '/workspace/repo');

    // Checkout specific commit
    await sandbox.exec(`git checkout ${commit}`, {
      cwd: '/workspace/repo'
    });

    // Install dependencies
    const install = await sandbox.exec('npm install', {
      cwd: '/workspace/repo',
      timeout: 180000 // 3 minutes
    });

    if (!install.success) {
      throw new Error(`Install failed: ${install.stderr}`);
    }

    // Run build
    const build = await sandbox.exec('npm run build', {
      cwd: '/workspace/repo',
      timeout: 300000 // 5 minutes
    });

    if (!build.success) {
      throw new Error(`Build failed: ${build.stderr}`);
    }

    // Save artifacts to R2
    const dist = await sandbox.exec('tar -czf dist.tar.gz dist', {
      cwd: '/workspace/repo'
    });
    const artifact = await sandbox.readFile('/workspace/repo/dist.tar.gz');
    await env.R2.put(`builds/${commit}.tar.gz`, artifact);

    return { success: true, artifactKey: `builds/${commit}.tar.gz` };
  } finally {
    // Optional: Keep sandbox for debugging or destroy
    // await sandbox.destroy();
  }
}

适用场景:构建系统、测试流水线、部署自动化

模式 4:使用 Claude Code 的 AI Agent
async function runClaudeCodeOnRepo(
  repoUrl: string,
  task: string,
  env: Env
): Promise<{ diff: string; logs: string }> {
  const sandboxId = `claude-${Date.now()}`;
  const sandbox = getSandbox(env.Sandbox, sandboxId);

  try {
    // Clone repository
    await sandbox.gitCheckout(repoUrl, '/workspace/repo');

    // Run Claude Code CLI with secure environment injection
    // ⚠️ SECURITY: Use env option instead of shell export to prevent key exposure in logs
    const result = await sandbox.exec(
      `claude -p "${task}" --permission-mode acceptEdits`,
      {
        cwd: '/workspace/repo',
        timeout: 300000, // 5 minutes
        env: {
          ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY
        }
      }
    );

    // Get diff of changes
    const diff = await sandbox.exec('git diff', {
      cwd: '/workspace/repo'
    });

    return {
      diff: diff.stdout,
      logs: result.stdout
    };
  } finally {
    await sandbox.destroy();
  }
}

适用场景:自动化代码重构、代码生成、AI 驱动的开发


使用捆绑资源

脚本(scripts/)
  • setup-sandbox-binding.sh - 交互式配置 wrangler.jsonc
  • test-sandbox.ts - 用于测试 Sandbox 设置的验证脚本

使用示例:

# Setup wrangler config
./scripts/setup-sandbox-binding.sh

# Test sandbox
npx tsx scripts/test-sandbox.ts
参考资料(references/)
  • references/persistence-guide.md - 深入介绍容器生命周期和持久化
  • references/session-management.md - 高级会话模式和最佳实践
  • references/common-errors.md - 错误完整列表及解决方案
  • references/naming-strategies.md - 为不同用例选择 Sandbox ID

Claude 应在以下情况加载这些资料:

  • 调试状态问题或冷启动时,加载 persistence-guide.md
  • 构建多步骤工作流或聊天 Agent 时,加载 session-management.md
  • 遇到特定错误时,加载 common-errors.md
  • 设计 Sandbox 架构时,加载 naming-strategies.md

高级主题

地理分布

对某个 Sandbox ID 的首次请求会决定其地理位置(通过 Durable Objects)。

面向全球应用:

// Option 1: Multiple sandboxes per user (better latency)
const region = request.cf?.colo || 'default';
const sandbox = getSandbox(env.Sandbox, `user-${userId}-${region}`);

// Option 2: Single sandbox (simpler, higher latency for distant users)
const sandbox = getSandbox(env.Sandbox, `user-${userId}`);
错误处理策略
async function safeSandboxExec(
  sandbox: Sandbox,
  cmd: string,
  options?: any
) {
  try {
    const result = await sandbox.exec(cmd, {
      ...options,
      timeout: options?.timeout || 30000
    });

    if (!result.success) {
      console.error(`Command failed: ${cmd}`, {
        exitCode: result.exitCode,
        stderr: result.stderr
      });

      return {
        success: false,
        error: result.stderr,
        exitCode: result.exitCode
      };
    }

    return {
      success: true,
      output: result.stdout,
      exitCode: 0
    };
  } catch (error) {
    console.error(`Sandbox error:`, error);
    return {
      success: false,
      error: error.message,
      exitCode: -1
    };
  }
}
安全加固
// Input validation
function sanitizeCommand(input: string): string {
  const dangerous = ['rm -rf', '$(', '`', '&&', '||', ';', '|'];
  for (const pattern of dangerous) {
    if (input.includes(pattern)) {
      throw new Error(`Dangerous pattern detected: ${pattern}`);
    }
  }
  return input;
}

// Use code interpreter instead of direct exec for untrusted code
async function executeUntrustedCode(code: string, sandbox: Sandbox) {
  const ctx = await sandbox.createCodeContext({ language: 'python' });
  return await sandbox.runCode(code, { context: ctx, timeout: 10000 });
}

依赖项

必需:

  • @cloudflare/[email protected] - Sandbox SDK
  • wrangler@latest - 部署 CLI
  • Docker Desktop - 仅用于本地开发

可选:

  • @anthropic-ai/sdk - 用于 AI 功能
  • @cloudflare/workers-types - TypeScript 类型

官方文档


软件包版本(已于 2025-10-29 验证)

{
  "dependencies": {
    "@cloudflare/sandbox": "^0.4.12"
  },
  "devDependencies": {
    "wrangler": "^3.80.0",
    "@cloudflare/workers-types": "^4.20241106.0"
  }
}

Docker 镜像:cloudflare/sandbox:0.4.12


生产示例

此技能基于 Cloudflare 官方教程:


故障排除

问题:"Class 'Sandbox' not found"

解决方案:将 migrations 添加到 wrangler.jsonc,并确保在 Worker 中包含 export { Sandbox }

问题:文件过一段时间后消失

解决方案:容器在空闲约 10 分钟后会停止。使用 R2/KV 持久化数据,或重建环境

问题:命令在错误的目录中执行

解决方案:使用 createSession() 创建会话,并将 sessionId 传递给所有相关命令

问题:本地开发期间出现 Docker 错误

解决方案:运行 npm run dev 之前,确保 Docker Desktop 正在运行

问题:"fetch is not defined"

解决方案:将 "compatibility_flags": ["nodejs_compat"] 添加到 wrangler.jsonc


完整设置清单

  • npm install @cloudflare/sandbox@latest
  • 将 nodejs_compat 添加到 compatibility_flags
  • 添加带有正确镜像版本的容器配置
  • 添加 Durable Objects 绑定
  • 为 Sandbox 类添加迁移
  • 在 Worker 中导出 Sandbox 类:export { Sandbox } from '@cloudflare/sandbox'
  • Docker Desktop 正在运行(仅限本地开发)
  • 使用简单的 exec 命令进行测试
  • 验证是否检查了退出代码
  • 为临时沙盒实现清理机制
  • 测试冷启动行为

有问题?遇到故障?

  1. 查看 references/common-errors.md,了解特定错误的解决方案
  2. 检查 wrangler.jsonc 配置中的所有步骤
  3. 查看官方文档:https://developers.cloudflare.com/sandbox/
  4. 确保本地开发时 Docker 正在运行
  5. 确认软件包版本与 Docker 镜像版本一致

评论

支持 Markdown