Skip to content

Container class API reference for Python

Use this reference to configure and control a containers.Container subclass. Container is a Durable Object that manages one container instance. Set its class attributes and override the hooks you need. You can also use the base DurableObject attributes, including self.ctx, self.env and SQLite storage through self.ctx.storage.

from containers import Container


class MyContainer(Container):
    default_port = 8080
    sleep_after = "10m"

This page mirrors the official Container class reference. Where the Python API differs, see Coming from TypeScript.

Properties

Set these as class attributes on your subclass. They apply to every instance.

Attribute Type Default Description
default_port int \| None None Port the container listens on. fetch() and container_fetch() use it when no port is given.
required_ports list[int] \| None None Ports that must accept connections before the container counts as ready. start_and_wait_for_ports() uses them when called without ports.
sleep_after str \| float "10m" Idle time before on_activity_expired() runs. Seconds as a number, or a string such as "30s", "5m" or "1h".
env_vars dict[str, str] {} Environment variables passed to the container on every start.
entrypoint list[str] \| None None Overrides the image's entrypoint.
enable_internet bool True Whether the container can reach the internet. See Outbound traffic.
labels dict[str, str] {} Labels attached to the container instance.
ping_endpoint str "ping" Host and path that readiness checks request, as http://<ping_endpoint>.
intercept_https bool False Intercept outbound HTTPS as well as HTTP. See HTTPS.
allowed_hosts list[str] \| None None Hosts the container may reach. Glob patterns allowed.
denied_hosts list[str] \| None None Hosts the container may never reach. Glob patterns allowed.
outbound_by_host dict[str, OutboundHandler] \| None None Outbound handlers by hostname or pattern.
outbound OutboundHandler \| None None Catch-all outbound handler.
outbound_handlers dict[str, OutboundHandler] \| None None Named handlers that can be selected at runtime.

Setting values per instance

To compute values when the Durable Object is created, for example from a secret in self.env, set them after calling super().__init__(). The constructor also accepts default_port, sleep_after, env_vars, entrypoint and enable_internet as keyword arguments:

from typing import Any

from containers import Container


class MyContainer(Container):
    def __init__(self, ctx: Any, env: Any) -> None:
        super().__init__(ctx, env, default_port=8080, sleep_after="5m")
        self.env_vars = {"API_KEY": env.API_KEY}

Lifecycle hooks

Override these on your subclass. Each can be def or async def. See Lifecycle for when each one runs.

on_start

async def on_start(self) -> None

Runs after the container starts successfully, from start(), start_and_wait_for_ports(), or a request that started it. By default it does nothing.

on_stop

async def on_stop(
    self, *, exit_code: int, reason: Literal["exit", "runtime_signal"]
) -> None

Runs after the container process exits, the next time the SDK checks the state. reason is always "exit" in this version. By default it does nothing. Annotating reason as str in your override is also valid, because an override may accept a wider type.

on_error

async def on_error(self, error: Exception) -> None

Runs when starting the container or waiting for a port fails, and when the runtime reports a failure without an exit code. By default it logs error and re-raises it. It doesn't run when the platform has no instance to assign. That failure raises from the start call, so catch it there.

on_activity_expired

async def on_activity_expired(self) -> None

Runs when the container has been idle for sleep_after. By default it calls self.stop(). If you override it, stop or destroy the container yourself, or it never goes to sleep.

Request methods

fetch

async def fetch(self, request: Request) -> Response

The Durable Object's fetch handler. It forwards the request, HTTP or WebSocket, to the container with container_fetch(), starting the container first if needed. It uses the port set by switch_port, or default_port. Raises ValueError if neither is set.

Override it to add routing or authentication, and forward with self.container_fetch() to avoid recursion.

container_fetch

async def container_fetch(
    self,
    request_or_url: Request | str,
    /,
    port: int | None = None,
    **init: Unpack[FetchKwargs],
) -> Response

