第8章 容器(Containers)
容器 容器运行非 JavaScript 程序,与需要它的 Worker 并列运行。Durable Object 负责启动容器,通过 TCP 端口与之通信,并在结束时将其停止。容器磁盘是临时存储,因此持久化状态必须保存在对象的存储中或其他绑定里。在 celld 中,容器仍处于实验阶段,因此配置项、ctx.container 接口、node 默认设置以及安全边界可能会在不另行通知的情况下变更。请参阅 Cloudflare Containers 文档以了解标准 API。 示例 该容器示例会启动一个 Python HTTP 服务器,并通过容器端口访问它。
Dockerfile FROM python:3.12-alpine WORKDIR /app COPY server.py . ENV PORT=8080 EXPOSE 8080 CMD ["python3", "server.py"]
index.js import { Container, getContainer, getRandom } from "@cloudflare/containers";
export class MyContainer extends Container { defaultPort = 8080; sleepAfter = "2m"; envVars = { MESSAGE: "passed in by the Container class" };
onStart() { console.log("container started"); } onStop() { console.log("container stopped"); } onError(error) { console.log("container error:", error); } }
export default {
async fetch(request, env) {
const { pathname } = new URL(request.url);
if (pathname.startsWith("/container/")) {
// One container per path: each name is its own object and process.
return getContainer(env.MY_CONTAINER, pathname).fetch(request);
}
if (pathname.startsWith("/lb")) {
// Spread requests over three containers.
const container = await getRandom(env.MY_CONTAINER, 3);
return container.fetch(request);
}
if (pathname.startsWith("/singleton")) {
return getContainer(env.MY_CONTAINER).fetch(request);
}
return new Response(
"Try /container/
package.json { "name": "celld-container-example", "private": true, "type": "module", "dependencies": { "@cloudflare/containers": "^0.3.7" } }
server.py # A tiny HTTP server: every response reports the container's hostname, the # request path, and the MESSAGE environment variable the object passed in. import json import os import signal import socket import sys from http.server import BaseHTTPRequestHandler, HTTPServer
# The process is PID 1 in the container, and PID 1 ignores a signal it has # no handler for. The object's stop() sends SIGTERM, so exit on it. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
class Handler(BaseHTTPRequestHandler): def do_GET(self): body = json.dumps({ "hostname": socket.gethostname(), "path": self.path, "message": os.environ.get("MESSAGE", ""), }).encode() self.send_response(200) self.send_header("content-type", "application/json") self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body)
def log_message(self, *args): pass
HTTPServer(("0.0.0.0", int(os.environ["PORT"])), Handler).serve_forever()
wrangler.jsonc { "name": "container", "main": "index.js", "compatibility_date": "2026-01-01", "compatibility_flags": ["nodejs_compat"], "containers": [ { "class_name": "MyContainer", "image": "./Dockerfile", "instance_type": "basic" } ], "durable_objects": { "bindings": [{ "name": "MY_CONTAINER", "class_name": "MyContainer" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyContainer"] }] }
对象与容器 containers 条目用于指定脚本中基于 SQLite 的 Durable Object 类。该类每个对象都获得一个 ctx.container 句柄,最多控制一个容器。 celld 实现了 ctx.container 的以下部分:
start() 启动容器,支持 entrypoint、env、enableInternet 和 labels 参数。 running 报告引擎状态,因此丢失了 monitor() 的对象能在下一个事件时感知到退出。 monitor() 返回一个 Promise,在容器退出时解决。 destroy() 停止容器,signal() 向容器发送信号。 getTcpPort(port).fetch() 向指定端口发送 HTTP 请求,getTcpPort(port).connect() 打开原始套接字。 exec() 在容器内执行进程。 setInactivityTimeout() 设置空闲窗口。
在 Linux 上,getTcpPort(port) 通过容器桥接地址访问所有端口。带有 Upgrade: websocket 头的 fetch 请求会返回 101 响应并附带 webSocket,这与 Cloudflare 的行为一致。node 会将启动失败记录为 container_start_failed。
@cloudflare/containers 按照发布版本运行,包括 sleepAfter 报警、getContainer()、getRandom() 和 switchPort()。@cloudflare/sandbox 也在 cloudflare/sandbox 镜像上按发布版本运行,支持 HTTP 和 RPC 传输协议。其预览 URL 需要在负载均衡器处配置通配符主机名,tunnels 在容器内部运行 cloudflared,bucket 挂载使用应用传递的凭证。参见 sandbox 示例。
镜像与 node
celld deploy 使用 PATH 中的 docker CLI 或 CELLD_DOCKER 指定的 CLI 构建项目中的 Dockerfile,或拉取镜像引用。Podman CLI 也可用。镜像会被保存为 fleet bucket 中的 deploy/images/
containers 条目接受 class_name、image、name、instance_type、max_instances 和 runtime。其他任何键都会终止部署。celld 增加了 runtime,并接受 name 但不使用它。 celld 将容器放置在拥有该 cell 的 node 上。Cloudflare 可将容器放置在远离其对象的位置。 提供容器类服务的 node 需要 Docker 或 Podman 守护进程。 celld 不强制实例类型的磁盘大小限制。 max_instances 在集群内收敛而非集中保持,因此集群可能在一次刷新中超出上限。celld dev 不执行任何上限。 inspect()、snapshotDirectory()、snapshotContainer() 以及出站拦截方法会抛出错误。start() 检查 hardTimeout 后将其忽略,因此值为 0 或负数会抛出异常,有效值则无实际效果。 getTcpPort(port).connect() 提供的套接字生命周期与打开它的 event 相同。参见 TCP 套接字。 monitor() 的 Promise 和 exec() 的进程不会在 handler 响应后保持对象活跃。 在 macOS 上,node 通过已发布端口访问容器,因此镜像必须使用 EXPOSE 声明端口。macOS 上 enableInternet: false 无效。 容器网桥不包含 IPv6 地址,fence 同时拒绝 IPv6 链路本地和唯一本地范围。 对象移动到另一 node 会停止其容器,因此移动后首次调用 @cloudflare/sandbox 可能因 SDK 的 OperationInterruptedError 失败,这与 Cloudflare 容器重启后的表现一致。下一次调用会启动新容器。
Cloudflare 兼容性页面列出了运行时 API 和不支持的服务。