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

main
mdx 250 lines 6.35 KB
Raw
1 ---
2 title: Container lifecycle
3 description: Start, stop, wait for, and restore a Cloudflare Container from its Durable Object — and save its filesystem as a snapshot to restore later.
4 ---
5
6 A [Container](/cloudflare/compute/containers) runs only when you start
7 it. You start it, stop it, and restore it from the Durable Object that
8 owns it.
9
10 The examples use this container:
11
12 ```typescript
13 // src/Sandbox.ts
14 export class Sandbox extends Cloudflare.Container<Sandbox>()("Sandbox", {
15 schedulingPolicy: "durable_object",
16 image: "node:24-slim",
17 }) {}
18 ```
19
20 ## Bind the container
21
22 `yield* Sandbox` in a Durable Object's Construction phase gives you
23 the container's handle:
24
25 ```typescript
26 export default class Workspace extends Cloudflare.DurableObject<Workspace>()(
27 "Workspace",
28 Effect.gen(function* () {
29 const sandbox = yield* Sandbox;
30
31 return Effect.gen(function* () {
32 return {};
33 });
34 }),
35 ) {}
36 ```
37
38 Binding does not start the container.
39
40 ## Start it before you use it
41
42 Call `start` at the top of each operation that needs the container:
43
44 ```typescript
45 const start = sandbox.start({
46 entrypoint: ["sleep", "infinity"],
47 enableInternet: false,
48 });
49
50 return {
51 run: (cmd: string[]) =>
52 Effect.gen(function* () {
53 yield* start;
54 // the container is running
55 }),
56 };
57 ```
58
59 `start` does nothing when the container is already running, and
60 concurrent calls start it once. A container that stopped or crashed
61 since the last request starts again on the next one.
62
63 The options only apply when `start` actually starts the container.
64 To run with different options, stop the container first.
65
66 ## Choose a size per start
67
68 A container with `schedulingPolicy: "durable_object"` picks its size
69 when it starts:
70
71 ```typescript
72 yield* sandbox.start({
73 instance: "standard-1",
74 entrypoint: ["sleep", "infinity"],
75 enableInternet: false,
76 });
77 ```
78
79 `start` starts the Container's own image. To run another image in the
80 same Durable Object, bind another Container — see
81 [Several images in one Durable Object](/cloudflare/compute/containers#several-images-in-one-durable-object).
82 An async Worker attaches Containers to a class with
83 `Cloudflare.DurableObject(className, { containers })` — see
84 [Several images on an async Worker](/cloudflare/compute/containers#several-images-on-an-async-worker).
85
86 ## Start it from a Layer
87
88 A Layer that depends on the container starts it the same way:
89
90 ```typescript
91 export const ShellLive = Layer.effect(
92 Shell,
93 Effect.gen(function* () {
94 const sandbox = yield* Sandbox;
95 const start = sandbox.start({ enableInternet: false });
96
97 return {
98 run: (cmd: string[]) =>
99 start.pipe(
100 Effect.andThen(sandbox.exec(cmd)),
101 Effect.flatMap((child) => child.output()),
102 Effect.scoped,
103 ),
104 };
105 }),
106 );
107 ```
108
109 Every Layer in the Durable Object shares one container, so a Layer
110 never stops it.
111
112 ## Wait for a port
113
114 `getTcpPort` waits until the server inside the container accepts
115 connections:
116
117 ```typescript
118 const { fetch } = yield* sandbox.getTcpPort(8080);
119
120 const health = Effect.gen(function* () {
121 yield* start;
122 const response = yield* fetch(HttpClientRequest.get("http://container/health"));
123 return yield* response.text;
124 });
125 ```
126
127 A port never starts the container. If the container is stopped, the
128 request fails with `ContainerNotRunningError`.
129
130 ## Run a command
131
132 `exec` runs a command in a started container:
133
134 ```typescript
135 const output = yield* Effect.scoped(
136 Effect.gen(function* () {
137 const child = yield* sandbox.exec(["npm", "test"]);
138 return yield* child.output();
139 }),
140 );
141 ```
142
143 `exec` runs the command without a shell. Pass `["sh", "-c", command]`
144 when you need one. Closing the scope kills a process that is still
145 running.
146
147 ## Check whether it is running
148
149 ```typescript
150 if (yield* sandbox.running) {
151 // the process is up; its ports may not be ready yet
152 }
153 ```
154
155 ## Stop it
156
157 `destroy` stops the container immediately:
158
159 ```typescript
160 yield* sandbox.destroy();
161 ```
162
163 `signal` sends a signal to its main process instead, so it can shut
164 down on its own:
165
166 ```typescript
167 yield* sandbox.signal(15); // SIGTERM
168 ```
169
170 ## Let it sleep
171
172 When nothing calls the Durable Object, it goes idle and its container
173 stops. Change how long it waits with `setInactivityTimeout`:
174
175 ```typescript
176 yield* sandbox.setInactivityTimeout(10 * 60 * 1000); // 10 minutes
177 ```
178
179 The next operation that calls `start` starts the container again.
180
181 ## Watch for a crash
182
183 `monitor` waits until the container exits:
184
185 ```typescript
186 yield* sandbox.monitor().pipe(
187 Effect.catchTag("ContainerError", (error) =>
188 Effect.logError(`container exited: ${error.message}`),
189 ),
190 );
191 ```
192
193 A crash fails with `ContainerError`; a clean exit succeeds.
194
195 ## Save a snapshot
196
197 `snapshotContainer` saves the container's filesystem:
198
199 ```typescript
200 const snapshot = yield* sandbox.snapshotContainer({ name: "workspace" });
201 yield* state.storage.put("snapshot", snapshot);
202 ```
203
204 Store the snapshot in the Durable Object's storage so you can restore
205 it after the container stops. A snapshot holds the writable root
206 filesystem: files, installed packages, build caches. It does not hold
207 memory, running processes, or mounted filesystems.
208
209 Snapshots need `schedulingPolicy: "durable_object"`.
210
211 ## Restore a snapshot
212
213 Pass the snapshot to `start` to begin from that filesystem:
214
215 ```typescript
216 const snapshot = yield* state.storage.get<Cloudflare.Containers.ContainerSnapshot>("snapshot");
217
218 yield* sandbox.start({
219 ...(snapshot ? { containerSnapshot: snapshot } : {}),
220 entrypoint: ["sleep", "infinity"],
221 enableInternet: false,
222 });
223 ```
224
225 Without a snapshot, `start` uses the Container's image. The entrypoint
226 starts fresh. A snapshot can start any number of
227 containers, and expires after 30 days without a restore.
228
229 ## Snapshot before you stop
230
231 Save the filesystem, then stop the container, so the next start picks
232 up where this one left off:
233
234 ```typescript
235 const suspend = Effect.gen(function* () {
236 const snapshot = yield* sandbox.snapshotContainer({ name: "workspace" });
237 yield* state.storage.put("snapshot", snapshot);
238 yield* sandbox.destroy();
239 });
240 ```
241
242 ## Where next
243
244 - [Containers](/cloudflare/compute/containers) — declare a container
245 and its image.
246 - [Run a Container](/cloudflare/compute/run-a-container) — build a
247 shell-running container end to end.
248 - [Durable Objects](/cloudflare/compute/durable-objects) — the object
249 that owns each container.
250 - [Container API reference](/providers/cloudflare/containers/container)