Skip to content

containers generated API reference

containers

__all__ = ('Container', 'ContainerProxy', 'DurableObjectNamespace', 'DurableObjectStub', 'OutboundHandler', 'OutboundHandlerContext', 'Schedule', 'Signal', 'State', 'get_container', 'get_random', 'load_balance', 'switch_port') module-attribute

__title__ = 'containers' module-attribute

__version__ = '0.2.2' module-attribute

__license__ = 'MIT OR Apache-2.0' module-attribute

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

Signal = Literal['SIGKILL', 'SIGINT', 'SIGTERM']

Container

Bases: DurableObject

A Durable Object that manages a container.

Configure it by setting class attributes on a subclass, e.g. default_port and sleep_after.

Attributes:

Name Type Description
default_port int | None

Port that requests go to when no port is given.

required_ports list[int] | None

Ports that must accept connections before the container is ready.

sleep_after str | float

Inactivity time after which the container gets a SIGTERM, as seconds or a time expression like "10m".

env_vars, entrypoint, enable_internet, labels

Start options for the container.

intercept_https bool

Intercept outbound HTTPS too. The container must trust /etc/cloudflare/certs/cloudflare-containers-ca.crt.

allowed_hosts list[str] | None

Hosts the container can reach, even when enable_internet is False.

denied_hosts list[str] | None

Hosts the container can never reach, even when enable_internet is True or an outbound handler is set.

ping_endpoint str

Host and path of the request that checks the container is ready. The container does not have to serve it.

outbound_by_host dict[str, OutboundHandler] | None

Maps hostnames to the handler for requests to that host.

outbound OutboundHandler | None

Handler for hosts that no more specific rule handles.

outbound_handlers dict[str, OutboundHandler] | None

Named handlers for set_outbound_handler and set_outbound_by_host.

outbound_proxies, outbound_proxy

Deprecated aliases of outbound_handlers and outbound.

default_port = None class-attribute instance-attribute

required_ports = None class-attribute instance-attribute

sleep_after = DEFAULT_SLEEP_AFTER class-attribute instance-attribute

env_vars = {} class-attribute instance-attribute

entrypoint = None class-attribute instance-attribute

enable_internet = True class-attribute instance-attribute

labels = {} class-attribute instance-attribute

intercept_https = False class-attribute instance-attribute

allowed_hosts = None class-attribute instance-attribute

denied_hosts = None class-attribute instance-attribute

ping_endpoint = 'ping' class-attribute instance-attribute

outbound_by_host = None class-attribute instance-attribute

outbound = None class-attribute instance-attribute

outbound_handlers = None class-attribute instance-attribute

__init_subclass__(**kwargs)

__init__(ctx, env, /, *, default_port=None, sleep_after=None, env_vars=None, entrypoint=None, enable_internet=None)

get_state() async

Get the current state of the container.

Returns:

Type Description
State

A copy of the current state.

set_outbound_handler(method_name, params=None) async

Set the catch-all outbound handler to a handler from outbound_handlers.

Overrides the default outbound at runtime via ContainerProxy props.

Parameters:

Name Type Description Default
method_name str

Name of a handler defined in outbound_handlers.

required
params Any

Optional params passed to the handler as ctx.params.

None

Raises:

Type Description
ValueError

If the method name is not found in outbound_handlers.

set_outbound_by_host(hostname, method_name, params=None) async

Add or override a hostname-specific outbound handler at runtime.

References a named handler from outbound_handlers, and overrides any matching entry in outbound_by_host for this hostname.

Parameters:

Name Type Description Default
hostname str

The hostname or ip:port to intercept (e.g. "google.com").

required
method_name str

Name of a handler defined in outbound_handlers.

required
params Any

Optional params passed to the handler as ctx.params.

None

Raises:

Type Description
ValueError

If the method name is not found in outbound_handlers.

remove_outbound_by_host(hostname) async

Remove a runtime hostname override added via set_outbound_by_host.

