记录 Container 何时就绪、成功退出或失败。Durable Object 启动一个命名镜像,并使用 monitor() 观察其退出。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "container-lifecycle",
"main": "src/index.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-20",
"observability": {
"enabled": true
},
"containers": [
{
"class_name": "MyContainer",
"scheduling_policy": "durable_object",
"images": {
"base": {
"dockerfile": "./Dockerfile"
}
}
}
],
"durable_objects": {
"bindings": [
{
"name": "MY_CONTAINER",
"class_name": "MyContainer"
}
]
},
"exports": {
"MyContainer": {
"type": "durable-object",
"storage": "sqlite"
}
}
}name = "container-lifecycle"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-20"
[observability]
enabled = true
[[containers]]
class_name = "MyContainer"
scheduling_policy = "durable_object"
[containers.images.base]
dockerfile = "./Dockerfile"
[[durable_objects.bindings]]
name = "MY_CONTAINER"
class_name = "MyContainer"
[exports.MyContainer]
type = "durable-object"
storage = "sqlite"start() 会发起启动。Worker 会等待 /health 成功响应后再转发流量。并发请求共用此就绪检查;如果检查失败,下一个请求可以重试。
import { DurableObject } from "cloudflare:workers";
const INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;
export class MyContainer extends DurableObject {
starting;
monitoring;
constructor(ctx, env) {
super(ctx, env);
const container = ctx.container;
if (container.running) {
void ctx.blockConcurrencyWhile(() =>
container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS),
);
this.observeExit();
}
}
async fetch(request) {
// Concurrent requests share startup and readiness checks.
this.starting ??= this.startAndWaitForPort().finally(() => {
this.starting = undefined;
});
await this.starting;
const url = new URL(request.url);
url.protocol = "http:";
url.host = "container";
const forwarded = new Request(url, request);
forwarded.headers.delete("host");
return this.ctx.container.getTcpPort(8080).fetch(forwarded);
}
async startAndWaitForPort() {
const container = this.ctx.container;
if (!container.running) {
container.start({
image: container.images.base,
instance: "lite",
enableInternet: false,
});
}
this.observeExit();
await container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS);
const port = container.getTcpPort(8080);
let lastError;
for (let attempt = 0; attempt < 100; attempt++) {
try {
const response = await port.fetch("http://container/health", {
signal: AbortSignal.timeout(1000),
});
await response.body?.cancel();
if (!response.ok) {
throw new Error(`Health check returned ${response.status}`);
}
console.log("Container is ready");
return;
} catch (error) {
lastError = error;
await scheduler.wait(200);
}
}
throw new Error("Container did not become ready on port 8080", {
cause: lastError,
});
}
observeExit() {
if (this.monitoring) return;
this.monitoring = this.ctx.container
.monitor()
.then(() => console.log("Container exited successfully"))
.catch((error) => console.error("Container failed:", error))
.finally(() => {
this.monitoring = undefined;
});
this.ctx.waitUntil(this.monitoring);
}
}
export default {
fetch(request, env) {
return env.MY_CONTAINER.getByName("demo").fetch(request);
},
};import { DurableObject } from "cloudflare:workers";
interface Env {
MY_CONTAINER: DurableObjectNamespace<MyContainer>;
}
const INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;
export class MyContainer extends DurableObject<Env> {
private starting: Promise<void> | undefined;
private monitoring: Promise<void> | undefined;
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
const container = ctx.container!;
if (container.running) {
void ctx.blockConcurrencyWhile(() =>
container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS),
);
this.observeExit();
}
}
async fetch(request: Request): Promise<Response> {
// Concurrent requests share startup and readiness checks.
this.starting ??= this.startAndWaitForPort().finally(() => {
this.starting = undefined;
});
await this.starting;
const url = new URL(request.url);
url.protocol = "http:";
url.host = "container";
const forwarded = new Request(url, request);
forwarded.headers.delete("host");
return this.ctx.container!.getTcpPort(8080).fetch(forwarded);
}
private async startAndWaitForPort(): Promise<void> {
const container = this.ctx.container!;
if (!container.running) {
container.start({
image: container.images.base,
instance: "lite",
enableInternet: false,
});
}
this.observeExit();
await container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS);
const port = container.getTcpPort(8080);
let lastError: unknown;
for (let attempt = 0; attempt < 100; attempt++) {
try {
const response = await port.fetch("http://container/health", {
signal: AbortSignal.timeout(1000),
});
await response.body?.cancel();
if (!response.ok) {
throw new Error(`Health check returned ${response.status}`);
}
console.log("Container is ready");
return;
} catch (error) {
lastError = error;
await scheduler.wait(200);
}
}
throw new Error("Container did not become ready on port 8080", {
cause: lastError,
});
}
private observeExit(): void {
if (this.monitoring) return;
this.monitoring = this.ctx
.container!.monitor()
.then(() => console.log("Container exited successfully"))
.catch((error: unknown) => console.error("Container failed:", error))
.finally(() => {
this.monitoring = undefined;
});
this.ctx.waitUntil(this.monitoring);
}
}
export default {
fetch(request: Request, env: Env): Promise<Response> {
return env.MY_CONTAINER.getByName("demo").fetch(request);
},
} satisfies ExportedHandler<Env>;成功退出后,monitor() 会解析且不返回值。发生失败(包括进程以非零状态退出)时,它会拒绝。当 Durable Object 在 Container 运行期间重启时,构造函数会恢复监控和非活动超时。
待处理的监控器可以使 Durable Object 保持活动状态最多 15 分钟。五分钟非活动超时从 Durable Object 变为非活动状态后开始计算,而不是从最后一次 HTTP 请求后的五分钟开始计算。监控并不是跨重启的持久事件订阅。请参阅 monitor()。
将这些文件保存到项目根目录。服务器监听 0.0.0.0:8080,并在 /health 提供就绪检查端点。
import { createServer } from "node:http";
createServer((request, response) => {
if (request.url === "/health") {
response.writeHead(200).end();
return;
}
response.setHeader("Content-Type", "application/json");
response.end(
JSON.stringify({
message: "Hello from a Container",
environment: process.env.ENV_VAR,
kvValue: process.env.KV_VALUE,
}),
);
}).listen(8080, "0.0.0.0");FROM node:24-bookworm-slim
WORKDIR /app
COPY server.mjs .
EXPOSE 8080
CMD ["node", "server.mjs"]启动兼容 Docker 的引擎。在项目中安装 Wrangler,并使用 4.136.0 或更高版本进行本地开发。
npm i -D wrangleryarn add -D wranglerpnpm add -D wranglerbun add -d wranglernpx wrangler devyarn wrangler devpnpm wrangler dev访问 http://localhost:8787/,并检查 Worker 日志中的就绪信息。monitor() 观察到 Container 完成或失败时,会记录相应日志。