Each container instance belongs to one Durable Object. To run more container instances, address more Durable Objects by name with getByName(). Getting a Durable Object does not start its container. The container starts when the Durable Object calls ctx.container.start().
// Get two Durable Objects. Each one starts its own container instance.
const containerOne = env.MY_CONTAINER.getByName(nameOne);
const containerTwo = env.MY_CONTAINER.getByName(nameTwo);
// The Durable Object starts its container when it handles a request.
const response = await containerOne.fetch(request);Each instance runs until the Durable Object stops it, or until the inactivity timeout that the Durable Object sets elapses. Without a timeout, Cloudflare stops the container shortly after the Durable Object becomes inactive.
This behavior is very useful when you want explicit control over the lifecycle of container instances. For instance, you may want to spin up a container backend instance for a specific user, or you may briefly run a code sandbox to isolate AI-generated code, or you may want to run a short-lived batch job.
To run multiple instances of a container and route requests between them, choose a name at random from a fixed pool:
const INSTANCE_COUNT = 3;
export default {
async fetch(request, env) {
const index = Math.floor(Math.random() * INSTANCE_COUNT);
return env.BACKEND.getByName(`instance-${index}`).fetch(request);
},
};const INSTANCE_COUNT = 3;
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const index = Math.floor(Math.random() * INSTANCE_COUNT);
return env.BACKEND.getByName(`instance-${index}`).fetch(request);
},
} satisfies ExportedHandler<Env>;Random selection from a fixed pool means:
- You set a fixed number of instances to route to.
- Each request goes to a random instance, regardless of location.
For the Durable Object that starts the container, waits for its port, and forwards the request, refer to Stateless instances.