The default handler from outbound_by_host (if any) will be used again.

Parameters:

Name Type Description Default
hostname str

The hostname or ip:port to stop overriding.

required

set_outbound_by_hosts(handlers) async

Replace all runtime hostname overrides at once.

Parameters:

Name Type Description Default
handlers dict[str, str | OutboundHandlerOverride]

Maps hostnames to either a handler name in outbound_handlers, or a dict with method and params.

required

Raises:

Type Description
ValueError

If any method name is not found in outbound_handlers.

set_allowed_hosts(hosts) async

Replace all allowed hosts at runtime.

Allowed hosts get internet access even when enable_internet is False.

Parameters:

Name Type Description Default
hosts list[str]

Hostnames to allow (e.g. ["api.stripe.com", "example.com"]).

required

set_denied_hosts(hosts) async

Replace all denied hosts at runtime.

Denied hosts are blocked unconditionally, even when enable_internet is True or a catch-all outbound handler is set.

Parameters:

Name Type Description Default
hosts list[str]

Hostnames to deny (e.g. ["evil.com", "blocked.org"]).

required

allow_host(hostname) async

Add a single hostname to the allowed hosts list at runtime.

Parameters:

Name Type Description Default
hostname str

The hostname to allow (e.g. "api.stripe.com").

required

deny_host(hostname) async

Add a single hostname to the denied hosts list at runtime.

Parameters:

Name Type Description Default
hostname str

The hostname to deny (e.g. "evil.com").

required

remove_allowed_host(hostname) async

Remove a hostname from the allowed hosts list.

Parameters:

Name Type Description Default
hostname str

The hostname to remove from the allow list.

required

remove_denied_host(hostname) async

Remove a hostname from the denied hosts list.

Parameters:

Name Type Description Default
hostname str

The hostname to remove from the deny list.

required

start(*, env_vars=None, entrypoint=None, enable_internet=None, labels=None, port_to_check=None, signal=None, retries=None, wait_interval=None) async

Start the container if it's not running, without waiting for ports.

Sets up monitoring and lifecycle hooks. It will automatically retry if the container fails to start.

Parameters:

Name Type Description Default
env_vars dict[str, str] | None

Override the class attributes of the same name for this start.

None
entrypoint dict[str, str] | None

Override the class attributes of the same name for this start.

None
enable_internet dict[str, str] | None

Override the class attributes of the same name for this start.

None
labels dict[str, str] | None

Override the class attributes of the same name for this start.

None
port_to_check int | None

Port used to check the container is up. Defaults to default_port, then the first of required_ports.

None
signal Event | None

Set this event to abort waiting for the container to start.

None
retries int | None

Number of attempts. Defaults to about 8s worth of attempts.

None
wait_interval int | None

Time between attempts, in milliseconds.

None

Raises:

Type Description
RuntimeError

If all start attempts fail.

Examples:

>>> await self.start(
...     env_vars={"DEBUG": "true", "NODE_ENV": "development"},
...     entrypoint=["npm", "run", "dev"],
...     enable_internet=False,
...     labels={"tenant": "acme", "env": "prod"},
... )

start_and_wait_for_ports(ports=None, /, *, abort=None, instance_get_timeout_ms=None, port_ready_timeout_ms=None, wait_interval=None, env_vars=None, entrypoint=None, enable_internet=None, labels=None) async

Start the container and wait for ports to be available.

For each port, it polls until the port is available or port_ready_timeout_ms is reached.

Parameters:

Name Type Description Default
ports int | list[int] | None

The ports to wait for. Defaults to required_ports, then default_port.

None
abort Event | None

Set this event to abort starting the container.

None
instance_get_timeout_ms int | None

Max time to get a container instance and start it, in milliseconds. The application inside may not be ready yet.

None
port_ready_timeout_ms int | None

Max time to wait for the application to be listening on all ports, in milliseconds.

None
wait_interval int | None

Time to wait between polling, in milliseconds.

None
env_vars dict[str, str] | None

