Python Labs · Lab 4 of 6
Containerise the API: Dockerfile, Compose and Postgres
Package the catalog API in a small, non-root container image built with uv, then run it with Postgres in Docker Compose: health checks, start-up order, persistent data and switching databases with one environment variable.
- Environment
- Container
- Level
- Intermediate
- Time
- About 45 min
- Cost
- Free
You will build
docker compose up starts Postgres and the API in the right order, the API stores products in Postgres, and the
data survives restarts.
Before you start
- Lab: A Tested REST API with FastAPI and SQLAlchemy
Docker with Compose v2 (
docker compose version)
You continue in the `catalog` project from the previous lab. The application code does not change: only the
database URL does.
Downloaded the finished project instead of building it step by step? Run uv lock first: the Docker build
installs exactly what uv.lock says (--frozen), and the download doesn't include one.
Project structure
catalog/ ├── .dockerignore # keeps .venv, tests and local files out of the image ├── .gitignore ├── Dockerfile ├── compose.yaml # db + api ├── pyproject.toml ├── uv.lock ├── src/catalog/... └── tests/...
Steps
-
1Add the Postgres driver
Run uv add "psycopg[binary]"Expected output
Resolved 30 packages in 6ms ... Installed 3 packages in 1ms - catalog==0.1.0 (from file://.../catalog) + catalog==0.1.0 (from file://.../catalog) + psycopg==3.3.9 + psycopg-binary==3.3.9
Check:Nothing in
src/changes: SQLAlchemy picks the driver from the URL (postgresql+psycopg://...). -
2Write a two-stage Dockerfile
The build stage installs dependencies with uv; the runtime stage copies only the finished virtual environment, so compilers, uv and caches never reach production. Dependencies are installed before the source is copied, so editing code doesn't reinstall every package. The app runs as an unprivileged user.
Dockerfile # syntax=docker/dockerfile:1 # Build stage: resolve and install dependencies with uv into /app/.venv. FROM python:3.12-slim AS build COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /bin/uv WORKDIR /app ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 # Dependencies first: this layer is cached until pyproject.toml or uv.lock change. COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev --no-install-project COPY README.md ./ COPY src ./src RUN uv sync --frozen --no-dev --no-editable # Runtime stage: only the virtual environment, run as a non-root user. FROM python:3.12-slim RUN useradd --create-home --uid 10001 app WORKDIR /app COPY --from=build --chown=app:app /app/.venv /app/.venv ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1 USER app EXPOSE 8000 CMD ["uvicorn", "catalog.main:app", "--host", "0.0.0.0", "--port", "8000"] -
3Keep the build context small
Everything not listed here is sent to the Docker daemon; your local
.venvwould otherwise be copied in..dockerignore .venv .git __pycache__ *.db dist tests .pytest_cache .ruff_cache -
4Describe the stack
depends_onwithservice_healthywaits until Postgres accepts connections, not just until its container starts. The API has its own health check too: without it,docker compose up --waitreturns as soon as the API container starts, before uvicorn listens, and your first request fails (this happened while recording the lab).compose.yaml services: db: image: postgres:18-alpine environment: POSTGRES_DB: catalog POSTGRES_USER: catalog POSTGRES_PASSWORD: catalog-dev-only volumes: - pgdata:/var/lib/postgresql healthcheck: test: ["CMD-SHELL", "pg_isready -U catalog -d catalog"] interval: 2s timeout: 3s retries: 15 api: build: . environment: DATABASE_URL: postgresql+psycopg://catalog:catalog-dev-only@db:5432/catalog ports: - "${API_PORT:-8000}:8000" depends_on: db: condition: service_healthy healthcheck: # The slim image has no curl, so ask Python to fetch the health endpoint. test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"] interval: 5s timeout: 3s retries: 5 start_period: 5s volumes: pgdata:Hint
The password here is for your laptop only. The production lab moves it to an
.envfile. -
5Build and start
Run docker compose up -d --build --waitCheck:The command returns only when both containers report
Healthy. -
6Check the services
Run docker compose ps --format "table {{.Service}}\t{{.State}}\t{{.Status}}"Expected output
SERVICE STATE STATUS api running Up 5 seconds (healthy) db running Up 8 seconds (healthy)
-
7Use the API
Run curl -s localhost:8000/healthz curl -s -X POST localhost:8000/products -H 'Content-Type: application/json' \ -d '{"name": "Coffee mug", "price_cents": 1299}' curl -s localhost:8000/productsExpected output
{"status":"ok"} {"name":"Coffee mug","price_cents":1299,"id":1} [{"name":"Coffee mug","price_cents":1299,"id":1}] -
8Look inside Postgres
Run docker compose exec db psql -U catalog -d catalog -c 'SELECT * FROM products;'Expected output
id | name | price_cents ----+------------+------------- 1 | Coffee mug | 1299 (1 row)
-
9Read the logs
Run docker compose logs apiExpected output
api-1 | INFO: Started server process [1] api-1 | INFO: Waiting for application startup. api-1 | INFO: Application startup complete. api-1 | INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) api-1 | INFO: 127.0.0.1:37284 - "GET /healthz HTTP/1.1" 200 OK api-1 | INFO: 172.23.0.1:42240 - "GET /healthz HTTP/1.1" 200 OK api-1 | INFO: 172.23.0.1:42248 - "POST /products HTTP/1.1" 201 Created api-1 | INFO: 172.23.0.1:42260 - "GET /products HTTP/1.1" 200 OK
Check:The
127.0.0.1lines are the container's own health checks; the others are your curl calls. -
10Confirm it doesn't run as root
Run docker compose exec api idExpected output
uid=10001(app) gid=10001(app) groups=10001(app)
-
11Restart everything and keep the data
downremoves the containers and network but keeps named volumes, so the database survives.Run docker compose down docker compose up -d --wait curl -s localhost:8000/productsExpected output
[{"name":"Coffee mug","price_cents":1299,"id":1}] -
12Remove everything, including the data
Run docker compose down -vCheck:docker volume lsno longer listscatalog_pgdata.
In production
Compose is an excellent way to run the whole stack on one machine. In production the same image runs on an orchestrator or a managed container service, and the database is usually managed too.
What changes
| In this lab | In production |
|---|---|
docker compose up on your laptop |
The image is built once in CI, pushed to a registry and deployed by tag or digest to Kubernetes, ECS, Cloud Run or similar |
| Postgres in a container with a volume | A managed database (Cloud SQL, RDS, Azure Database) with automated backups, point-in-time recovery and high availability |
Password in compose.yaml |
Secrets from a secret manager, injected at run time, never baked into the image or committed |
python:3.12-slim tag |
Base image pinned by digest and rebuilt regularly for security patches; images scanned in CI |
create_all when the API starts |
Migrations run once per release, before the new version takes traffic |
| Container logs in your terminal | Logs shipped to a central log platform, plus metrics and alerts |
Why the image is built this way
Multi-stage builds keep the runtime image free of build tools, which means fewer vulnerabilities to patch. Running as a non-root user limits what an attacker can do if the app is compromised. Copying dependency files before source code keeps rebuilds fast because the dependency layer is cached.
Production checklist
- Multi-stage build; runtime image has no compilers or package managers it doesn't need
- Runs as a non-root user; no secrets in the image or in Git
- Health checks on every service; start-up waits for dependencies to be healthy
- Base images pinned and scanned; rebuilt on a schedule
- Database data on managed storage with tested backups
.dockerignorekeeps local files and secrets out of the build context
Learn the concepts
- Python pip and Virtual Environments · Python Tutorial
- Docker from Basics to Production · Course