本指南说明如何通过预览 URL 将 sandbox 中运行的服务暴露到互联网。
在以下情况下暴露端口:
- 测试 Web 应用 - 预览前端或后端应用
- 分享演示 - 让他人访问正在运行的应用
- 开发 API - 从外部工具测试端点
- 调试服务 - 访问内部服务以进行故障排除
- 构建开发环境 - 创建可分享的开发工作区
典型工作流为:启动服务 → 等待就绪 → 暴露端口 → 使用 proxyToSandbox 处理请求。
import { getSandbox, proxyToSandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";
export default {
async fetch(request, env) {
// Proxy requests to exposed ports first
const proxyResponse = await proxyToSandbox(request, env);
if (proxyResponse) return proxyResponse;
// Extract hostname from request
const { hostname } = new URL(request.url);
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// 1. Start a web server
await sandbox.startProcess("python -m http.server 8000");
// 2. Wait for service to start
await new Promise((resolve) => setTimeout(resolve, 2000));
// 3. Expose the port
const exposed = await sandbox.exposePort(8000, { hostname });
// 4. Preview URL is now available (public by default)
console.log("Server accessible at:", exposed.url);
// Production: https://8000-abc123.yourdomain.com
// Local dev: http://localhost:8787/...
return Response.json({ url: exposed.url });
},
};import { getSandbox, proxyToSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Proxy requests to exposed ports first
const proxyResponse = await proxyToSandbox(request, env);
if (proxyResponse) return proxyResponse;
// Extract hostname from request
const { hostname } = new URL(request.url);
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// 1. Start a web server
await sandbox.startProcess('python -m http.server 8000');
// 2. Wait for service to start
await new Promise(resolve => setTimeout(resolve, 2000));
// 3. Expose the port
const exposed = await sandbox.exposePort(8000, { hostname });
// 4. Preview URL is now available (public by default)
console.log('Server accessible at:', exposed.url);
// Production: https://8000-abc123.yourdomain.com
// Local dev: http://localhost:8787/...
return Response.json({ url: exposed.url });
}
};对于生产部署或需要与用户分享 URL 的场景,使用自定义 token 可在容器重启后保持预览 URL 一致:
// Extract hostname from request
const { hostname } = new URL(request.url);
// Without custom token - URL changes on restart
const exposed = await sandbox.exposePort(8080, { hostname });
// https://8080-sandbox-id-random16chars12.yourdomain.com
// With custom token - URL stays the same across restarts
const stable = await sandbox.exposePort(8080, {
hostname,
token: "api-v1",
});
// https://8080-sandbox-id-api-v1.yourdomain.com
// Same URL after container restart ✓
return Response.json({
"Temporary URL (changes on restart)": exposed.url,
"Stable URL (consistent)": stable.url,
});// Extract hostname from request
const { hostname } = new URL(request.url);
// Without custom token - URL changes on restart
const exposed = await sandbox.exposePort(8080, { hostname });
// https://8080-sandbox-id-random16chars12.yourdomain.com
// With custom token - URL stays the same across restarts
const stable = await sandbox.exposePort(8080, {
hostname,
token: 'api-v1'
});
// https://8080-sandbox-id-api-v1.yourdomain.com
// Same URL after container restart ✓
return Response.json({
'Temporary URL (changes on restart)': exposed.url,
'Stable URL (consistent)': stable.url
});Token 要求:
- 长度为 1–16 个字符
- 仅限小写字母 (a-z)、数字 (0-9)、连字符 (-) 和下划线 (_)
- 在每个 sandbox 内必须唯一
用例:
- 具有稳定端点的生产 API
- 与外部用户分享演示 URL
- 使用可预测 URL 的集成测试
- 带一致示例的文档
暴露多个端口时,使用名称以保持条理:
// Extract hostname from request
const { hostname } = new URL(request.url);
// Start and expose API server with stable token
await sandbox.startProcess("node api.js", { env: { PORT: "8080" } });
await new Promise((resolve) => setTimeout(resolve, 2000));
const api = await sandbox.exposePort(8080, {
hostname,
name: "api",
token: "api-prod",
});
// Start and expose frontend with stable token
await sandbox.startProcess("npm run dev", { env: { PORT: "5173" } });
await new Promise((resolve) => setTimeout(resolve, 2000));
const frontend = await sandbox.exposePort(5173, {
hostname,
name: "frontend",
token: "web-app",
});
console.log("Services:");
console.log("- API:", api.url);
console.log("- Frontend:", frontend.url);// Extract hostname from request
const { hostname } = new URL(request.url);
// Start and expose API server with stable token
await sandbox.startProcess('node api.js', { env: { PORT: '8080' } });
await new Promise(resolve => setTimeout(resolve, 2000));
const api = await sandbox.exposePort(8080, {
hostname,
name: 'api',
token: 'api-prod'
});
// Start and expose frontend with stable token
await sandbox.startProcess('npm run dev', { env: { PORT: '5173' } });
await new Promise(resolve => setTimeout(resolve, 2000));
const frontend = await sandbox.exposePort(5173, {
hostname,
name: 'frontend',
token: 'web-app'
});
console.log('Services:');
console.log('- API:', api.url);
console.log('- Frontend:', frontend.url);暴露前务必确认服务已就绪。大多数情况下使用简单延迟即可:
// Extract hostname from request
const { hostname } = new URL(request.url);
// Start service
await sandbox.startProcess("npm run dev", { env: { PORT: "8080" } });
// Wait 2-3 seconds
await new Promise((resolve) => setTimeout(resolve, 2000));
// Now expose
await sandbox.exposePort(8080, { hostname });// Extract hostname from request
const { hostname } = new URL(request.url);
// Start service
await sandbox.startProcess('npm run dev', { env: { PORT: '8080' } });
// Wait 2-3 seconds
await new Promise(resolve => setTimeout(resolve, 2000));
// Now expose
await sandbox.exposePort(8080, { hostname });对于关键服务,轮询健康检查端点:
// Extract hostname from request
const { hostname } = new URL(request.url);
await sandbox.startProcess("node api-server.js", { env: { PORT: "8080" } });
// Wait for health check
for (let i = 0; i < 10; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const check = await sandbox.exec(
'curl -f http://localhost:8080/health || echo "not ready"',
);
if (check.stdout.includes("ok")) {
break;
}
}
await sandbox.exposePort(8080, { hostname });// Extract hostname from request
const { hostname } = new URL(request.url);
await sandbox.startProcess('node api-server.js', { env: { PORT: '8080' } });
// Wait for health check
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
const check = await sandbox.exec('curl -f http://localhost:8080/health || echo "not ready"');
if (check.stdout.includes('ok')) {
break;
}
}
await sandbox.exposePort(8080, { hostname });为全栈应用暴露多个端口:
// Extract hostname from request
const { hostname } = new URL(request.url);
// Start backend
await sandbox.startProcess("node api/server.js", {
env: { PORT: "8080" },
});
await new Promise((resolve) => setTimeout(resolve, 2000));
// Start frontend
await sandbox.startProcess("npm run dev", {
cwd: "/workspace/frontend",
env: { PORT: "5173", API_URL: "http://localhost:8080" },
});
await new Promise((resolve) => setTimeout(resolve, 3000));
// Expose both
const api = await sandbox.exposePort(8080, { hostname, name: "api" });
const frontend = await sandbox.exposePort(5173, { hostname, name: "frontend" });
return Response.json({
api: api.url,
frontend: frontend.url,
});// Extract hostname from request
const { hostname } = new URL(request.url);
// Start backend
await sandbox.startProcess('node api/server.js', {
env: { PORT: '8080' }
});
await new Promise(resolve => setTimeout(resolve, 2000));
// Start frontend
await sandbox.startProcess('npm run dev', {
cwd: '/workspace/frontend',
env: { PORT: '5173', API_URL: 'http://localhost:8080' }
});
await new Promise(resolve => setTimeout(resolve, 3000));
// Expose both
const api = await sandbox.exposePort(8080, { hostname, name: 'api' });
const frontend = await sandbox.exposePort(5173, { hostname, name: 'frontend' });
return Response.json({
api: api.url,
frontend: frontend.url
});const { ports, count } = await sandbox.getExposedPorts();
console.log(`${count} ports currently exposed:`);
for (const port of ports) {
console.log(` Port ${port.port}: ${port.url}`);
if (port.name) {
console.log(` Name: ${port.name}`);
}
}const { ports, count } = await sandbox.getExposedPorts();
console.log(`${count} ports currently exposed:`);
for (const port of ports) {
console.log(` Port ${port.port}: ${port.url}`);
if (port.name) {
console.log(` Name: ${port.name}`);
}
}// Unexpose a single port
await sandbox.unexposePort(8000);
// Unexpose multiple ports
for (const port of [3000, 5173, 8080]) {
await sandbox.unexposePort(port);
}// Unexpose a single port
await sandbox.unexposePort(8000);
// Unexpose multiple ports
for (const port of [3000, 5173, 8080]) {
await sandbox.unexposePort(port);
}- 等待就绪 - 不要在启动进程后立即暴露端口
- 使用命名端口 - 暴露多个端口时更易跟踪
- 及时清理 - 完成后取消暴露端口,防止遗留 URL
- 添加身份验证 - 预览 URL 是公开的;保护敏感服务
使用 wrangler dev 进行本地开发时,必须在 Dockerfile 中暴露端口:
FROM docker.io/cloudflare/sandbox:0.3.3
# Expose ports you plan to use
EXPOSE 8000
EXPOSE 8080
EXPOSE 5173更新 wrangler.jsonc 以使用你的 Dockerfile:
{
"containers": [
{
"class_name": "Sandbox",
"image": "./Dockerfile"
}
]
}在生产环境中,所有端口均可用,并通过 exposePort() / unexposePort() 以编程方式控制。
端口 3000 由内部 Bun 服务器使用,无法暴露:
// Extract hostname from request
const { hostname } = new URL(request.url);
// ❌ This will fail
await sandbox.exposePort(3000, { hostname }); // Error: Port 3000 is reserved
// ✅ Use a different port
await sandbox.startProcess("node server.js", { env: { PORT: "8080" } });
await sandbox.exposePort(8080, { hostname });// Extract hostname from request
const { hostname } = new URL(request.url);
// ❌ This will fail
await sandbox.exposePort(3000, { hostname }); // Error: Port 3000 is reserved
// ✅ Use a different port
await sandbox.startProcess('node server.js', { env: { PORT: '8080' } });
await sandbox.exposePort(8080, { hostname });暴露前等待服务启动:
// Extract hostname from request
const { hostname } = new URL(request.url);
await sandbox.startProcess("npm run dev");
await new Promise((resolve) => setTimeout(resolve, 3000));
await sandbox.exposePort(8080, { hostname });// Extract hostname from request
const { hostname } = new URL(request.url);
await sandbox.startProcess('npm run dev');
await new Promise(resolve => setTimeout(resolve, 3000));
await sandbox.exposePort(8080, { hostname });暴露前先检查以避免错误:
// Extract hostname from request
const { hostname } = new URL(request.url);
const { ports } = await sandbox.getExposedPorts();
if (!ports.some((p) => p.port === 8080)) {
await sandbox.exposePort(8080, { hostname });
}// Extract hostname from request
const { hostname } = new URL(request.url);
const { ports } = await sandbox.getExposedPorts();
if (!ports.some(p => p.port === 8080)) {
await sandbox.exposePort(8080, { hostname });
}错误:Preview URLs require lowercase sandbox IDs
原因:你创建了包含大写字符的 sandbox(例如 "MyProject-123"),但预览 URL 路由始终使用小写,导致不匹配。
解决方案:
// Create sandbox with normalization
const sandbox = getSandbox(env.Sandbox, "MyProject-123", { normalizeId: true });
await sandbox.exposePort(8080, { hostname });// Create sandbox with normalization
const sandbox = getSandbox(env.Sandbox, 'MyProject-123', { normalizeId: true });
await sandbox.exposePort(8080, { hostname });这会以 ID "myproject-123" 创建 Durable Object,以匹配预览 URL 路由。
详情请参阅 Sandbox options - normalizeId。
生产环境:https://{port}-{sandbox-id}-{token}.yourdomain.com
- 自动生成的 token:
https://8080-abc123-random16chars12.yourdomain.com - 自定义 token:
https://8080-abc123-my-api-v1.yourdomain.com
本地开发:http://localhost:8787/...
注意:端口 3000 保留给内部 Bun 服务器,无法暴露。
- Ports API 参考 - 完整的端口暴露 API
- 后台进程指南 - 管理服务
- 执行命令指南 - 启动服务
- Tunnels API 参考 - 大多数公共 URL 用例的推荐替代方案(快速或命名隧道)