Override the class attributes of the same name for this start.

None
entrypoint dict[str, str] | None

Override the class attributes of the same name for this start.

None
enable_internet dict[str, str] | None

Override the class attributes of the same name for this start.

None
labels dict[str, str] | None

Override the class attributes of the same name for this start.

None

Raises:

Type Description
RuntimeError

If port checks fail after the timeout, or the container fails to start.

wait_for_port(port_to_check, /, *, signal=None, retries=None, wait_interval=None) async

Wait for a port to be ready.

Parameters:

Name Type Description Default
port_to_check int

The port number to check.

required
signal Event | None

Set this event to abort waiting.

None
retries int | None

Number of retries before giving up. Defaults to about 20s worth.

None
wait_interval int | None

Time between retries, in milliseconds.

None

Returns:

Type Description
int

The number of tries.

Raises:

Type Description
Exception

The last connection error, if the port wasn't ready within the retries.

stop(signal='SIGTERM') async

Send a signal to the container.

Parameters:

Name Type Description Default
signal Signal | int

The signal to send, as a name or a number. signal.Signals members work too.

'SIGTERM'

destroy() async

Destroy the container with a SIGKILL. Triggers on_stop.

on_start() async

Lifecycle method called when the container starts successfully.

Override this method in subclasses to handle container start events.

on_stop(*, exit_code, reason) async

Lifecycle method called when the container shuts down.

Override this method in subclasses to handle container stopped events.

Parameters:

Name Type Description Default
exit_code int

The exit code of the container.

required
reason Literal['exit', 'runtime_signal']

Why the container stopped.

required

on_activity_expired() async

Lifecycle method called when the activity timeout has been reached.

Called when the container is running and the activity timeout expiration (set by sleep_after) has been reached. If you want to shutdown the container, you should call self.stop() here.

By default, this method calls self.stop().

on_error(error) async

Error handler for container errors.

Override this method in subclasses to handle container errors.

Parameters:

Name Type Description Default
error Exception

The error that occurred.

required

Raises:

Type Description
Exception

By default, re-raises error.

renew_activity_timeout()

Renew the container's activity timeout.

Call this method whenever there is activity on the container.

schedule(when, callback, payload=None) async

Schedule a task to be executed in the future.

We strongly recommend using this instead of the alarm handler.

Parameters:

Name Type Description Default
when datetime | float

When to execute the task, as a datetime or a delay in seconds.

required
callback str

Name of the method to call. It must be an async def method and is called with (payload, schedule).

required
payload T | None

Data to pass to the callback. Must be JSON serialisable.

None

Returns:

Type Description
Schedule

The scheduled task.

Raises:

Type Description
TypeError

If callback is not a string, or when is of the wrong type.

ValueError

If callback is not a method on this container.

container_fetch(request_or_url, /, port=None, **init) async

Send a request to the container (HTTP or WebSocket).

WebSocket requests done outside the DO won't work until https://github.com/cloudflare/workerd/issues/2319 is addressed. Until then, please use switch_port + fetch().

Supports two forms:

  • container_fetch(request, port=None)
  • container_fetch(url, port=None, **init), where init takes the same options as workers.Request (method, headers, body...)

Starts the container if not already running, and waits for the target port to be ready.

Parameters:

Name Type Description Default
request_or_url Request | str

A request, or an absolute or relative URL.

required
port int | None

The container port. Defaults to default_port.

None
**init Unpack[FetchKwargs]

Request options, only when request_or_url is a URL.

{}

Returns:

Type Description
Response

A response from the container.

Raises:

Type Description
ValueError

If no port is given and default_port is not set.

fetch(request) async

Fetch handler on the Container class.

By default this forwards all requests to the container by calling container_fetch. Use switch_port to specify which port on the container to target, or this will use default_port.

Parameters:

Name Type Description Default
request Request

The request to handle.

required

Returns:

Type Description
Response

A response from the container.

Raises:

Type Description
ValueError