Sends a request to the container. If the container isn't healthy, it starts it and waits for port first. port defaults to default_port. With a URL, init takes the same keyword arguments as workers.Request, such as method, headers and body, typed with the workers SDK's FetchKwargs. The URL can be relative.

from http import HTTPMethod

response = await self.container_fetch(
    "/api/items", port=9090, method=HTTPMethod.POST, body="{}"
)

FetchKwargs types method as http.HTTPMethod or str, so "POST" also works.

  • Raises ValueError if no port is given and default_port isn't set.
  • Raises TypeError if init options are passed with a Request.
  • Returns a 503, 429 or 500 response when the container can't be started or reached. See Troubleshooting.
  • Proxies WebSockets when called inside the Durable Object. From a Worker, use stub.fetch() instead. See WebSockets.

Start and stop

Durations are in milliseconds for every option below, as in the TypeScript SDK. sleep_after and schedule() use seconds.

start_and_wait_for_ports

async def start_and_wait_for_ports(
    self,
    ports: int | list[int] | None = None,
    /,
    *,
    abort: asyncio.Event | None = None,
    instance_get_timeout_ms: int | None = None,  # default 8_000
    port_ready_timeout_ms: int | None = None,    # default 20_000
    wait_interval: int | None = None,            # default 300
    env_vars: dict[str, str] | None = None,
    entrypoint: list[str] | None = None,
    enable_internet: bool | None = None,
    labels: dict[str, str] | None = None,
) -> None

Starts the container if it isn't running, waits until every port accepts connections, marks it healthy and runs on_start(). Ports resolve in this order: ports, then required_ports, then default_port, then port 33 as a last resort. Before it starts, it runs on_stop() for any exit the SDK hasn't reported yet.

  • abort: set this asyncio.Event to cancel waiting. Only usable inside the Durable Object.
  • instance_get_timeout_ms: how long to wait for an instance to be assigned and started. Your application may not be ready yet at that point.
  • port_ready_timeout_ms: the budget for each port. The SDK converts it to attempts, ceil(port_ready_timeout_ms / wait_interval), and subtracts the attempts the start used. Each port then gets that many attempts. If the start used them all, the SDK skips the port checks and marks the container healthy, so keep this longer than instance_get_timeout_ms.
  • wait_interval: the time between polls.
  • env_vars, entrypoint, enable_internet, labels: override the class attributes for this start only.

Raises RuntimeError if the container can't be started, and re-raises the last connection error if a port isn't ready in time. The container keeps running in the running state after a port timeout. See When a start fails or times out.

start

async def start(
    self,
    *,
    env_vars: dict[str, str] | None = None,
    entrypoint: list[str] | None = None,
    enable_internet: bool | None = None,
    labels: dict[str, str] | None = None,
    port_to_check: int | None = None,
    signal: asyncio.Event | None = None,
    retries: int | None = None,
    wait_interval: int | None = None,  # default 300
) -> None

Starts the container without waiting for your application's ports, then runs on_start(). The state stays running. Use it for batch jobs, or when you check readiness yourself.

port_to_check defaults to default_port, then the first of required_ports, then port 33. retries defaults to ceil(8_000 / wait_interval), which is 27 attempts at the default 300 milliseconds. Each attempt's request times out after 5,000 milliseconds. Raises RuntimeError if every attempt fails.

await self.start(
    env_vars={"DEBUG": "true"},
    entrypoint=["python", "worker.py"],
    enable_internet=False,
    labels={"tenant": "acme"},
)

wait_for_port

async def wait_for_port(
    self,
    port_to_check: int,
    /,
    *,
    signal: asyncio.Event | None = None,
    retries: int | None = None,
    wait_interval: int | None = None,
) -> int

Polls one port until it accepts connections. retries defaults to ceil(20_000 / wait_interval), which is 67 attempts at the default 300 milliseconds, and each request times out after 5,000 milliseconds.

