celld中文文档v0.6.2
GitHub ↗
文档 / 入门与运行

sandbox 示例源码

这些文件来自仓库的 examples/sandbox,可结合对应中文文档阅读和运行。

wrangler.jsonc

json
{
  "name": "sandbox",
  "main": "index.js",
  "compatibility_date": "2026-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "containers": [
    {
      "class_name": "Sandbox",
      "image": "./Dockerfile",
      "instance_type": "basic",
      "max_instances": 4
    }
  ],
  "durable_objects": {
    "bindings": [{ "name": "Sandbox", "class_name": "Sandbox" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Sandbox"] }]
}

package.json

plaintext
{
  "name": "celld-sandbox-example",
  "private": true,
  "type": "module",
  "dependencies": {
    "@cloudflare/sandbox": "0.12.9"
  }
}

index.js

javascript
import { getSandbox, Sandbox } from "@cloudflare/sandbox";

export { Sandbox };

// One sandbox per `id`: a Linux environment with a shell, a filesystem,
// and background processes, supervised by the Durable Object.
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const sandbox = getSandbox(env.Sandbox, url.searchParams.get("id") ?? "demo");
    switch (url.pathname) {
      case "/exec": {
        const command = url.searchParams.get("cmd") ?? "uname -a";
        const result = await sandbox.exec(command);
        return Response.json({
          stdout: result.stdout,
          stderr: result.stderr,
          exitCode: result.exitCode,
        });
      }
      case "/write": {
        await sandbox.writeFile("/workspace/note.txt", `written at ${new Date().toISOString()}\n`);
        const file = await sandbox.readFile("/workspace/note.txt");
        return Response.json({ content: file.content });
      }
      case "/serve": {
        // A background process that outlives this request: a small HTTP
        // server. It uses node, which the Sandbox image ships, rather than a
        // language the image may not carry.
        const process = await sandbox.startProcess(
          `node -e "require('http').createServer((_req, res) => res.end('served from the sandbox')).listen(8787, '0.0.0.0')"`,
        );
        return Response.json({ id: process.id, status: process.status });
      }
      case "/processes": {
        const list = await sandbox.listProcesses();
        return Response.json(list.map((process) => ({ id: process.id, status: process.status })));
      }
      default:
        return new Response(
          "Try /exec?cmd=..., /write, /serve, or /processes, with ?id=<sandbox>\n",
          { headers: { "content-type": "text/plain" } },
        );
    }
  },
};

Dockerfile

dockerfile
# The Cloudflare Sandbox SDK image: a control server on port 3000 that the
# `@cloudflare/sandbox` package drives. Keep the tag and the package version
# on the same release line.
FROM docker.io/cloudflare/sandbox:0.12.9
EXPOSE 3000
celld v0.6.2 · 简体中文文档
产品名、API、命令与示例代码保留原始写法。

输入关键词,搜索 20 篇中文文档。

支持中文术语、API 与环境变量 · Esc 关闭