进阶 celld.dev 2026-10-11 10:08:47 · 35 阅读

第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/, /lb, or /singleton\n", { headers: { "content-type": "text/plain" } }, ); }, };

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/.tar,其中 key 是对镜像层和配置的哈希值,因此重新部署未变更的镜像时不会上传任何内容。node 在某个 cell 首次启动时加载镜像到其自身引擎中,且不会接触注册表。celld-fence 镜像随每个包含容器的部署一起分发。 celld deploy 构建和拉取 linux/amd64 架构的镜像,这与 Wrangler 的行为一致。可通过 CELLD_CONTAINER_PLATFORM 选择其他平台。celld dev 针对本地机器构建,并将镜像保留在本地引擎中。 容器运行在拥有该 cell 的 node 上。每个提供容器类服务的 node 都需要 Docker 或 Podman 守护进程。celld 使用 DOCKER_HOST 指定的 Unix socket,或 Docker、Docker Desktop、OrbStack、Podman 的默认 socket。若 DOCKER_HOST 的值不是 unix:// URL,celld 将无法获得 socket。没有引擎的 node 无法激活容器类的 cell,但可服务其他所有类别。 隔离边界 在默认运行时下,容器共享 node 的 Linux 内核,并非虚拟机。celld 会丢弃所有 Linux 能力,设置 no-new-privileges,保留守护进程默认的 seccomp 配置,将容器进程数限制为 1024,并运行一个作为 PID 1 的 init 来回收孤儿进程。同一 node 上的两个容器之间无法相互连接。 在第一个容器启动前,node 会通过一个一次性特权容器(使用 celld-fence 镜像)在其容器网桥上安装 nftables 规则。设置 enableInternet: true 的容器可以访问互联网,但无法访问 node、其他 node、私有网段(10/8、172.16/12、192.168/16、100.64/10)或链路本地网段。无法安装规则的 node 不会启动任何容器;未包含 fence 镜像的 celld 版本在带有 fence 的 node 上也不会启动容器。 设置 enableInternet: false 会将容器连接到无出站路由的内部网桥。在 macOS 上,内部网络不发布端口,因此 macOS 上的 celld dev 会保持出站连接开启并记录警告。fence 规则仍然适用。 CELLD_CONTAINER_DNS 指定 node 上所有容器的 OCI 运行时,例如用于 gVisor 的 runsc 或用于虚拟机的 kata。containers 条目中的 runtime 键可覆盖该类的默认设置;Cloudflare 没有此键。若守护进程缺少该运行时,所有 start() 调用都会因守护进程错误而失败。 对于非自写的代码,应指定为每个容器提供独立内核的运行时,并将密钥保留在 Worker 中。 在指定运行时下运行的容器会获得写入的 /etc/resolv.conf,指向 1.1.1.1 和 1.0.0.1,或 CELLD_CONTAINER_DNS 指定的解析器,因为 gVisor 无法访问引擎内置解析器。fence 允许公共解析器。使用默认运行时的容器保留引擎解析器,除非操作员设置了 CELLD_CONTAINER_DNS。 休眠、唤醒与 node 资源 setInactivityTimeout() 设置空闲窗口,默认值为 10 分钟,与 Cloudflare 一致。cell 的空闲驱逐会在该窗口内保持容器运行,同一 node 上的下次激活会重新连接至该容器。移动到另一 node、node 重启、重置或停止 node 都会销毁容器。在 celld dev 中按 Ctrl-C 会销毁容器但保留本地状态。 instance_type 支持 lite(旧称 dev)、basic、standard-1(别名 standard)、standard-2、standard-3 和 standard-4,CPU 和内存限制参见 Cloudflare 限制页面。 默认为 dev:1/16 CPU 和 256 MiB,与 Cloudflare 一致。若镜像需启动解释器,请指定更大的类型。 node 将每个运行中容器的内存上限计为已提交内存,因为容器 cgroup 位于 node 进程之外。因此容器密集的 node 会报告无剩余空间并驱逐 cell。应将 node 内存上限设置在最大实例类型之上并留有缓冲。 每个 node 在共享容量采样中发布其每类运行中容器数量。在启动前,node 会将全集群计数与自身实时计数相加并与 max_instances 对比。超出上限的启动会失败,node 会记录带有限制值的 container_start_failed。 与 Cloudflare 的差异

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 和不支持的服务。

本篇用到的工具

评论 (0)