Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/containers/api.md
1## Container Class API23```typescript4import { Container } from "@cloudflare/containers";56export class MyContainer extends Container {7defaultPort = 8080;8requiredPorts = [8080];9sleepAfter = "30m";10enableInternet = true;11pingEndpoint = "/health";12envVars = {};13entrypoint = [];1415onStart() { /* container started */ }16onStop() { /* container stopping */ }17onError(error: Error) { /* container error */ }18onActivityExpired(): boolean { /* timeout, return true to stay alive */ }19async alarm() { /* scheduled task */ }20}21```2223## Routing2425**getByName(id)** - Named instance for session affinity, per-user state26**getRandom()** - Random instance for load balancing stateless services2728```typescript29const container = env.MY_CONTAINER.getByName("user-123");30const container = env.MY_CONTAINER.getRandom();31```3233## Startup Methods3435### start() - Basic start (8s timeout)3637```typescript38await container.start();39await container.start({ envVars: { KEY: "value" } });40```4142Returns when **process starts**, NOT when ports ready. Use for fire-and-forget.4344### startAndWaitForPorts() - Recommended (20s timeout)4546```typescript47await container.startAndWaitForPorts(); // Uses requiredPorts48await container.startAndWaitForPorts({ ports: [8080, 9090] });49await container.startAndWaitForPorts({50ports: [8080],51startOptions: { envVars: { KEY: "value" } }52});53```5455Returns when **ports listening**. Use before HTTP/TCP requests.5657**Port resolution:** explicit ports → requiredPorts → defaultPort → port 335859### waitForPort() - Wait for specific port6061```typescript62await container.waitForPort(8080);63await container.waitForPort(8080, { timeout: 30000 });64```6566## Communication6768### fetch() - HTTP with WebSocket support6970```typescript71// ✅ Supports WebSocket upgrades72const response = await container.fetch(request);73const response = await container.fetch("http://container/api", {74method: "POST",75body: JSON.stringify({ data: "value" })76});77```7879**Use for:** All HTTP, especially WebSocket.8081### containerFetch() - HTTP only (no WebSocket)8283```typescript84// ❌ No WebSocket support85const response = await container.containerFetch(request);86```8788**⚠️ Critical:** Use `fetch()` for WebSocket, not `containerFetch()`.8990### TCP Connections9192```typescript93const port = this.ctx.container.getTcpPort(8080);94const conn = port.connect();95await conn.opened;9697if (request.body) await request.body.pipeTo(conn.writable);98return new Response(conn.readable);99```100101### switchPort() - Change default port102103```typescript104this.switchPort(8081); // Subsequent fetch() uses this port105```106107## Lifecycle Hooks108109### onStart()110111Called when container process starts (ports may not be ready). Runs in `blockConcurrencyWhile` - no concurrent requests.112113```typescript114onStart() {115console.log("Container starting");116}117```118119### onStop()120121Called when SIGTERM received. 15 minutes until SIGKILL. Use for graceful shutdown.122123```typescript124onStop() {125// Save state, close connections, flush logs126}127```128129### onError()130131Called when container crashes or fails to start.132133```typescript134onError(error: Error) {135console.error("Container error:", error);136}137```138139### onActivityExpired()140141Called when `sleepAfter` timeout reached. Return `true` to stay alive, `false` to stop.142143```typescript144onActivityExpired(): boolean {145if (this.hasActiveConnections()) return true; // Keep alive146return false; // OK to stop147}148```149150## Scheduling151152```typescript153export class ScheduledContainer extends Container {154async fetch(request: Request) {155await this.schedule(Date.now() + 60000); // 1 minute156await this.schedule("2026-01-28T00:00:00Z"); // ISO string157return new Response("Scheduled");158}159160async alarm() {161// Called when schedule fires (SQLite-backed, survives restarts)162}163}164```165166**⚠️ Don't override `alarm()` directly when using `schedule()` helper.**167168## State Inspection169170### External state check171172```typescript173const state = await container.getState();174// state.status: "starting" | "running" | "stopping" | "stopped"175```176177### Internal state check178179```typescript180export class MyContainer extends Container {181async fetch(request: Request) {182if (this.ctx.container.running) { ... }183}184}185```186187**⚠️ Use `getState()` for external checks, `ctx.container.running` for internal.**188