Easily connect Containers and Sandboxes to Workers
Containers and Sandboxes now support connecting directly to Workers over HTTP. This allows you to call Workers functions and bindings, like KV or R2, from within the container at specific hostnames.
Define an outbound handler to capture any HTTP request or use outboundByHost to capture requests to individual hostnames and IPs.
export class MyApp extends Sandbox {}
MyApp.outbound = async (request, env, ctx) => { // you can run arbitrary functions defined in your Worker on any HTTP request return await someWorkersFunction(request.body);};
MyApp.outboundByHost = { "my.worker": async (request, env, ctx) => { return await anotherFunction(request.body); },};In this example, requests from the container to http://my.worker will run the function defined within outboundByHost,
and any other HTTP requests will run the outbound handler. These handlers run entirely inside the Workers runtime,
outside of the container sandbox.
Each handler has access to env, so it can call any binding set in Wrangler config.
Code inside the container makes a standard HTTP request to that hostname and the outbound Worker translates it into a binding call.
export class MyApp extends Sandbox {}
MyApp.outboundByHost = { "my.kv": async (request, env, ctx) => { const key = new URL(request.url).pathname.slice(1); const value = await env.KV.get(key); return new Response(value ?? "", { status: value ? 200 : 404 }); }, "my.r2": async (request, env, ctx) => { const key = new URL(request.url).pathname.slice(1); const object = await env.BUCKET.get(key); return new Response(object?.body ?? "", { status: object ? 200 : 404 }); },};Now, from inside the container sandbox, curl http://my.kv/some-key will access Workers KV and curl http://my.r2/some-object will access R2.
Use ctx.containerId to reference the container's automatically provisioned Durable Object.
export class MyContainer extends Container {}
MyContainer.outboundByHost = { "get-state.do": async (request, env, ctx) => { const id = env.MY_CONTAINER.idFromString(ctx.containerId); const stub = env.MY_CONTAINER.get(id); return stub.getStateForKey(request.body); },};This provides an easy way to associate state with any container instance, and includes a built-in SQLite database.
Upgrade to @cloudflare/containers version 0.2.0 or later, or @cloudflare/sandbox version 0.8.0 or later to use outbound Workers.
Refer to Containers outbound traffic and Sandboxes outbound traffic for more details and examples.