容器可以通过 出站处理程序访问 Workers 绑定 —— KV、R2、D1、Durable Objects 等等。出站处理程序会拦截来自容器的 HTTP 请求,并在 Workers 运行时内运行,所有您配置的绑定在此处均可用。
容器向虚拟主机名(例如 http://my.kv/some-key)发出纯 HTTP 请求,而出站处理程序使用绑定的资源来解析该请求。在容器内部不需要任何 SDK 或客户端库。
为每个虚拟主机名定义一个 outboundByHost 处理程序。env 参数允许您访问在您的 Wrangler 配置中声明的每个绑定。
export class MyContainer extends Container {}
MyContainer.outboundByHost = {
"my.kv": async (request, env, ctx) => {
const url = new URL(request.url);
const key = url.pathname.slice(1);
const value = await env.KV.get(key);
return new Response(value);
},
"my.r2": async (request, env, ctx) => {
const url = new URL(request.url);
// Scope access to this container's ID
const path = `${ctx.containerId}${url.pathname}`;
const object = await env.R2.get(path);
return new Response(object?.body ?? null, { status: object ? 200 : 404 });
},
};容器调用 http://my.kv/some-key,并且处理程序使用 KV 绑定对其进行解析。对 http://my.r2/file.png 的调用将从 R2 读取,作用域为当前的容器实例。
ctx 参数暴露了 containerId,它允许您从出站处理程序与容器自己的 Durable Object 进行交互。
"get-state.do": async (request, env, ctx) => {
const id = env.MY_CONTAINER.idFromString(ctx.containerId);
const stub = env.MY_CONTAINER.get(id);
// Assumes getStateForKey is defined on your DO
return stub.getStateForKey(request.body);
},- 处理出站流量 — 阻止、允许和拦截来自容器的所有出站 HTTP
- 环境变量和机密 — 配置机密和环境变量
- Durable Object 接口 — 完整的
ctx.containerAPI 参考