このガイドでは、プレビュー URL 経由で、サンドボックス内のサービスをインターネットへ公開する方法を説明します。
次のようなときにポートを公開します。
- 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 を共有するときは、コンテナ再起動後もプレビュー 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
});トークンの要件:
- 長さは 1〜16 文字
- 使えるのは小文字(a-z)、数字(0-9)、ハイフン(-)、アンダースコア(_)のみ
- 各サンドボックス内で一意であること
用途:
- エンドポイントが変わらない本番 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 5173wrangler.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
原因: 大文字を含む ID(例: "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 });これで Durable Object の ID は "myproject-123" になり、プレビュー URL のルーティングと一致します。
詳細は Sandbox オプション - normalizeId を参照してください。
本番: https://{port}-{sandbox-id}-{token}.yourdomain.com
- 自動生成トークン:
https://8080-abc123-random16chars12.yourdomain.com - カスタムトークン:
https://8080-abc123-my-api-v1.yourdomain.com
ローカル開発: http://localhost:8787/...
注意: ポート 3000 は内部の Bun サーバー用に予約されており、公開できません。
- Ports API リファレンス - ポート公開 API の全体
- バックグラウンドプロセスのガイド - サービスの管理
- コマンド実行のガイド - サービスの起動
- Tunnels API リファレンス - ほとんどの公開 URL 用途で推奨する代替(クイックトンネルまたは名前付きトンネル)