创建并管理 sandbox 容器。获取 sandbox 实例、配置选项并清理资源。
按 ID 获取或创建 sandbox 实例。
const sandbox = getSandbox(
binding: DurableObjectNamespace<Sandbox>,
sandboxId: string,
options?: SandboxOptions
): Sandbox参数:
binding- 来自 Worker 环境的 Durable Object 命名空间绑定(binding)sandboxId- 此 sandbox 的唯一标识符。相同 ID 始终返回同一 sandbox 实例。在面向用户的应用中,请将 ID 限定到单个用户。options(可选)- 有关所有可用选项,请参阅 SandboxOptions:enableDefaultSession- 对未显式指定sessionId的操作使用默认会话。设为false可让每次调用在隔离环境中评估(默认:true)sleepAfter- 不活动后自动休眠的时长(默认:"10m")keepAlive- 完全阻止自动休眠。在休眠期间也会保持(默认:false)containerTimeouts- 配置容器启动超时normalizeId- 将 sandbox ID 转为小写,以兼容预览 URL(默认:false)
返回:Sandbox 实例
import { getSandbox } from "@cloudflare/sandbox";
export default {
async fetch(request, env) {
const sandbox = getSandbox(env.Sandbox, "user-123");
const result = await sandbox.exec("python script.py");
return Response.json(result);
},
};import { getSandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python script.py');
return Response.json(result);
}
};在创建 sandbox 后动态启用或禁用 keepAlive 模式。
await sandbox.setKeepAlive(keepAlive: boolean): Promise<void>参数:
keepAlive-true阻止自动休眠,false允许正常休眠行为
启用后,sandbox 会每 30 秒自动发送心跳 ping,以防止容器被驱逐。禁用后,sandbox 会根据 sleepAfter 配置恢复正常休眠行为。
const sandbox = getSandbox(env.Sandbox, "user-123");
// Enable keepAlive for a long-running process
await sandbox.setKeepAlive(true);
await sandbox.startProcess("python long_running_analysis.py");
// Later, disable keepAlive when done
await sandbox.setKeepAlive(false);const sandbox = getSandbox(env.Sandbox, 'user-123');
// Enable keepAlive for a long-running process
await sandbox.setKeepAlive(true);
await sandbox.startProcess('python long_running_analysis.py');
// Later, disable keepAlive when done
await sandbox.setKeepAlive(false);销毁 sandbox 容器并释放资源。
await sandbox.destroy(): Promise<void>立即终止容器并永久删除所有状态:
/workspace、/tmp与/home中的所有文件- 所有正在运行的进程
- 所有会话(包括默认会话)
- 网络连接与已暴露的端口
async function executeCode(code) {
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
try {
await sandbox.writeFile("/tmp/code.py", code);
const result = await sandbox.exec("python /tmp/code.py");
return result.stdout;
} finally {
await sandbox.destroy();
}
}async function executeCode(code: string): Promise<string> {
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
try {
await sandbox.writeFile('/tmp/code.py', code);
const result = await sandbox.exec('python /tmp/code.py');
return result.stdout;
} finally {
await sandbox.destroy();
}
}- Sandbox 生命周期概念 - 了解容器生命周期与状态
- Sandbox 选项配置 - 配置
keepAlive及其他选项 - Sessions API - 在 sandbox 内创建执行上下文