cloudflare/containers
TypeScript
Captured source
source ↗cloudflare/containers
Description: Enhance your Workers with serverless containers
Language: TypeScript
License: Apache-2.0
Stars: 256
Forks: 35
Open issues: 38
Created: 2025-04-24T22:49:53Z
Pushed: 2026-06-04T21:01:03Z
Default branch: main
Fork: no
Archived: no
README:
Containers
A class for interacting with Containers on Cloudflare Workers.
Features
- HTTP request proxying and WebSocket forwarding
- Outbound request interception by host or catch-all handler, with HTTPS support
- Host allow/deny lists with glob pattern matching
- Simple container lifecycle management (starting and stopping containers)
- Event hooks for container lifecycle events (onStart, onStop, onError)
- Configurable sleep timeout that renews on requests
- Load balancing utilities
Installation
npm install @cloudflare/containers
Basic Example
import { Container, getContainer, getRandom } from '@cloudflare/containers';
export class MyContainer extends Container {
// Configure default port for the container
defaultPort = 8080;
// After 1 minute of no new activity, shutdown the container
sleepAfter = '1m';
}
export default {
async fetch(request, env) {
const pathname = new URL(request.url).pathname;
// If you want to route requests to a specific container,
// pass a unique container identifier to .get()
if (pathname.startsWith('/specific/')) {
// In this case, each unique pathname will spawn a new container
const container = env.MY_CONTAINER.getByName(pathname);
return await container.fetch(request);
}
// Note: this is a temporary method until built-in autoscaling and load balancing are added.
// If you want to route to one of many containers (in this case 5), use the getRandom helper.
// This load balances incoming requests across these container instances.
let container = await getRandom(env.MY_CONTAINER, 5);
return await container.fetch(request);
},
};API Reference
Container Class
The Container class that extends a container-enbled Durable Object to provide additional container-specific functionality.
Properties
defaultPort?
Optional default port to use when communicating with the container. If this is not set, or you want to target a specific port on your container, you can specify the port with fetch(switchPort(req, 8080)) or containerFetch(req, 8080).
requiredPorts?
Array of ports that should be checked for availability during container startup. Used by startAndWaitForPorts when no specific ports are provided.
sleepAfter
How long to keep the container alive without activity (format: number for seconds, or string like "5m", "30s", "1h").
Defaults to "10m", meaning that after the Container class Durable Object receives no requests for 10 minutes, it will shut down the container.
The following properties are used to set defaults when starting the container, but can be overriden on a per-instance basis by passing in values to startAndWaitForPorts() or start().
env?: Record
Environment variables to pass to the container when starting up.
entrypoint?: string[]
Specify an entrypoint to override image default.
enableInternet: boolean
Whether to enable internet access for the container.
Defaults to true.
interceptHttps: boolean
When true, outbound HTTPS traffic is also intercepted through the same handler chain as HTTP. The container must trust the Cloudflare-provided CA certificate at /etc/cloudflare/certs/cloudflare-containers-ca.crt. See [Egress docs](docs/egress.md#intercepthttps) for setup instructions per distribution.
Defaults to false.
allowedHosts: string[]
A whitelist of hostname patterns. When non-empty, only matching hosts can proceed past the allow check; everything else is blocked (HTTP 520). Supports simple glob patterns where * matches any sequence of characters (e.g. '*.example.com').
deniedHosts: string[]
A blocklist of hostname patterns. Matching hosts are blocked unconditionally (HTTP 520), overriding everything else in the handler chain including per-host handlers. Supports the same glob patterns as allowedHosts.
pingEndpoint: string
Specify an endpoint the container class will hit to check if the underlying instance started. This does not need to be set by the majority of people, only use it if you would like the container supervisor to hit another endpoint in your container when it starts it. Observe that pingEndpoint can include both the hostname and the path. You can set container/health, meaning "container" will be the value passed along the Host header, and "/health" the path.
Defaults to ping.
Methods
##### Lifecycle Hooks
These lifecycle methods are automatically called when the container state transitions. Override these methods to use these hooks.
See [this example](#http-example-with-lifecycle-hooks).
onStart()
Called when container starts successfully.
- called when states transition from
stopped->running,running->healthy
onStop()
Called when container shuts down.
onError(error)
Called when container encounters an error, and by default logs and throws the error.
onActivityExpired()
Called when the activity is expired. The container will run continue to run for some time after the last activity - this length of time is configured by sleepAfter. By default, this stops the container with a SIGTERM, but you can override this behaviour, as with other lifecycle hooks. However, if you don't stop the container here, the activity tracker will be renewed, and this lifecycle hook will be called again when the timer re-expires.
##### Container Methods
fetch(input: RequestInfo | URL, init?: RequestInit): Promise
Forwards HTTP requests to the container.
If you want to target a specific port on the container, rather than the default port, you should use switchPort like so:
const container = env.MY_CONTAINER.getByName('id');
await container.fetch(switchPort(request, 8080));Make sure you provide a port with switchPort or specify a port with the defaultPort property.
You must use fetch rather than containerFetch if you want to forward websockets.
Note that when you call any of the fetch functions, the activity will be automatically renewed (sleepAfter time starts after last activity), and the container will be started if not already running.
containerFetch(...)
Note: containerFetch does not work with websockets.…
Excerpt shown — open the source for the full document.
Notability
notability 5.0/10New Cloudflare containers repo, moderate traction.