Returns the retries value it ran with, not the number of attempts it used. The TypeScript SDK does the same.

Raises the last connection error if the port never becomes ready, or right away if the container crashes. Raises RuntimeError: Container request aborted. if signal is set while it waits.

stop

async def stop(self, signal: Signal | int = "SIGTERM") -> None

Sends a signal to the container's main process. Accepts a signal name, a number or a signal.Signals member. Signal is Literal["SIGKILL", "SIGINT", "SIGTERM"]. It returns without waiting for the process to exit. on_stop() runs after the exit, the next time the SDK checks the state.

destroy

async def destroy(self) -> None

Kills the container with SIGKILL. on_stop() runs after the exit, the next time the SDK checks the state.

State and monitoring

get_state

async def get_state(self) -> State

Returns a copy of the current state:

class State(TypedDict):
    status: Literal["running", "healthy", "stopping", "stopped", "stopped_with_code"]
    last_change: int  # Unix time in milliseconds
    exit_code: NotRequired[int]  # set when status is "stopped_with_code"

See States.

renew_activity_timeout

def renew_activity_timeout(self) -> None

Resets the sleep_after timer. Requests through the SDK already do this, so call it only for activity the SDK can't see. This method is not a coroutine.

Scheduling

The Container class uses the Durable Object alarm for its own lifecycle management. Don't override alarm(). Use schedule() instead.

schedule

async def schedule[T](
    self, when: datetime | float, callback: str, payload: T | None = None
) -> Schedule[T | None]

Runs the method named callback later, once.

  • when: a datetime, or a delay in seconds.
  • callback: the name of an async def method on your subclass. It's called as await self.<callback>(payload, schedule).
  • payload: optional data passed to the callback. Must be JSON serialisable.

Raises TypeError if callback isn't a string or when has the wrong type, and ValueError if no such method exists. If the callback raises, the SDK logs the error and still removes the task.

from datetime import datetime, timedelta, timezone
from http import HTTPMethod
from typing import TypedDict

from containers import Container, Schedule


class RotatePayload(TypedDict):
    keep: int


class MyContainer(Container):
    async def on_start(self) -> None:
        await self.schedule(30, "warm_cache")
        await self.schedule(
            datetime.now(timezone.utc) + timedelta(hours=1),
            "rotate_logs",
            RotatePayload(keep=5),
        )

    async def warm_cache(self, payload: None, schedule: Schedule[None]) -> None:
        await self.container_fetch("/warm", method=HTTPMethod.POST)

    async def rotate_logs(
        self, payload: RotatePayload, schedule: Schedule[RotatePayload]
    ) -> None:
        await self.container_fetch(
            f"/logs/rotate?keep={payload['keep']}", method=HTTPMethod.POST
        )

on_start() can run more than once per container, so this sample adds new tasks on every start. Check list_schedules() first, as in Recurring work.

The SDK looks up callbacks by name at runtime, so a type checker can't connect the callback string to the method. Keep the payload type and the callback's payload annotation in sync yourself.

The returned Schedule is a dict:

class Schedule(TypedDict, Generic[PayloadT]):
    task_id: str
    callback: str
    payload: PayloadT
    type: Literal["scheduled", "delayed"]  # "scheduled" for a datetime, "delayed" for seconds
    time: int  # Unix time in seconds when it runs
    delay_in_seconds: NotRequired[float]  # set for "delayed" tasks

get_schedule, list_schedules, delete_schedules

async def get_schedule(self, id: str) -> Schedule[PayloadT] | None
async def list_schedules(self, name: str) -> list[Schedule[PayloadT]]
def delete_schedules(self, name: str) -> None
  • get_schedule looks up a task by its task_id. It returns None once the task has run or been deleted.
  • list_schedules returns pending tasks for the callback name.
  • delete_schedules removes every pending task for the callback name. It is not a coroutine.

