Skip to content

Run Cloudflare Containers from Python Workers

This guide puts a small FastAPI app in a container and routes requests to it from a Python Worker. By the end, each ?id= value in the URL gets its own container instance.

Prerequisites

  • uv and Node.js, to build and deploy Python Workers. containers-py needs Python 3.12 or later and works with either crosswind-workers or workers-runtime-sdk. This guide uses pywrangler, which installs workers-runtime-sdk.
  • Docker, or another Docker-compatible engine, running locally. Check with docker info. Wrangler builds your image with it in both dev and deploy.
  • A Cloudflare account on the Workers Paid plan, which Containers requires. See Pricing.

1. Create a Python Worker

Create a project with pywrangler, then add containers-py:

uvx --from workers-py pywrangler init
cd hello-containers  # the directory you chose during init
uv add containers-py

pyproject.toml now lists the package:

pyproject.toml
[project]
name = "hello-containers"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = ["containers-py"]

[dependency-groups]
dev = ["workers-py"]

2. Write the container

Any image that listens on a port works. This one runs a FastAPI app with uvicorn on port 8080. The container is a separate Python project from the Worker, so it gets its own pyproject.toml:

container_src/pyproject.toml
[project]
name = "container-app"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
    "fastapi>=0.115",
    "pydantic-settings>=2.6",
    "uvicorn[standard]>=0.32",
]

Lock it, so every image build installs the same versions:

cd container_src && uv lock && cd ..
container_src/main.py
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    # Read from the MESSAGE environment variable
    message: str = "no message set"


class Echo(BaseModel):
    text: str


settings = Settings()
app = FastAPI(title="hello-containers")


@app.get("/")
async def index() -> dict[str, str]:
    return {"message": settings.message}


@app.post("/echo")
async def echo(body: Echo) -> Echo:
    return body

The Dockerfile installs the locked dependencies before it copies your code, so editing main.py doesn't reinstall them:

Dockerfile
FROM python:3.13-slim

# Pin a specific uv version in production
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=0 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# Docker caches this layer until the lockfile changes
COPY container_src/pyproject.toml container_src/uv.lock ./
RUN uv sync --locked --no-install-project --no-dev

COPY container_src/main.py ./

ENV PATH="/app/.venv/bin:$PATH"

EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

Wrangler uses the project root as the build context. Keep the Worker's virtual environment and vendored packages out of the image:

.dockerignore
.git
.venv
.wrangler
python_modules
node_modules
**/__pycache__

The server doesn't need a health-check route. While the container starts, the SDK sends plain HTTP requests to the port it's waiting for, every 300 milliseconds for up to 20 seconds. It treats any response as ready, including a 404. The port check requests http://ping unless you set ping_endpoint.

3. Define the Container class

Replace src/entry.py:

src/entry.py
from urllib.parse import parse_qs, urlparse

from containers import Container, get_container, get_random
from workers import Request, Response, WorkerEntrypoint


class MyContainer(Container):
    default_port = 8080
    sleep_after = "2m"
    env_vars = {"MESSAGE": "I was passed in via the Container class!"}

    async def on_start(self) -> None:
        print("Container successfully started")

    async def on_stop(self, *, exit_code: int, reason: str) -> None:
        print(f"Container stopped with exit code {exit_code} ({reason})")


class Default(WorkerEntrypoint):
    async def fetch(self, request: Request) -> Response:
        query = parse_qs(urlparse(request.url).query)

        if "id" in query:
            # One container per ID: ?id=<id>
            container = get_container(self.env.MY_CONTAINER, query["id"][0])
        elif "lb" in query:
            # One of 3 interchangeable instances: ?lb
            container = await get_random(self.env.MY_CONTAINER, 3)
        else:
            # One shared instance
            container = get_container(self.env.MY_CONTAINER)

        return await container.fetch(request)

default_port is the port fetch() forwards to. sleep_after stops the container after 2 minutes without requests. The SDK passes env_vars to the container on every start.

Define MyContainer in src/entry.py or import it there. The runtime looks in that module for the Durable Object class named in your Wrangler config.

4. Configure Wrangler

{
  "name": "hello-containers",
  "main": "src/entry.py",
  "compatibility_date": "2026-05-12",
  "compatibility_flags": ["python_workers"],
  "containers": [
    {
      "class_name": "MyContainer",
      "image": "./Dockerfile",
      "max_instances": 10
    }
  ],
  "durable_objects": {
    "bindings": [{ "class_name": "MyContainer", "name": "MY_CONTAINER" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyContainer"] }]
}
name = "hello-containers"
main = "src/entry.py"
compatibility_date = "2026-05-12"
compatibility_flags = ["python_workers"]

[[containers]]
class_name = "MyContainer"
image = "./Dockerfile"
max_instances = 10

[[durable_objects.bindings]]
class_name = "MyContainer"
name = "MY_CONTAINER"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["MyContainer"]
# cloudflare.config.py needs Wynd: run `uvx wynd dev` in place of `pywrangler dev`.
from wynd.config import Config, Container, Worker, bindings, exports

container = Container(
    name="hello-containers-mycontainer",
    dockerfile="./Dockerfile",
    max_instances=10,
)

config = Config(
    worker=Worker(
        name="hello-containers",
        entrypoint="src/entry.py",
        compatibility_date="2026-05-12",
        env={"MY_CONTAINER": bindings.DurableObject("MyContainer")},
        exports={"MyContainer": exports.DurableObject(container=container)},
    ),
)
Key What it does
containers[].class_name Links the image to your Container subclass. Must match the class name in src/entry.py.
containers[].image A Dockerfile, a directory or a registry image. See Image management.
containers[].max_instances The most instances of this class that can run at once.
durable_objects.bindings Exposes the class to the Worker as self.env.MY_CONTAINER.
migrations Declares the class as a SQLite-backed Durable Object. Container needs SQLite.

For every option, including instance_type, see Wrangler configuration.

5. Run locally

uv run pywrangler dev

Wrangler builds the image and runs containers on your machine. The first build downloads the base image, so it takes longer than later builds. Worker code reloads on save. Container code doesn't, so press r in the dev session to rebuild the image.

In another terminal:

curl "http://localhost:8787/?id=abc"
{"message":"I was passed in via the Container class!"}
curl -X POST "http://localhost:8787/echo?id=abc" \
  -H "content-type: application/json" \
  -d '{"text": "hello"}'
{"text":"hello"}

The first request to a new id starts a container, which takes a few seconds. Later requests with the same id reach the running instance until it sleeps. The dev terminal prints Container successfully started once per start.

6. Deploy

uv run pywrangler deploy

Wrangler builds the image, pushes it to Cloudflare's registry and deploys the Worker. The first deploy takes a few minutes to provision. Until then, requests that need a container get a 503. Check progress with:

npx wrangler containers list

Then send the same curl requests to your workers.dev URL.

Next steps