Skip to content

Block, allow and intercept container outbound traffic

By default a container can reach the public internet. You can block that, allow only some hosts, or send the container's outbound HTTP and HTTPS requests through Python functions in your Worker. Those functions run outside the container and can read your Worker's bindings and secrets, so the container never needs to hold credentials.

This page covers the Python API. For how egress works at the platform level, including non-HTTP traffic and ports, see Handle outbound traffic.

Enable interception

A Worker entrypoint called ContainerProxy applies outbound handlers and host lists. It must be importable from your Worker's entry module, even if you never reference it:

src/entry.py
from containers import Container, ContainerProxy, get_container  # noqa: F401

If it's missing, containers with outbound handlers or host lists fail to start, with RuntimeError: ctx.exports.ContainerProxy is undefined. enable_internet = False on its own doesn't need ContainerProxy.

Block internet access

Set enable_internet = False to deny outbound traffic by default:

class Sandbox(Container):
    default_port = 8080
    enable_internet = False

The container can then only reach hosts you allow, or hosts an outbound handler answers for.

Allow and deny hosts

allowed_hosts is an allowlist. When it's set, the container can't reach any host that isn't on it, even when enable_internet is True. denied_hosts is a blocklist, and it takes precedence over both the allowlist and any handler.

class Sandbox(Container):
    default_port = 8080
    enable_internet = False
    allowed_hosts = ["pypi.org", "files.pythonhosted.org", "*.example.com"]
    denied_hosts = ["internal.example.com"]

The SDK matches patterns against the hostname. * matches any run of characters, so *.example.com, api.*.com and goo*gle are all valid. *.example.com doesn't match example.com itself, so list both if the container needs both. The SDK ignores a trailing dot on the hostname. Blocked requests get a 520 response with the body Origin is disallowed.

Note

Host lists apply to HTTP traffic, and to HTTPS once HTTPS interception is on. See the platform docs for how the platform handles other ports and protocols.

Outbound handlers

An outbound handler is an async function that takes the intercepted request and returns a Response:

from typing import Any

from containers import OutboundHandlerContext
from workers import Request, Response


async def handler(
    request: Request, env: Any, ctx: OutboundHandlerContext
) -> Response: ...

containers exports this signature as the type alias OutboundHandler, which is what outbound, outbound_by_host and outbound_handlers expect. The examples below use the same imports.

  • request is the request the container made.
  • env is your Worker's environment, with all its bindings and secrets.
  • ctx.container_id is the ID of the Durable Object that owns the container.
  • ctx.class_name is the name of your Container subclass.
  • ctx.params holds the params given to set_outbound_handler or set_outbound_by_host, or None.

Handlers run in ContainerProxy, not in your Durable Object, so they can't use self. Write them as module-level functions.

Handle specific hosts

outbound_by_host maps hostnames or glob patterns to handlers. An exact hostname match takes precedence over a glob:

async def mock_payments(
    request: Request, env: Any, ctx: OutboundHandlerContext
) -> Response:
    return Response.json({"status": "succeeded"})


async def block(request: Request, env: Any, ctx: OutboundHandlerContext) -> Response:
    return Response("blocked in tests", status=403)


class Tests(Container):
    default_port = 8080
    outbound_by_host = {
        "api.stripe.com": mock_payments,
        "*.analytics.example.com": block,
    }

If you set only outbound_by_host, the container's requests to other hosts go out unchanged.

Handle everything else

outbound is a catch-all for any host that no more specific rule handled:

from workers import fetch


async def log_and_forward(
    request: Request, env: Any, ctx: OutboundHandlerContext
) -> Response:
    print(f"[{ctx.container_id}] outbound: {request.method} {request.url}")
    return await fetch(request)


class Audited(Container):
    default_port = 8080
    outbound = log_and_forward

Inject credentials

A handler can read env, so it can add a secret the container never sees:

from workers import Request, fetch


async def github(request: Request, env: Any, ctx: OutboundHandlerContext) -> Response:
    headers = [
        (key, value)
        for key, value in request.headers.items()
        if key.lower() != "authorization"
    ]
    headers.append(("authorization", f"Bearer {env.GITHUB_TOKEN}"))
    return await fetch(Request(request, headers=headers))


class Agent(Container):
    default_port = 8080
    intercept_https = True
    outbound_by_host = {"api.github.com": github}

Defining handlers after the class

Handlers are plain class attributes, so you can also assign them after the class is defined. This helps when a handler needs to refer to the class:

class Agent(Container):
    default_port = 8080


async def catch_all(
    request: Request, env: Any, ctx: OutboundHandlerContext
) -> Response:
    return Response(f"blocked by {ctx.class_name}", status=403)


Agent.outbound = catch_all

Subclasses inherit outbound configuration through normal attribute lookup.

HTTPS

By default the SDK intercepts only plain HTTP. To intercept HTTPS too, set intercept_https = True:

class Agent(Container):
    default_port = 8080
    intercept_https = True

