The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 762 lines 26.5 KB
Raw
1 ---
2 title: Containers
3 description: Cloudflare Containers run long-lived processes beside a Durable Object — declare a typed container class, implement its runtime in a separate file, and alchemy builds the image, pushes it, and wires the DO pairing.
4 ---
5
6 A Cloudflare Container is a long-lived process running next to a
7 [Durable Object](/cloudflare/compute/durable-objects): the DO owns the
8 container's lifecycle, and callers reach the container through it.
9 In alchemy a container is a class with a typed RPC surface — the
10 same tagged-shape ceremony as a Durable Object — plus a runtime
11 implementation that alchemy bundles into a Docker image and pushes
12 to Cloudflare's registry for you.
13
14 Reach for a container when a [Worker](/cloudflare/compute/workers) isn't
15 enough: you need a real OS process — a sandboxed shell, a binary you
16 can't compile to wasm, an HTTP server listening on a port, a
17 runtime Workers doesn't offer. If you only need per-entity state
18 and coordination, a plain Durable Object is lighter; if you only
19 need request/response compute, a Worker is.
20
21 ## Declare the container class
22
23 The class declares the container's name and its public RPC surface;
24 configuration lives on `.make()`, not here:
25
26 ```typescript
27 // src/Sandbox.ts
28 import * as Cloudflare from "@alchemy.run/cloudflare";
29 import type * as Effect from "effect/Effect";
30
31 export class Sandbox extends Cloudflare.Container<
32 Sandbox,
33 { ping: () => Effect.Effect<string> }
34 >()("Sandbox") {}
35 ```
36
37 Anything that binds `Sandbox` sees `ping()` as a typed RPC method
38 returning `Effect<string>` — no schemas, no serialization
39 boilerplate, exactly like DO methods.
40
41 ## Implement the runtime in a separate file
42
43 The runtime always lives in its own file — the DO imports the class,
44 and if the implementation lived alongside it, the DO bundle would
45 pull in process spawners, Node APIs, and SDKs that the Workers
46 runtime rejects. `.make()` takes the deploy-time props first and the
47 implementation second:
48
49 ```typescript
50 // src/Sandbox.runtime.ts
51 import * as Effect from "effect/Effect";
52 import * as HttpServerResponse from "effect/http/HttpServerResponse";
53 import { Sandbox } from "./Sandbox.ts";
54
55 export default Sandbox.make(
56 { main: import.meta.url },
57 Effect.gen(function* () {
58 return Sandbox.of({
59 ping: () => Effect.succeed("pong"),
60 fetch: Effect.succeed(
61 HttpServerResponse.text("Hello from the container!"),
62 ),
63 });
64 }),
65 );
66 ```
67
68 `main` tells alchemy to bundle this file's Effect program and bake
69 it into a generated image as the entrypoint. RPC methods and `fetch`
70 are independent: `fetch` serves HTTP on port `3000` inside the
71 container by default, while methods like `ping` are invoked directly
72 through the typed handle.
73
74 ## Run it from a Durable Object
75
76 Yield the class inside a DO's Construction phase. That binds the
77 container to the DO and hands you its handle, without starting it:
78
79 ```typescript
80 // src/Agent.ts
81 import * as Cloudflare from "@alchemy.run/cloudflare";
82 import * as Effect from "effect/Effect";
83 import { Sandbox } from "./Sandbox.ts";
84
85 export default class Agent extends Cloudflare.DurableObject<Agent>()(
86 "Agents",
87 Effect.gen(function* () {
88 const sandbox = yield* Sandbox;
89
90 return Effect.gen(function* () {
91 const start = sandbox.start({ enableInternet: true });
92 return {
93 ping: () => start.pipe(Effect.andThen(sandbox.ping())),
94 };
95 });
96 }),
97 ) {}
98 ```
99
100 `start` is idempotent: it starts the container unless it is already
101 running, and concurrent calls start it once, so call it at the top of
102 each operation. RPC methods and `getTcpPort` wait until the container's
103 port accepts connections, but never start it.
104
105 :::note
106 Stopping, sleeping, crash handling and snapshots are covered in
107 [Container lifecycle](/cloudflare/compute/container-lifecycle).
108 :::
109
110 Importing `Sandbox` (the class) does not pull in the runtime file —
111 it gets tree-shaken out of the DO's bundle. A Worker then binds
112 `Agent` and calls `agents.getByName(name).ping()` like any other DO
113 method.
114
115 ## Wire the runtime into the Stack
116
117 The `.make()` default export is the side-effect that registers the
118 container's runtime, so it must be reachable from `alchemy.run.ts`:
119
120 ```typescript
121 // alchemy.run.ts
122 import SandboxLive from "./src/Sandbox.runtime.ts";
123
124 export default Alchemy.Stack(
125 "MyApp",
126 { providers: Cloudflare.providers(), state: Cloudflare.state() },
127 Effect.gen(function* () {
128 const worker = yield* Worker;
129 return { url: worker.url };
130 }).pipe(Effect.provide(SandboxLive)),
131 );
132 ```
133
134 On deploy, alchemy bundles the entrypoint, builds and pushes the Docker
135 image as needed, and reconciles the application's scaling and runtime
136 configuration. The first deploy takes a minute or two longer while the
137 registry is provisioned. Builds are [cached by default](#cached-builds-by-default):
138 a matching image can be reused from the registry without invoking Docker.
139
140 ## Proxy HTTP to a container port
141
142 `getTcpPort(port)` returns a `fetch` handle for any port inside the
143 container, so an HTTP server you'd normally run in Docker just
144 works:
145
146 ```typescript
147 // inside the DO's inner Effect
148 const { fetch } = yield* sandbox.getTcpPort(3000);
149
150 return {
151 hello: () =>
152 Effect.gen(function* () {
153 yield* sandbox.start({ enableInternet: true });
154 const response = yield* fetch(
155 HttpClientRequest.get("http://container/"),
156 );
157 return yield* response.text;
158 }),
159 };
160 ```
161
162 The returned `fetch` waits until the port accepts connections, so you
163 don't coordinate readiness yourself. It never starts the container:
164 call `start` first.
165
166 ## Process scope vs request scope
167
168 Unlike Workers, a Container is a **real process** — and that changes
169 what the instance scope means. The bundled program runs under a root
170 scope that closes when the process shuts down gracefully, so
171 resources acquired in the constructor (a connection kept warm across requests,
172 a background consumer) are genuinely released on exit. Serverless
173 runtimes only approximate this: workerd never closes its instance
174 scope at all, and Lambda gets a best-effort 500 ms SIGTERM window at
175 sandbox shutdown. A hard kill still skips finalizers, as in any
176 process, so treat instance-level cleanup as best-effort.
177
178 Each incoming request to the container's HTTP server still gets its
179 own request `Scope`, released when the response settles — the same
180 per-event contract as every other runtime. See
181 [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope)
182 for the model across all runtimes.
183
184 ## Bring your own image
185
186 `main` is one of three image sources. Point `context` at a directory
187 with a Dockerfile to build your own image, or `image` at a pre-built
188 remote image that alchemy pulls and re-pushes — no Effect bundling,
189 no `.make()`, props declared inline on the class:
190
191 ```typescript
192 export class Web extends Cloudflare.Container<Web>()("Web", {
193 context: `${import.meta.dirname}/context`,
194 }) {}
195
196 export class Echo extends Cloudflare.Container<Echo>()("Echo", {
197 image: "mendhak/http-https-echo:latest",
198 }) {}
199 ```
200
201 Arbitrary images expose no RPC methods — the DO talks to them purely
202 over their TCP port via `getTcpPort`. To build, tag, and push that
203 image as part of the same Stack, see
204 [Build & push images](/docker/build-and-push) in the Docker hub.
205
206 When `image` already references Cloudflare's managed registry —
207 for example a digest reference pushed by CI, like
208 `registry.cloudflare.com/<accountId>/app@sha256:...` — alchemy
209 deploys the reference as-is and skips the docker pull and push
210 entirely.
211
212 alchemy pulls an `image` as `linux/amd64` on every deploy and every
213 `alchemy dev` start, so a mutable tag like `:latest` picks up a newly
214 pushed image. An image that is only in your local Docker, built on
215 your machine or loaded with `docker load`, has no registry to pull
216 from, so alchemy uses the local copy:
217
218 ```typescript
219 // docker build --platform linux/amd64 -t local-only/app:dev .
220 export class App extends Cloudflare.Container<App>()("App", {
221 image: "local-only/app:dev",
222 }) {}
223 ```
224
225 Build it for `linux/amd64`, the platform Cloudflare runs. When an
226 image can be neither pulled nor found locally, the error names the
227 image and the `docker login` or `docker build` command that fixes it.
228 The tag is the image's identity, so give each build its own tag to
229 redeploy it.
230
231 ## Cached builds by default
232
233 Dockerfile builds, inline Dockerfiles, and Effect-native `main` builds use
234 registry caching without extra configuration:
235
236 ```typescript
237 export class Web extends Cloudflare.Container<Web>()("Web", {
238 context: `${import.meta.dirname}/context`,
239 }) {}
240 ```
241
242 The default repository is
243 `registry.cloudflare.com/<account-id>/<application-physical-name>`.
244 The generated physical name includes the stack, stage, and resource-instance
245 identity. Updates to that application within the stage can reuse published
246 images, including when reverting to previously built inputs. Replacement or
247 destroy/recreate can change the physical name and start a new cache.
248
249 This is resource-specific caching within a stage, not one shared repository
250 for every container. To reuse images across stages or applications, choose
251 a common `publish.repository` as shown below.
252
253 :::caution[Pin external build inputs]
254 Pin base images and downloaded dependencies. A changed upstream image tag or
255 package download is outside the build context and cannot invalidate its
256 content hash, so a matching cached image may still be reused.
257 :::
258
259 ## Share published images across stages
260
261 Set `publish.repository` to choose a destination repository shared by
262 applications and stages in the same Cloudflare account:
263
264 ```typescript
265 export class Web extends Cloudflare.Container<Web>()("Web", {
266 context: `${import.meta.dirname}/context`,
267 publish: { repository: "web" },
268 }) {}
269 ```
270
271 `"web"` is the repository name, not a source image, application name,
272 registry host, or complete image reference. Alchemy lowercases it and adds
273 the configured account ID. With the default registry host, a build uses:
274
275 ```text
276 Published build: registry.cloudflare.com/<account-id>/web:<build-hash>
277 Build cache: registry.cloudflare.com/<account-id>/web:buildcache
278 Deployed image: registry.cloudflare.com/<account-id>/web@sha256:<manifest-digest>
279 ```
280
281 The build hash identifies the inputs; the manifest digest identifies the
282 published artifact. Stages using the same repository and matching build
283 inputs reuse the published image without invoking Docker. Changed inputs
284 produce a new hash tag in that repository and can reuse its shared inline
285 build-layer cache. Each stage still has its own Container application,
286 runtime settings, and running instances; only images and build layers are shared.
287
288 All builds targeting a repository import reusable layers from its
289 `:buildcache` tag, even when their complete input hashes differ. That tag
290 points to the latest exported inline cache, not an aggregate of every image
291 ever published to the repository. A finished-image cache hit leaves the
292 layer-cache tag unchanged. The Container deploys the immutable digest, not
293 the mutable `buildcache` tag.
294
295 For an Effect-native Container, put `publish` in the props passed to
296 `.make()`, alongside `main`. Omitting `publish` keeps the default cached,
297 application-specific repository.
298
299 For a pre-built external `image`, `publish.repository` chooses where it is
300 re-published, but does not enable finished-image cache reuse. Images already
301 in the target registry keep their existing repository instead of being
302 copied into the requested one.
303
304 ## Configure the container with `env`
305
306 A container is a process, not a Worker: it has no bindings, so every
307 piece of configuration reaches it as an environment variable. `env`
308 takes a plain map and lands each entry on the deployment, where the
309 program reads it from `process.env` — the same for a generated
310 (`main`) image, a `context` build, and a pre-built `image`:
311
312 ```typescript
313 export class Api extends Cloudflare.Container<Api>()("Api", {
314 context: `${import.meta.dirname}/api`,
315 ports: [{ name: "http", port: 8080 }],
316 env: {
317 PORT: "8080",
318 LOG_LEVEL: "info",
319 },
320 }) {}
321 ```
322
323 Values are strings. Wrap a secret in `Redacted` and it stays
324 encrypted in alchemy's state and out of plan output, while the
325 container still reads a plain string:
326
327 ```typescript
328 env: {
329 SESSION_KEY: Redacted.make(process.env.SESSION_KEY!),
330 }
331 ```
332
333 ## Read another resource's outputs
334
335 A class body is module scope, so there is nowhere to `yield*` the
336 bucket, queue, or database whose output you need — and a bare
337 declaration is an Effect, not a resolved handle, so
338 `Uploads.bucketName` is `undefined` until something yields it. Pass
339 the props as an `Effect.gen` instead; inside it, sibling resources
340 resolve like anywhere else:
341
342 ```typescript
343 import * as Effect from "effect/Effect";
344
345 export const Uploads = Cloudflare.R2.Bucket("Uploads");
346
347 export class Api extends Cloudflare.Container<Api>()(
348 "Api",
349 Effect.gen(function* () {
350 const uploads = yield* Uploads;
351 return {
352 context: `${import.meta.dirname}/api`,
353 env: { BUCKET_NAME: uploads.bucketName },
354 };
355 }),
356 ) {}
357 ```
358
359 The reference is what orders the deploy: the bucket is created
360 before the container application that reads its name.
361
362 ## Connect to a SQL database
363
364 An **effectful** (`main`) container runs your Effect program, so it
365 resolves a database capability the same way a Worker does — declare
366 the connection once, then bind it:
367
368 ```typescript
369 // src/Db.ts
370 import * as Prisma from "@alchemy.run/prisma";
371 import * as Effect from "effect/Effect";
372
373 export const Connection = Effect.gen(function* () {
374 const project = yield* Prisma.Project("app", {
375 createDatabase: false,
376 region: "us-east-1",
377 });
378 const postgres = yield* Prisma.Postgres("db", {
379 project,
380 region: "us-east-1",
381 });
382 return yield* Prisma.Connection("api", { database: postgres });
383 });
384 ```
385
386 ```typescript
387 // src/Api.runtime.ts
388 import * as Prisma from "@alchemy.run/prisma";
389 import * as SQL from "@alchemy.run/sql/Postgres";
390 import * as Effect from "effect/Effect";
391 import * as HttpServerResponse from "effect/http/HttpServerResponse";
392 import { Api } from "./Api.ts";
393 import { Connection } from "./Db.ts";
394
395 export default Api.make(
396 { main: import.meta.url },
397 Effect.gen(function* () {
398 const db = yield* Prisma.Connect(Connection);
399 const sql = yield* SQL.Postgres({ url: db.databaseUrl });
400
401 return Api.of({
402 fetch: Effect.gen(function* () {
403 const users = yield* sql`SELECT * FROM users`;
404 return yield* HttpServerResponse.json(users);
405 }),
406 });
407 }).pipe(Effect.provide(Prisma.ConnectBinding)),
408 );
409 ```
410
411 You never name `DATABASE_URL`. The container has no bindings — it is
412 a process, not a Worker — so `Prisma.Connect` writes the connection's
413 outputs onto the deployment as environment variables and reads them
414 back at runtime. The capability owns both ends.
415
416 Start it with outbound networking, or the container never reaches the
417 database at all:
418
419 ```typescript
420 yield* api.start({ enableInternet: true });
421 ```
422
423 ## Connect an arbitrary image to a database
424
425 An image you brought yourself knows nothing about alchemy, so there
426 is no capability to bind — you name the variable and hand it the
427 connection string. Give it the provider's **pooled** endpoint
428 (Prisma's `databaseUrl` already prefers it; on Neon it is
429 `branch.pooledConnectionUri`, on PlanetScale `role.connectionUrlPooled`),
430 since nothing else is pooling those connections on the container's
431 behalf:
432
433 ```typescript
434 // src/Web.ts
435 import * as Cloudflare from "@alchemy.run/cloudflare";
436 import * as Effect from "effect/Effect";
437 import { Connection } from "./Db.ts";
438
439 export class Web extends Cloudflare.Container<Web>()(
440 "Web",
441 Effect.gen(function* () {
442 const connection = yield* Connection;
443 return {
444 context: `${import.meta.dirname}/web`,
445 ports: [{ name: "http", port: 8080 }],
446 env: {
447 DATABASE_URL: connection.databaseUrl,
448 PORT: "8080",
449 },
450 };
451 }),
452 ) {}
453 ```
454
455 Your image reads `DATABASE_URL` with whatever client it already
456 uses — `pg`, Prisma, Rails, Django. Nothing about the container is
457 alchemy-specific; only the value's provenance is.
458
459 A Worker fronting the same database still binds Hyperdrive — see
460 [Hyperdrive](/cloudflare/data/hyperdrive). The two coexist: point
461 Hyperdrive at the *direct* origin (it pools for the Worker) and the
462 container at the pooled one.
463
464 Under `alchemy dev` the same wiring targets your local emulators. A
465 local dev database hands out `localhost` URLs, but inside the Docker
466 container `localhost` is the container itself — so the dev runtime
467 rewrites loopback hosts in the container's env to
468 `host.docker.localhost`. The alias deliberately keeps `localhost` in
469 the hostname so clients that gate plain-HTTP on a local-looking host
470 (Prisma's `prisma+postgres://` protocol, for one) keep working against
471 the local dev server.
472
473 On Docker Desktop that alias is Docker's `host-gateway`, which
474 forwards to processes bound to `127.0.0.1` on your machine.
475
476 On native Linux, `host-gateway` is the docker bridge IP
477 (`172.17.0.1`). A TCP SYN to that address is host INPUT — UFW,
478 firewalld, and nftables on CachyOS/Arch will drop it. Binding the
479 same port on the bridge or on your LAN NIC does not skip INPUT.
480 Alchemy does not go that way:
481
482 1. `@prisma/dev` (and any host server you start) stay on `127.0.0.1`.
483 2. A unix socket on the host forwards to that port.
484 3. The workerd `<name>-proxy` sidecar bind-mounts the socket and maps
485 `host.docker.localhost` to `127.0.0.1` in the shared netns.
486 4. A Docker-managed helper shares that network namespace, accepts
487 `127.0.0.1:<port>`, and forwards through the socket. Alchemy waits
488 for its listeners before completing container startup and removes
489 the helper when the container is deleted or the dev runtime stops.
490
491 The container talks to itself. The socket crosses the boundary. UFW
492 never sees a SYN to `172.17.0.1`.
493
494 The helper uses `node:22-alpine`, which Docker downloads on first use.
495 Normal Docker access is sufficient; Alchemy does not require host-side
496 `nsenter` permissions. If the helper fails to start, container startup
497 reports the error.
498
499 Neon and PlanetScale have no local emulator: even under `alchemy
500 dev` the URL is a cloud host (`*.neon.tech`, `*.psdb.cloud`) and the
501 rewrite is a no-op. The container still needs
502 `enableInternet: true` to reach them.
503
504 ## Which capabilities reach a container
505
506 The split follows the transport. A capability whose config travels as
507 environment variables works in a container: `Prisma.Connect`, and the
508 token-scoped HTTP clients for
509 [R2](/cloudflare/data/r2), [KV](/cloudflare/data/kv), and
510 [Queues](/cloudflare/messaging/queues) —
511 `Cloudflare.R2.ReadWriteBucketHttp` and friends, which mint a scoped
512 API token instead of using a native binding.
513
514 A capability that *is* a workerd binding cannot:
515 `Cloudflare.Hyperdrive.Connect`, `Cloudflare.D1.QueryDatabase`, and
516 every `*Binding` layer resolve against the Workers runtime, which no
517 container process has. Use the `*Http` layer where one exists, and
518 environment variables otherwise.
519
520 ## Bind on an async Worker
521
522 An async Worker can host a container-backed Durable Object class
523 that ships as plain JavaScript — `@cloudflare/sandbox`'s `Sandbox`,
524 or your own class extending `@cloudflare/containers`' `Container`.
525 The class lives in the worker script:
526
527 ```typescript
528 // src/worker.ts
529 import { Container } from "@cloudflare/containers";
530
531 export class Sandbox extends Container {
532 defaultPort = 8080;
533 }
534 ```
535
536 `Sandbox` is the Durable Object class Cloudflare instantiates for
537 each container instance; `Container` (from `@cloudflare/containers`)
538 handles the lifecycle and forwards `fetch` to the port inside it.
539
540 Declare it in the stack by binding a `Cloudflare.Container` in the
541 Worker's `env` — the Container is the Durable Object binding and its
542 ContainerApplication together. Alchemy emits the
543 `durable_object_namespace` binding, marks the class as
544 container-backed in the script metadata, provisions the application,
545 and attaches it to the class's namespace:
546
547 ```typescript
548 // alchemy.run.ts
549 import type { Sandbox } from "./src/worker.ts";
550
551 export const Worker = Cloudflare.Worker("Worker", {
552 main: "./src/worker.ts",
553 env: {
554 Sandbox: Cloudflare.Container<Sandbox>("Sandbox", {
555 image: "docker.io/cloudflare/sandbox:0.1.3",
556 }),
557 },
558 });
559 ```
560
561 The Durable Object class name defaults to the binding name (the
562 `env` key). Set `className` when the exported class is named
563 differently. The type parameter (`Container<Sandbox>`) is the class
564 from `worker.ts` above — it types `env.Sandbox` as
565 `DurableObjectNamespace<Sandbox>` through
566 [`InferEnv`](/cloudflare/compute/workers#async-workers),
567 so the handler reaches the container with full types:
568
569 ```typescript
570 // src/worker.ts
571 import { getContainer } from "@cloudflare/containers";
572 import type * as Cloudflare from "@alchemy.run/cloudflare";
573 import type { Worker } from "../alchemy.run.ts";
574
575 export default {
576 async fetch(request: Request, env: Cloudflare.InferEnv<typeof Worker>) {
577 return getContainer(env.Sandbox, "default").fetch(request);
578 },
579 };
580 ```
581
582 Only image-backed containers (`image`, or `context`/`dockerfile`)
583 can be bound this way. An effectful (`main`) container's runtime is
584 provided by its `.make()` Layer, which needs an Effect-native
585 Durable Object host.
586
587 ## Several images in one Durable Object
588
589 A Durable Object can choose its image at runtime. Declare one Container
590 per image with `schedulingPolicy: "durable_object"`:
591
592 ```typescript
593 export class Node extends Cloudflare.Container<Node>()("Node", {
594 schedulingPolicy: "durable_object",
595 image: "node:24-slim",
596 }) {}
597
598 export class Python extends Cloudflare.Container<Python>()("Python", {
599 schedulingPolicy: "durable_object",
600 dockerfile: "./python/Dockerfile",
601 context: "./python",
602 }) {}
603 ```
604
605 One Container is one image: `image` copies a registry image, and
606 `context`/`dockerfile` builds one. Alchemy publishes it to Cloudflare's
607 registry and prepares it before the Worker is uploaded.
608
609 Bind both in the Durable Object. Each handle's `start()` starts its own
610 image:
611
612 ```typescript
613 export class Agent extends Cloudflare.DurableObject<Agent>()(
614 "Agent",
615 Effect.gen(function* () {
616 const node = yield* Node;
617 const python = yield* Python;
618 return Effect.succeed({
619 run: (cmd: string[]) =>
620 Effect.gen(function* () {
621 yield* node.start({
622 instance: "lite",
623 entrypoint: ["sleep", "infinity"],
624 enableInternet: false,
625 });
626 return yield* (yield* node.exec(cmd)).output();
627 }).pipe(Effect.scoped),
628 });
629 }),
630 ) {}
631 ```
632
633 Cloudflare gives a Durable Object class one container application, and
634 each object one container. Every binding adds its image to the class's
635 application under the Container's id. The handles control the same
636 container, so start one image at a time and `destroy()` before you
637 switch.
638
639 Application-wide settings — `ssh`, `authorizedKeys`, and
640 `observability` — can be declared on any of the class's Containers.
641 Two Containers that declare different values fail the deploy with
642 `ContainerApplicationSettingsConflict`.
643
644 A Container can be bound by several Durable Object classes. Each class adds
645 the image to its own application.
646
647 ## Several images on an async Worker
648
649 A plain Durable Object class lists its Containers on its binding. A
650 Container can back several classes:
651
652 ```typescript
653 // alchemy.run.ts
654 const Node = Cloudflare.Container("Node", {
655 schedulingPolicy: "durable_object",
656 image: "node:24-slim",
657 });
658
659 const Python = Cloudflare.Container("Python", {
660 schedulingPolicy: "durable_object",
661 image: "python:3.13-slim",
662 });
663
664 const Rust = Cloudflare.Container("Rust", {
665 schedulingPolicy: "durable_object",
666 image: "rust:1.90-slim",
667 });
668
669 export const Worker = Cloudflare.Worker("App", {
670 main: "./src/worker.ts",
671 env: {
672 AGENT: Cloudflare.DurableObject("Agent", { containers: [Node, Python] }),
673 REVIEWER: Cloudflare.DurableObject("Reviewer", { containers: [Node, Rust] }),
674 },
675 });
676 ```
677
678 Each class gets its own container application. The class finds each
679 image in `ctx.container.images` under its Container's id:
680
681 ```typescript
682 // src/worker.ts
683 import { DurableObject } from "cloudflare:workers";
684
685 export class Agent extends DurableObject {
686 async run(cmd: string[]) {
687 const container = this.ctx.container!;
688 if (!container.running) {
689 container.start({
690 image: container.images.Node,
691 entrypoint: ["sleep", "infinity"],
692 enableInternet: false,
693 });
694 }
695 return (await container.exec(cmd)).output();
696 }
697 }
698 ```
699
700 Only fleet Containers bind directly in `env`. A Durable Object-managed
701 Container placed there fails with `DurableObjectContainerBindingError`.
702
703 ## ContainerApplication
704
705 Under the hood every container is backed by a
706 [ContainerApplication](/providers/cloudflare/containers/containerapplication)
707 — the deployed, scalable unit that carries the image, instance
708 type, instance counts, and observability settings. You typically
709 extend `Cloudflare.Container` rather than using it directly, but
710 the same props shape (`instanceType`, `observability`, `runtime`,
711 …) flows through `.make()`.
712
713 ## Rollouts
714
715 When a deploy changes the image or configuration, running instances
716 are replaced with the new version. By default the replacement is
717 immediate — every instance at once. Set `rollout` to replace them in
718 steps instead, so the application stays available through the update:
719
720 ```typescript
721 export class Api extends Cloudflare.Container<Api>()("Api", {
722 main: import.meta.url,
723 instances: 4,
724 maxInstances: 4,
725 rollout: { strategy: "rolling", stepPercentage: 25 },
726 }) {}
727 ```
728
729 A `rolling` strategy replaces `stepPercentage` of the instances per
730 step and advances automatically as the new instances come up. Each
731 replaced instance receives `SIGTERM` and has 15 minutes to shut down
732 cleanly before `SIGKILL`.
733
734 Rollouts replace instances; they do not split requests between two
735 image versions. The Worker and Durable Object fronting the container
736 cut over immediately while instances roll, so keep the
737 Worker-to-container protocol compatible across both image versions
738 until the rollout completes. Request-level traffic splitting exists
739 one layer up, on the Worker — see
740 [Gradual deployments](/cloudflare/compute/gradual-deployments).
741
742 ## Where next
743
744 The full walkthrough:
745
746 - [Run a Container](/cloudflare/compute/run-a-container) — build the
747 sandbox above out to a shell-executing container with RPC, HTTP
748 proxying, stage-dependent config, and tests.
749
750 Related:
751
752 - [Container lifecycle](/cloudflare/compute/container-lifecycle) — start,
753 stop, sleep, and snapshot a container.
754 - [Durable Objects](/cloudflare/compute/durable-objects) — every container
755 is fronted by one.
756 - [Workers](/cloudflare/compute/workers) — the entrypoint that reaches the
757 DO (and through it, the container).
758
759 Reference:
760
761 - [Container API reference](/providers/cloudflare/containers/container)
762 - [ContainerApplication API reference](/providers/cloudflare/containers/containerapplication)