在使用 getSandbox() 创建沙箱实例时传入选项,以配置沙箱行为。
import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(binding, sandboxId, options?: SandboxOptions);类型:boolean
默认值:true
控制在没有显式 sessionId 的情况下调用沙箱方法时发生的情况。为 true 时,隐式操作使用沙箱的默认会话,并在调用之间保留 shell 状态。为 false 时,隐式操作以隔离方式运行,除非你显式指定会话,否则不会继承先前调用的 shell 状态。
对交互式或有状态工作流(命令应共享工作目录与已导出变量)使用 enableDefaultSession: true。对无状态请求处理(一次调用不应影响下一次)使用 enableDefaultSession: false。建议将此设为 false——默认会话支持将在未来版本的 Sandbox SDK 中移除,显式使用 createSession() 是今后的首选模式。
// Default behavior: implicit operations use the default session
const statefulSandbox = getSandbox(env.Sandbox, "user-123");
await statefulSandbox.exec("cd /workspace/app");
const statefulResult = await statefulSandbox.exec("pwd");
// statefulResult.stdout: "/workspace/app"
// The second exec inherited the working directory from the first.
// Sessionless behavior: implicit operations do not share shell state
const statelessSandbox = getSandbox(env.Sandbox, "api-worker", {
enableDefaultSession: false,
});
await statelessSandbox.exec("cd /workspace/app");
const statelessResult = await statelessSandbox.exec("pwd");
// statelessResult.stdout: "/workspace"
// The second exec did not inherit shell state from the first.// Default behavior: implicit operations use the default session
const statefulSandbox = getSandbox(env.Sandbox, 'user-123');
await statefulSandbox.exec('cd /workspace/app');
const statefulResult = await statefulSandbox.exec('pwd');
// statefulResult.stdout: "/workspace/app"
// The second exec inherited the working directory from the first.
// Sessionless behavior: implicit operations do not share shell state
const statelessSandbox = getSandbox(env.Sandbox, 'api-worker', {
enableDefaultSession: false
});
await statelessSandbox.exec('cd /workspace/app');
const statelessResult = await statelessSandbox.exec('pwd');
// statelessResult.stdout: "/workspace"
// The second exec did not inherit shell state from the first.类型:boolean
默认值:false
通过阻止自动关闭使容器无限期保持存活。为 true 时,容器每 30 秒自动发送心跳 ping 以防止被驱逐,且永远不会自动超时。
工作原理:沙箱每 30 秒自动调度对容器的轻量级 ping 请求。这可在最小化资源开销的同时防止容器因不活动而被驱逐。你也可以使用 setKeepAlive() 动态启用/禁用 keepAlive。
keepAlive 标志在 Durable Object 休眠与唤醒周期中保持。一旦启用,你无需在沙箱从休眠唤醒后重新设置它。
// For long-running processes that need the container to stay alive
const sandbox = getSandbox(env.Sandbox, "user-123", {
keepAlive: true,
});
// Run your long-running process
await sandbox.startProcess("python long_running_script.py");
// 重要:完成后必须显式销毁
try {
// Your work here
} finally {
await sandbox.destroy(); // Required to prevent containers running indefinitely
}// For long-running processes that need the container to stay alive
const sandbox = getSandbox(env.Sandbox, 'user-123', {
keepAlive: true
});
// Run your long-running process
await sandbox.startProcess('python long_running_script.py');
// 重要:完成后必须显式销毁
try {
// Your work here
} finally {
await sandbox.destroy(); // Required to prevent containers running indefinitely
}类型:string | number
默认值:"10m"(10 分钟)
沙箱在不活动后自动休眠前的持续时间。接受持续时间字符串("30s"、"5m"、"1h")或数字(秒)。
// Sleep after 30 seconds of inactivity
const sandbox = getSandbox(env.Sandbox, "user-123", {
sleepAfter: "30s",
});
// Sleep after 5 minutes (using number)
const sandbox2 = getSandbox(env.Sandbox, "user-456", {
sleepAfter: 300, // 300 seconds = 5 minutes
});// Sleep after 30 seconds of inactivity
const sandbox = getSandbox(env.Sandbox, 'user-123', {
sleepAfter: '30s'
});
// Sleep after 5 minutes (using number)
const sandbox2 = getSandbox(env.Sandbox, 'user-456', {
sleepAfter: 300 // 300 seconds = 5 minutes
});类型:object
配置容器启动操作的超时。
// Extended startup with custom Dockerfile work
// (installing packages, starting services before SDK)
const sandbox = getSandbox(env.Sandbox, "data-processor", {
containerTimeouts: {
portReadyTimeoutMS: 180_000, // 3 minutes for startup work
},
});
// Wait longer during traffic spikes
const sandbox2 = getSandbox(env.Sandbox, "user-env", {
containerTimeouts: {
instanceGetTimeoutMS: 60_000, // 1 minute for provisioning
},
});// Extended startup with custom Dockerfile work
// (installing packages, starting services before SDK)
const sandbox = getSandbox(env.Sandbox, 'data-processor', {
containerTimeouts: {
portReadyTimeoutMS: 180_000 // 3 minutes for startup work
}
});
// Wait longer during traffic spikes
const sandbox2 = getSandbox(env.Sandbox, 'user-env', {
containerTimeouts: {
instanceGetTimeoutMS: 60_000 // 1 minute for provisioning
}
});可用超时选项:
instanceGetTimeoutMS— 等待 Cloudflare 预配新容器实例的时长。在许多容器同时预配的流量高峰期间可增加此值。默认值:30000(30 秒)portReadyTimeoutMS— 等待沙箱 API 就绪的时长。如果你用自定义启动工作(安装软件包、启动服务)扩展基础 Dockerfile,可增加此值。默认值:90000(90 秒)
环境变量覆盖:
SANDBOX_INSTANCE_TIMEOUT_MS— 覆盖instanceGetTimeoutMSSANDBOX_PORT_TIMEOUT_MS— 覆盖portReadyTimeoutMS
优先级:options > env vars > SDK 默认值
类型:环境变量
控制 SDK 日志记录以进行调试与监控。在 Worker 的 wrangler.jsonc 文件中设置这些变量。
可用选项:
SANDBOX_LOG_LEVEL— 最低日志级别:debug、info、warn、error。默认值:infoSANDBOX_LOG_FORMAT— 输出格式:json、pretty。默认值:json
{
"vars": {
"SANDBOX_LOG_LEVEL": "debug",
"SANDBOX_LOG_FORMAT": "pretty"
}
}[vars]
SANDBOX_LOG_LEVEL = "debug"
SANDBOX_LOG_FORMAT = "pretty"本地开发使用 debug + pretty。生产环境使用 info 或 warn + json(结构化日志)。
类型:boolean
默认值:false(在未来版本中将成为 true)
创建沙箱时将沙箱 ID 转为小写。为 true 时,你提供的 ID 在创建 Durable Object 之前会转为小写(例如 "MyProject-123" → "myproject-123")。
为何重要:预览 URL 从主机名提取沙箱 ID,由于 DNS 不区分大小写,主机名始终为小写。如果不规范化,使用 "MyProject-123" 创建的沙箱会因 URL 路由查找 "myproject-123"(不同的 Durable Object)而无法通过预览 URL 访问。
// Without normalization (default)
const sandbox1 = getSandbox(env.Sandbox, "MyProject-123");
// Creates Durable Object with ID: "MyProject-123"
// Preview URL: 8000-myproject-123.example.com
// Problem: URL routes to "myproject-123" (different DO)
// With normalization
const sandbox2 = getSandbox(env.Sandbox, "MyProject-123", {
normalizeId: true,
});
// Creates Durable Object with ID: "myproject-123"
// Preview URL: 8000-myproject-123.example.com
// Works: URL routes to "myproject-123" (same DO)// Without normalization (default)
const sandbox1 = getSandbox(env.Sandbox, 'MyProject-123');
// Creates Durable Object with ID: "MyProject-123"
// Preview URL: 8000-myproject-123.example.com
// Problem: URL routes to "myproject-123" (different DO)
// With normalization
const sandbox2 = getSandbox(env.Sandbox, 'MyProject-123', {
normalizeId: true
});
// Creates Durable Object with ID: "myproject-123"
// Preview URL: 8000-myproject-123.example.com
// Works: URL routes to "myproject-123" (same DO)在以下情况使用 normalizeId: true:
- 使用预览 URL — 如果 ID 包含大写字母,端口暴露需要此选项
- 新项目 — 启用此选项,或从一开始就使用小写 ID(两者皆可)
- 迁移现有代码 — 在启用此选项的情况下创建新沙箱;旧的大写沙箱最终会被销毁(显式销毁或超时后)
最佳实践:从一开始就使用小写 ID('my-project-123' 而不是 'MyProject-123')。
使用自定义 sleepAfter 值可以:
- 降低成本 — 对不频繁的工作负载使用较短超时(例如
"1m") - 延长可用性 — 对交互式工作流使用较长超时(例如
"30m") - 平衡性能 — 根据应用的使用模式进行微调
默认的 10 分钟超时适用于大多数应用。请根据需求调整。
对以下情况使用 keepAlive: true:
- 长时间运行的构建 — 步骤之间可能有空闲期的 CI/CD 流水线
- 批处理 — 以批次处理数据且批次之间有间隔的作业
- 监控任务 — 定期检查外部服务的进程
- 交互式会话 — 容器应保持可用的用户驱动工作流
使用 keepAlive 时,容器每 30 秒发送自动心跳 ping 以防止被驱逐,且永远不会自动休眠。适用于你显式控制生命周期的场景。