构建安全、隔离的代码执行环境
Sandbox SDK 让你可以在隔离环境中安全运行不受信任的代码。它构建于 Containers 之上,提供简洁 API,用于执行命令、管理文件、运行后台进程并暴露服务——全部从你的 Workers 应用完成。
Sandbox 非常适合构建需要执行代码的 AI Agent、交互式开发环境、数据分析平台、CI/CD 系统,以及任何需要在边缘安全执行代码的应用。每个 sandbox 都在独立的隔离 container 中运行,具备完整 Linux 环境,在保持性能的同时提供强安全边界。
使用 Sandbox,你可以执行 Python 脚本、运行 Node.js 应用、分析数据、编译代码并执行复杂计算——全部通过简洁的 TypeScript API 完成,无需管理基础设施。
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
// Execute a command and get the result
const result = await sandbox.exec('python --version');
return Response.json({
output: result.stdout,
exitCode: result.exitCode,
success: result.success
});
}
};import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
// Create a Python execution context
const ctx = await sandbox.createCodeContext({ language: 'python' });
// Execute Python code with automatic result capture
const result = await sandbox.runCode(`
import pandas as pd
data = {'product': ['A', 'B', 'C'], 'sales': [100, 200, 150]}
df = pd.DataFrame(data)
df['sales'].sum() # Last expression is automatically returned
`, { context: ctx });
return Response.json({
result: result.results?.[0]?.text,
logs: result.logs
});
}
};import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
// Create a project structure
await sandbox.mkdir('/workspace/project/src', { recursive: true });
// Write files
await sandbox.writeFile(
'/workspace/project/package.json',
JSON.stringify({ name: 'my-app', version: '1.0.0' })
);
// Read a file back
const content = await sandbox.readFile('/workspace/project/package.json');
return Response.json({ content });
}
};import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
// Watch for file changes in real-time
const watcher = await sandbox.watch('/workspace/src', {
include: ['*.js', '*.ts'],
onEvent: (event) => {
console.log(`${event.type}: ${event.path}`);
if (event.type === 'modify') {
// Trigger rebuild or hot reload
console.log('Code changed, recompiling...');
}
},
onError: (error) => {
console.error('Watch error:', error);
}
});
// Stop watching when done
setTimeout(() => watcher.stop(), 60000);
return Response.json({ message: 'File watcher started' });
}
};import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// Terminal WebSocket connection
if (url.pathname === '/ws/terminal') {
const sandbox = getSandbox(env.Sandbox, 'user-123');
return sandbox.terminal(request, { cols: 80, rows: 24 });
}
return Response.json({ message: 'Terminal endpoint' });
}
};通过 WebSocket 将浏览器终端直接连接到 sandbox shell。了解更多:浏览器终端。
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Connect to WebSocket services in sandbox
if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') {
const sandbox = getSandbox(env.Sandbox, 'user-123');
return await sandbox.wsConnect(request, 8080);
}
return Response.json({ message: 'WebSocket endpoint' });
}
};连接到 sandbox 中运行的 WebSocket server。了解更多:WebSocket 连接。
快速入门
API 参考
运行 shell 命令、Python 脚本、Node.js 应用等,支持流式输出与自动超时处理。
在 sandbox 文件系统中读取、写入和操作文件。运行后台进程、监控输出并管理长时间运行的操作。
为 sandbox 中运行的 HTTP 服务自动生成 Preview URL,非常适合交互式开发环境与应用托管。
执行 Python 与 JavaScript 代码,获得图表、表格与图片等丰富输出。在多次执行之间保持持久 state,适用于 AI 生成代码与交互式工作流。
创建基于浏览器的终端界面,通过 WebSocket 直接连接 sandbox shell。构建协作终端、交互式开发环境,并支持自动重连的实时 shell 访问。
将 S3 兼容对象存储(R2、S3、GCS 等)挂载为本地文件系统。使用标准文件操作访问 bucket,数据在 sandbox 生命周期内持久保留。需要生产环境部署。
使用原生文件系统事件监视文件与目录变更。非常适合构建热重载开发 server、构建自动化系统与配置监控工具。
将凭据保留在 Worker 中,同时允许 sandbox 访问外部 API。Worker 代理验证来自 sandbox 的短期 JWT token,并在请求时注入真实凭据。
使用 Sandbox 构建强大应用:
安全可靠地执行大语言模型生成的代码。与 Workers AI 模型(如 GPT-OSS)的原生集成支持 function calling 与 sandbox 执行。非常适合需要运行不受信任代码的 AI Agent、代码助手与自主系统。
使用 pandas、NumPy 与 Matplotlib 创建交互式数据分析环境。生成图表、表格与可视化,并自动格式化丰富输出。
构建云 IDE、编码 playground 与协作开发工具,提供完整 Linux 环境与 Preview URL。
在隔离环境中运行测试、编译代码并执行构建流水线,支持并行执行与流式日志。
为 Sandbox 提供动力的无服务器 container 运行时,使你可以在边缘运行任何 container 化工作负载。
在网络上运行机器学习模型与 LLM。与 Sandbox 结合,实现安全的 AI 代码执行工作流。
有状态协调层,使 Sandbox 能够维护具强一致性的持久环境。