INTEGRITY Dokumentace

Zpřístupnění služeb

Tato příručka ukazuje, jak zpřístupnit služby běžící ve vašem sandboxu internetu pomocí náhledových URL adres.

Kdy zpřístupnit porty

Porty zpřístupněte, když potřebujete:

Základní zpřístupnění portu

Typický postup je: spustit službu → počkat na připravenost → exponovat port → zpracovat požadavky pomocí 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 });
  }
};

Stabilní URL adresy s vlastními tokeny

Pro produkční nasazení nebo při sdílení URL s uživateli použijte vlastní tokeny, aby preview URL zůstaly konzistentní i po restartu kontejneru:

// 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
});

Požadavky na token:

Případy použití:

Pojmenujte vystavené porty

Při zpřístupňování více portů použijte pro přehlednost názvy:

// 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);

Čekání na připravenost služby

Před zpřístupněním služby vždy ověřte, že je připravená. Ve většině případů postačí jednoduché zpoždění:

// 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 });

U kritických služeb pravidelně kontrolujte health endpoint:

// 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 });

Více služeb

Zpřístupněte více portů pro fullstack aplikace:

// 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
});

Správa zpřístupněných portů

Vypište aktuálně zpřístupněné porty

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}`);
  }
}

Zrušení zpřístupnění portů

// 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);
}

Osvědčené postupy

Lokální vývoj

Při lokálním vývoji s wrangler dev, musíte v souboru Dockerfile zveřejnit porty:

Dockerfile
FROM docker.io/cloudflare/sandbox:0.3.3

# Expose ports you plan to use
EXPOSE 8000
EXPOSE 8080
EXPOSE 5173

Aktualizujte wrangler.jsonc k použití vašeho Dockerfile:

wrangler.jsonc
{
  "containers": [
    {
      "class_name": "Sandbox",
      "image": "./Dockerfile"
    }
  ]
}

V produkčním prostředí jsou všechny porty dostupné a programově řízené prostřednictvím exposePort() / unexposePort().

Řešení potíží

Port 3000 je rezervovaný

Port 3000 používá interní server Bun a nelze ho zveřejnit:

// 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 });

Port není připravený

Před zpřístupněním počkejte, až se služba spustí:

// 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 });

Port je již zveřejněný

Před zveřejněním zkontrolujte, abyste předešli chybám:

// 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 });
}

Chyba ID sandboxu s velkými písmeny

Chyba: Preview URLs require lowercase sandbox IDs

Příčina: Vytvořili jste sandbox s velkými písmeny (např. "MyProject-123") ale náhledové URL při směrování vždy používají malá písmena, což způsobí neshodu.

Řešení:

// 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 });

Tím se vytvoří Durable Object s ID "myproject-123", odpovídající směrování náhledové URL.

Viz Možnosti sandboxu - normalizeId s podrobnostmi.

Formát URL adresy náhledu

Produkce: https://{port}-{sandbox-id}-{token}.yourdomain.com

Lokální vývoj: http://localhost:8787/...

Poznámka: Port 3000 je vyhrazen pro interní server Bun a nelze jej zpřístupnit.