As in the TypeScript SDK, PayloadT defaults to str. Annotate the result to get your payload type:

tasks: list[Schedule[RotatePayload]] = await self.list_schedules("rotate_logs")

schedule_next_alarm

async def schedule_next_alarm(self, ms: int = 1000) -> None

Sets the Durable Object alarm to fire in ms milliseconds, 1,000 by default. The SDK calls this itself, so you rarely need to.

Outbound interception

These methods change the outbound rules of one running instance. Handler names refer to keys in outbound_handlers. Unknown names raise ValueError. OutboundHandlerOverride is a TypedDict of the form {"method": str, "params": Any}, where params is optional. It isn't re-exported from containers; import it from containers.container if you need it. See Outbound traffic for the full guide.

async def set_outbound_handler(self, method_name: str, params: Any = None) -> None
async def set_outbound_by_host(
    self, hostname: str, method_name: str, params: Any = None
) -> None
async def set_outbound_by_hosts(
    self, handlers: dict[str, str | OutboundHandlerOverride]
) -> None
async def remove_outbound_by_host(self, hostname: str) -> None
async def set_allowed_hosts(self, hosts: list[str]) -> None
async def set_denied_hosts(self, hosts: list[str]) -> None
async def allow_host(self, hostname: str) -> None
async def deny_host(self, hostname: str) -> None
async def remove_allowed_host(self, hostname: str) -> None
async def remove_denied_host(self, hostname: str) -> None

OutboundHandler

type OutboundHandler = Callable[
    [Request, Any, OutboundHandlerContext[Any]], Response | Awaitable[Response]
]

A plain or async function taking (request, env, ctx):

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

OutboundHandlerContext

Attribute Type Description
container_id str ID of the Durable Object that owns the container.
class_name str Name of the Container subclass.
params ParamsT \| None Params given to set_outbound_handler or set_outbound_by_host.

OutboundHandlerContext is generic over ParamsT, which defaults to Any. Write OutboundHandlerContext[MyParams] to type ctx.params.

ContainerProxy

The Worker entrypoint that runs outbound handlers. Import it in your Worker's entry module whenever you use outbound configuration:

from containers import ContainerProxy  # noqa: F401

Utility functions

get_container

def get_container(
    binding: DurableObjectNamespace, name: str = "cf-singleton-container"
) -> DurableObjectStub

Returns the stub for the instance called name. It isn't a coroutine, so don't await it.

get_random

async def get_random(
    binding: DurableObjectNamespace, instances: int = 3
) -> DurableObjectStub

Returns the stub for one of instances instances, chosen at random.

load_balance is a deprecated alias that also emits a DeprecationWarning.

switch_port

def switch_port(request: Request, port: int) -> Request

Returns a copy of request that Container.fetch() sends to port.

return await container.fetch(switch_port(request, 9090))

See Route requests for how to use all three.

Exports

Everything public is importable from containers:

Name Kind
Container, ContainerProxy Classes
get_container, get_random, switch_port Functions
load_balance Deprecated function
State, Schedule TypedDicts
Signal, OutboundHandler Type aliases
OutboundHandlerContext Class
DurableObjectNamespace, DurableObjectStub Typing-only Protocols

Type hints

The package ships a py.typed marker, and the public API is fully annotated. It supports Python 3.12 and later. A few things are looser, because the Workers runtime doesn't ship Python types for them:

  • self.env, self.ctx and self.ctx.container are untyped JavaScript objects.
  • On a DurableObjectStub, only fetch() is typed. Every other attribute is Any. See Typing calls on a stub.
  • schedule() callbacks are found by name, so their payload types aren't checked against the call that scheduled them.

Logging

The SDK logs through the standard logging module to the containers.container logger. It logs errors with logger.error, and routine events such as an activity timeout with logger.info. To see the info messages, lower the level:

import logging

logging.getLogger("containers").setLevel(logging.INFO)

Output ends up in your Worker's logs. See Logs.