This does nothing on its own. It needs an outbound rule, either a class-level outbound, outbound_by_host, outbound_handlers, allowed_hosts or denied_hosts, or a runtime change.

The runtime then terminates TLS with an ephemeral certificate authority that it writes to /etc/cloudflare/certs/cloudflare-containers-ca.crt when the container starts. Your container must trust that CA before it makes requests. For example:

Node.js

class Agent(Container):
    intercept_https = True
    env_vars = {
        "NODE_EXTRA_CA_CERTS": "/etc/cloudflare/certs/cloudflare-containers-ca.crt",
    }

System trust store (Debian)

entrypoint.sh
#!/bin/sh
cp /etc/cloudflare/certs/cloudflare-containers-ca.crt \
   /usr/local/share/ca-certificates/cloudflare-containers-ca.crt
update-ca-certificates
exec "$@"

Python (httpx, requests)

Both libraries verify against the certifi bundle, not the system trust store. Install the CA with the Debian entrypoint above, then point them at the system bundle:

class Agent(Container):
    intercept_https = True
    env_vars = {
        "SSL_CERT_FILE": "/etc/ssl/certs/ca-certificates.crt",
        "REQUESTS_CA_BUNDLE": "/etc/ssl/certs/ca-certificates.crt",
    }

The file only exists at runtime, so install it from your entrypoint, not in your Dockerfile. HTTPS interception needs a compatibility_date of 2026-04-02 or later. On an older runtime, the SDK raises a RuntimeError before applying any interception. See HTTPS traffic for the platform side.

Change rules at runtime

Rules set as class attributes apply to every instance. To change rules for one instance while it runs, register named handlers in outbound_handlers, then switch between them. ctx.params is generic, so parametrise OutboundHandlerContext to type the params a handler expects:

from typing import TypedDict


class TenantParams(TypedDict):
    tenant: str


async def allow_all(
    request: Request, env: Any, ctx: OutboundHandlerContext
) -> Response:
    return await fetch(request)


async def tag_tenant(
    request: Request, env: Any, ctx: OutboundHandlerContext[TenantParams]
) -> Response:
    if ctx.params is None:  # params are optional, so narrow before use
        return Response("missing tenant", status=500)
    headers = [*request.headers.items(), ("x-tenant", ctx.params["tenant"])]
    return await fetch(Request(request, headers=headers))


class Workspace(Container):
    default_port = 8080
    enable_internet = False
    outbound_handlers = {"allow_all": allow_all, "tag_tenant": tag_tenant}
container = get_container(self.env.WORKSPACE, workspace_id)

# Route one host through a named handler, with params
params: TenantParams = {"tenant": "acme"}
await container.set_outbound_by_host("api.example.com", "tag_tenant", params)

# Replace the catch-all handler
await container.set_outbound_handler("allow_all")

# Adjust host lists
await container.allow_host("pypi.org")
await container.deny_host("evil.example")
Method Effect
set_outbound_handler(name, params=None) Replace the catch-all outbound with a named handler.
set_outbound_by_host(hostname, name, params=None) Route one host or pattern to a named handler.
set_outbound_by_hosts(handlers) Replace all runtime host rules. Values are a handler name, or {"method": name, "params": ...}.
remove_outbound_by_host(hostname) Remove a runtime host rule. Any class-level outbound_by_host entry applies again.
set_allowed_hosts(hosts) / set_denied_hosts(hosts) Replace the allowlist or blocklist.
allow_host(hostname) / deny_host(hostname) Add one host to the allowlist or blocklist.
remove_allowed_host(hostname) / remove_denied_host(hostname) Remove one host from the allowlist or blocklist.

allow_host and remove_allowed_host on a class with no allowed_hosts create an allowlist, so every other host then gets a 520.

Changes apply to a running container without a restart. The SDK stores them in the Durable Object, so they survive the Durable Object leaving memory. A stored list replaces the class attribute on that instance, so changing allowed_hosts and redeploying doesn't reach it. Call set_allowed_hosts to change it. Naming a handler that isn't in outbound_handlers raises ValueError. Over RPC, pass these arguments positionally. See Calling container methods.

Precedence

The SDK checks each outbound request against these rules in order. The first rule that applies decides what happens:

  1. denied_hosts. The SDK blocks a matching host.
  2. allowed_hosts. If the list is set, the SDK blocks a host that doesn't match.
  3. Runtime host rules from set_outbound_by_host.
  4. Class host rules from outbound_by_host.
  5. Runtime catch-all from set_outbound_handler.
  6. Class catch-all from outbound.
  7. Egress. The request goes out to the internet if the host matched allowed_hosts or enable_internet is True. Otherwise the SDK blocks it.

Note

If your only rules are class-level outbound_by_host entries, only requests to those hosts go through ContainerProxy. Anything else, such as a catch-all, a host list or any runtime change, routes all of the container's HTTP traffic through it. That stays in place after the container restarts, because the SDK saves it in the Durable Object.