Pular para o conteúdo

Lifecycle

Atualizado em Ver como Markdown

Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.

Methods

getSandbox()

Get or create a sandbox instance by ID.

const sandbox = getSandbox(
  binding: DurableObjectNamespace<Sandbox>,
  sandboxId: string,
  options?: SandboxOptions
): Sandbox

Parameters:

  • binding - The Durable Object namespace binding from your Worker environment
  • sandboxId - Unique identifier for this sandbox. The same ID always returns the same sandbox instance. In user-facing apps, scope IDs to a single user.
  • options (optional) - See SandboxOptions for all available options:
    • enableDefaultSession - Use the default session for operations without an explicit sessionId. Set to false to evaluate each call in isolation (default: true)
    • sleepAfter - Duration of inactivity before automatic sleep (default: "10m")
    • keepAlive - Prevent automatic sleep entirely. Persists across hibernation (default: false)
    • containerTimeouts - Configure container startup timeouts
    • normalizeId - Lowercase sandbox IDs for preview URL compatibility (default: false)

Returns: Sandbox instance

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

setKeepAlive()

Enable or disable keepAlive mode dynamically after sandbox creation.

await sandbox.setKeepAlive(keepAlive: boolean): Promise<void>

Parameters:

  • keepAlive - true to prevent automatic sleep, false to allow normal sleep behavior

When enabled, the sandbox automatically sends heartbeat pings every 30 seconds to prevent container eviction. When disabled, the sandbox returns to normal sleep behavior based on the sleepAfter configuration.

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

destroy()

Destroy the sandbox container and free up resources.

await sandbox.destroy(): Promise<void>

Immediately terminates the container and permanently deletes all state:

  • All files in /workspace, /tmp, and /home
  • All running processes
  • All sessions (including the default session)
  • Network connections and exposed ports
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();
  }
}