If no port is configured, or the port set by switch_port is not a number.

delete_schedules(name)

Delete all scheduled tasks for a callback.

Parameters:

Name Type Description Default
name str

The callback method name.

required

alarm(alarm_info=None) async

Method called when an alarm fires.

Executes any scheduled tasks that are due.

schedule_next_alarm(ms=1000) async

Schedule the next alarm based on upcoming tasks.

Parameters:

Name Type Description Default
ms int

Delay until the next alarm, in milliseconds.

1000

list_schedules(name) async

List scheduled tasks for a callback.

Parameters:

Name Type Description Default
name str

The callback method name.

required

Returns:

Type Description
list of Schedule

The scheduled tasks.

get_schedule(id) async

Get a scheduled task by ID.

Parameters:

Name Type Description Default
id str

ID of the scheduled task.

required

Returns:

Type Description
Schedule or None

The scheduled task, or None if not found.

ContainerProxy

Bases: WorkerEntrypoint

Handles outbound HTTP from containers.

It must be importable from the Worker entry module for outbound interception to work.

fetch(request) async

OutboundHandlerContext

Bases: Generic[ParamsT]

Context passed to outbound handlers.

Parameters:

Name Type Description Default
container_id str

The ID of the Durable Object the container belongs to.

required
class_name str

The name of the Container subclass.

required
params ParamsT | None

Params given to set_outbound_handler or set_outbound_by_host.

None

container_id = container_id instance-attribute

class_name = class_name instance-attribute

params = params instance-attribute

__init__(container_id, class_name, params=None)

Schedule

Bases: TypedDict, Generic[PayloadT]

Represents a scheduled task within a Container.

type is "scheduled" for one-time execution at a specific time, or "delayed" for delayed execution, in which case delay_in_seconds is set.

task_id instance-attribute

callback instance-attribute

payload instance-attribute

type instance-attribute

time instance-attribute

delay_in_seconds instance-attribute

State

Bases: TypedDict

The container state.

running means that the container is trying to start and is transitioning to a healthy status. on_stop might be triggered if there is an exit code, and it will transition to stopped.

status instance-attribute

last_change instance-attribute

exit_code instance-attribute

DurableObjectNamespace

Bases: Protocol

A Durable Object namespace binding, e.g. self.env.MY_CONTAINER.

idFromName(name)

get(id)

DurableObjectStub

Bases: Protocol

A Durable Object stub, as returned by a Durable Object namespace binding.

fetch(request, /, **kwargs)

__getattr__(name)

get_container(binding, name=SINGLETON_CONTAINER_ID)

Get a container stub.

Parameters:

Name Type Description Default
binding DurableObjectNamespace

The Container's Durable Object binding.

required
name str

The name of the instance to get, "cf-singleton-container" by default.

SINGLETON_CONTAINER_ID

Returns:

Type Description
DurableObjectStub

A container stub ready to handle requests.

get_random(binding, instances=3) async

Get a random container instance across N instances.

This is useful for load balancing.

Parameters:

Name Type Description Default
binding DurableObjectNamespace

The Container's Durable Object binding.

required
instances int

Number of instances to load balance across.

3

Returns:

Type Description
DurableObjectStub

A container stub ready to handle requests.

load_balance(binding, instances=3) async

Deprecated alias of get_random.

Parameters:

Name Type Description Default
binding DurableObjectNamespace

The Container's Durable Object binding.

required
instances int

Number of instances to load balance across.

3

Returns:

Type Description
DurableObjectStub

A container stub ready to handle requests.

switch_port(request, port)

Return a request with the port target set correctly.

Use this when you have to use fetch and not container_fetch, as container_fetch is an RPC method and can't pass WebSockets.

Parameters:

Name Type Description Default
request Request

The request to target.

required
port int

The container port to send the request to.

required

Returns:

Type Description
Request

A copy of request with the cf-container-target-port header set.

Examples:

>>> await container.fetch(switch_port(request, 8090))