Python Labs · Lab 6 of 6
A Production-Grade Python Service
Turn the catalog API into a service you could run in production: settings from the environment, structured JSON logs with request IDs, liveness and readiness checks, Alembic migrations, a hardened container, graceful shutdown and a CI pipeline.
- Environment
- Production
- Level
- Advanced
- Time
- About 90 min
- Cost
- Free (runs on your computer)
You will build
A production-ready service and the habits behind it: configuration that fails fast, logs you can search, health checks an orchestrator can trust, migrations as a release step, and a pipeline that checks all of it.
Before you start
- Lab: Containerise the API: Dockerfile, Compose and Postgres
Docker with Compose v2
You continue in the `catalog` project. Every behaviour in this lab was tested for real while recording it,
including the database going down and the container being stopped mid-run. Timestamps, process IDs, request
IDs and the migration's revision ID will differ for you.
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
├── .env.example # documents required settings (commit); .env holds real values (don't)
├── .github/workflows/
│ └── ci.yml # lint, migrations, tests, image build and smoke test
├── .gitignore
├── Dockerfile # non-root, health check, migrations included
├── alembic.ini
├── compose.yaml # db, one-off migrate job, hardened api
├── migrations/
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│ └── 20261126_3a9c14a040bc_create_products.py
├── pyproject.toml
├── uv.lock
├── src/catalog/
│ ├── db.py
│ ├── logging_config.py
│ ├── main.py # app, request logging, /healthz, /readyz
│ ├── models.py
│ ├── products.py # product routes
│ ├── schemas.py
│ └── settings.py
└── tests/
├── conftest.py
├── test_health.py
├── test_products.py
└── test_settings_and_logging.py
Steps
-
1Add settings and migration tools
Run uv add pydantic-settings alembicExpected output
Resolved 35 packages in 15ms ... Installed 6 packages in 2ms + alembic==1.20.1 ~ catalog==0.1.0 (from file://.../catalog) + mako==1.4.3 + markupsafe==3.0.4 + pydantic-settings==2.16.3 + python-dotenv==1.2.4
-
2Read all configuration from the environment
One typed settings object, read once. A bad value stops the app at start-up instead of failing on the first request, and production refuses to run on SQLite.
src/catalog/settings.py from functools import lru_cache from typing import Literal from pydantic import model_validator from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): """All configuration comes from environment variables (or a local .env file).""" model_config = SettingsConfigDict(env_file=".env", extra="ignore") environment: Literal["dev", "test", "prod"] = "dev" database_url: str = "sqlite:///./catalog.db" db_pool_size: int = 5 log_level: str = "INFO" @model_validator(mode="after") def prod_needs_a_real_database(self) -> "Settings": if self.environment == "prod" and self.database_url.startswith("sqlite"): raise ValueError("DATABASE_URL must point at a server database in prod") return self @lru_cache def get_settings() -> Settings: return Settings() -
3Log JSON, one event per line
Log platforms (Cloud Logging, CloudWatch, Datadog, Loki) can search and graph JSON fields. uvicorn's own messages go through the same formatter; requests are logged by the app with more detail.
src/catalog/logging_config.py import json import logging import sys from datetime import UTC, datetime EXTRA_FIELDS = ("request_id", "method", "path", "status", "duration_ms") class JsonFormatter(logging.Formatter): """One JSON object per line: easy to search in any log platform.""" def format(self, record: logging.LogRecord) -> str: entry = { "time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"), "level": record.levelname, "logger": record.name, "message": record.getMessage(), } for key in EXTRA_FIELDS: if hasattr(record, key): entry[key] = getattr(record, key) if record.exc_info: entry["exception"] = self.formatException(record.exc_info) return json.dumps(entry) def configure_logging(level: str) -> None: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(JsonFormatter()) root = logging.getLogger() root.handlers = [handler] root.setLevel(level) # Send uvicorn's own messages through the JSON handler; requests are logged by our middleware. for name in ("uvicorn", "uvicorn.error"): logging.getLogger(name).handlers = [] logging.getLogger(name).propagate = True logging.getLogger("uvicorn.access").disabled = True -
4Configure the database connection pool
pool_pre_pingquietly replaces connections the database closed, so a database restart doesn't cause errors.src/catalog/db.py from collections.abc import Iterator from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker from catalog.settings import get_settings settings = get_settings() if settings.database_url.startswith("sqlite"): engine = create_engine(settings.database_url, connect_args={"check_same_thread": False}) else: # pool_pre_ping replaces connections the database closed (restarts, idle timeouts) before use. engine = create_engine(settings.database_url, pool_size=settings.db_pool_size, pool_pre_ping=True) SessionLocal = sessionmaker(engine, expire_on_commit=False) class Base(DeclarativeBase): pass def get_session() -> Iterator[Session]: with SessionLocal() as session: yield session -
5Enforce rules in the database too
Validation in the API can be bypassed by scripts and other services; a check constraint can't.
src/catalog/models.py from sqlalchemy import CheckConstraint, String from sqlalchemy.orm import Mapped, mapped_column from catalog.db import Base class Product(Base): __tablename__ = "products" __table_args__ = (CheckConstraint("price_cents >= 0", name="ck_products_price_nonnegative"),) id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(200)) price_cents: Mapped[int] -
6Move the product routes into a router
src/catalog/products.py from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Response, status from sqlalchemy import select from sqlalchemy.orm import Session from catalog.db import get_session from catalog.models import Product from catalog.schemas import ProductIn, ProductOut router = APIRouter(prefix="/products", tags=["products"]) SessionDep = Annotated[Session, Depends(get_session)] @router.post("", status_code=status.HTTP_201_CREATED, response_model=ProductOut) def create_product(body: ProductIn, session: SessionDep) -> Product: product = Product(**body.model_dump()) session.add(product) session.commit() return product @router.get("", response_model=list[ProductOut]) def list_products(session: SessionDep) -> list[Product]: return list(session.scalars(select(Product).order_by(Product.id))) @router.get("/{product_id}", response_model=ProductOut) def get_product(product_id: int, session: SessionDep) -> Product: product = session.get(Product, product_id) if product is None: raise HTTPException(status_code=404, detail="Product not found") return product @router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_product(product_id: int, session: SessionDep) -> Response: product = session.get(Product, product_id) if product is None: raise HTTPException(status_code=404, detail="Product not found") session.delete(product) session.commit() return Response(status_code=status.HTTP_204_NO_CONTENT) -
7Add request logging and health checks
- Liveness (
/healthz): is the process alive? It never checks dependencies; if it did, a database outage would make the orchestrator restart every healthy container. - Readiness (
/readyz): can this instance serve traffic right now? It checks the database, so a load balancer stops sending requests while the database is unreachable.
Every response carries an
x-request-id(the caller's, or a new one) that also appears in the log line, so one request can be followed across services.create_allis gone: migrations own the schema now. The interactive docs are switched off in production.src/catalog/main.py import logging import time import uuid from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Request from sqlalchemy import text from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session from catalog import products from catalog.db import get_session from catalog.logging_config import configure_logging from catalog.settings import get_settings settings = get_settings() configure_logging(settings.log_level) logger = logging.getLogger("catalog") app = FastAPI(title="Catalog", docs_url=None if settings.environment == "prod" else "/docs") app.include_router(products.router) QUIET_PATHS = {"/healthz", "/readyz"} @app.middleware("http") async def request_log(request: Request, call_next): request_id = request.headers.get("x-request-id") or uuid.uuid4().hex start = time.perf_counter() response = await call_next(request) response.headers["x-request-id"] = request_id logger.log( logging.DEBUG if request.url.path in QUIET_PATHS else logging.INFO, "request", extra={ "request_id": request_id, "method": request.method, "path": request.url.path, "status": response.status_code, "duration_ms": round((time.perf_counter() - start) * 1000, 1), }, ) return response @app.get("/healthz") def healthz() -> dict: """Liveness: the process is up. Never checks dependencies.""" return {"status": "ok"} @app.get("/readyz") def readyz(session: Annotated[Session, Depends(get_session)]) -> dict: """Readiness: we can serve traffic, which needs the database.""" try: session.execute(text("SELECT 1")) except SQLAlchemyError: logger.warning("readiness check failed: database unavailable") raise HTTPException(status_code=503, detail="database unavailable") from None return {"status": "ready"} - Liveness (
-
8Test health, failure and configuration
broken_db_clientpoints the app at a database that can't be opened, to prove readiness fails and liveness doesn't. The other new tests cover settings and the log format (included in the download).tests/conftest.py and tests/test_health.py import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import StaticPool from catalog.db import Base, get_session from catalog.main import app def _client_for(engine) -> TestClient: TestSession = sessionmaker(engine, expire_on_commit=False) def override(): with TestSession() as session: yield session app.dependency_overrides[get_session] = override return TestClient(app) @pytest.fixture def client(): # Unit tests use an in-memory SQLite database; CI also runs the migrations against Postgres. engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) Base.metadata.create_all(engine) yield _client_for(engine) app.dependency_overrides.clear() @pytest.fixture def broken_db_client(tmp_path): engine = create_engine(f"sqlite:///{tmp_path}/missing-dir/db.sqlite") yield _client_for(engine) app.dependency_overrides.clear() # tests/test_health.py def test_liveness(client): assert client.get("/healthz").json() == {"status": "ok"} def test_readiness_with_database(client): assert client.get("/readyz").json() == {"status": "ready"} def test_readiness_fails_without_database(broken_db_client): r = broken_db_client.get("/readyz") assert r.status_code == 503 assert r.json() == {"detail": "database unavailable"} def test_liveness_does_not_need_the_database(broken_db_client): assert broken_db_client.get("/healthz").status_code == 200 def test_request_id_is_returned(client): assert client.get("/healthz", headers={"x-request-id": "abc123"}).headers["x-request-id"] == "abc123" assert len(client.get("/healthz").headers["x-request-id"]) == 32 -
9Run the test suite
Run uv run ruff check && uv run ruff format --check uv run pytest -vExpected output
All checks passed! 15 files already formatted collecting ... collected 13 items tests/test_health.py::test_liveness PASSED [ 7%] tests/test_health.py::test_readiness_with_database PASSED [ 15%] tests/test_health.py::test_readiness_fails_without_database PASSED [ 23%] tests/test_health.py::test_liveness_does_not_need_the_database PASSED [ 30%] tests/test_health.py::test_request_id_is_returned PASSED [ 38%] tests/test_products.py::test_create_and_get PASSED [ 46%] tests/test_products.py::test_list_is_ordered PASSED [ 53%] tests/test_products.py::test_validation_rejects_negative_price PASSED [ 61%] tests/test_products.py::test_missing_product_is_404 PASSED [ 69%] tests/test_products.py::test_delete PASSED [ 76%] tests/test_settings_and_logging.py::test_prod_rejects_sqlite PASSED [ 84%] tests/test_settings_and_logging.py::test_settings_read_environment PASSED [ 92%] tests/test_settings_and_logging.py::test_json_log_line PASSED [100%] ============================== 13 passed in 0.21s ==============================
-
10Start a Postgres to develop migrations against
Run docker run -d --name catalog-pg -p 5432:5432 -e POSTGRES_DB=catalog \ -e POSTGRES_USER=catalog -e POSTGRES_PASSWORD=local-only postgres:18-alpine > /dev/null sleep 5 docker exec catalog-pg pg_isready -U catalog -d catalog export DATABASE_URL=postgresql+psycopg://catalog:local-only@localhost:5432/catalogExpected output
/var/run/postgresql:5432 - accepting connections
Hint
If port 5432 is taken, map another (
-p 5433:5432) and change the URL to match. -
11Create the migrations folder
Run uv run alembic init migrationsExpected output
Creating directory .../catalog/migrations ... done Creating directory .../catalog/migrations/versions ... done Generating .../catalog/migrations/README ... done Generating .../catalog/migrations/env.py ... done Generating .../catalog/alembic.ini ... done Generating .../catalog/migrations/script.py.mako ... done Please edit configuration/connection/logging settings in .../catalog/alembic.ini before proceeding.
-
12Point Alembic at the app's settings and models
The database URL comes from the same settings as the app, never from
alembic.ini, so there is one source of truth and no password in the file. New migration files are named by date and linted and formatted by ruff automatically.alembic.ini # Alembic reads the database URL from the app's settings (migrations/env.py), never from this file. [alembic] script_location = %(here)s/migrations prepend_sys_path = . path_separator = os file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s [post_write_hooks] # Lint and format every new migration file. hooks = ruff_fix, ruff_format ruff_fix.type = module ruff_fix.module = ruff ruff_fix.options = check --fix REVISION_SCRIPT_FILENAME ruff_format.type = module ruff_format.module = ruff ruff_format.options = format REVISION_SCRIPT_FILENAME # [loggers] ... (unchanged from alembic init) -
13Use the app's engine in migrations/env.py
migrations/env.py from logging.config import fileConfig from alembic import context from catalog import models # noqa: F401 (registers the tables on Base.metadata) from catalog.db import Base, engine config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) target_metadata = Base.metadata def run_migrations_offline() -> None: """`alembic upgrade head --sql`: print the SQL instead of running it (for DBA review).""" context.configure(url=engine.url, target_metadata=target_metadata, literal_binds=True) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: with engine.connect() as connection: context.configure(connection=connection, target_metadata=target_metadata, compare_type=True) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() -
14Generate the first migration from the models
Autogenerate compares the models with the empty database. Always read the generated file before committing it.
Run uv run alembic revision --autogenerate -m "create products"Expected output
INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. ... INFO [alembic.autogenerate.compare.tables] Detected added table 'products' Generating ./migrations/versions/20261126_3a9c14a040bc_create_products.py ... done Running post write hook 'ruff_fix' ... Found 6 errors (6 fixed, 0 remaining). done Running post write hook 'ruff_format' ... 1 file reformatted done
-
15Review the migration
migrations/versions/20261126_3a9c14a040bc_create_products.py """create products Revision ID: 3a9c14a040bc Revises: Create Date: 2026-11-26 01:49:47.710020 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "3a9c14a040bc" down_revision: str | Sequence[str] | None = None branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: """Upgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### op.create_table( "products", sa.Column("id", sa.Integer(), nullable=False), sa.Column("name", sa.String(length=200), nullable=False), sa.Column("price_cents", sa.Integer(), nullable=False), sa.CheckConstraint("price_cents >= 0", name="ck_products_price_nonnegative"), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade() -> None: """Downgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### op.drop_table("products") # ### end Alembic commands ###Check:It creates the table with the check constraint and has a
downgrade()that undoes it. -
16Apply it and confirm models and database agree
Run uv run alembic upgrade head uv run alembic checkExpected output
INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.runtime.migration] Running upgrade -> 3a9c14a040bc, create products ... No new upgrade operations detected.
-
17See CI catch a forgotten migration
Add
sku: Mapped[str] = mapped_column(String(40))toProductwithout writing a migration, run the check, then remove the line again. This is the exact check the CI pipeline runs.Run uv run alembic checkExpected output
INFO [alembic.autogenerate.compare.tables] Detected added column 'products.sku' ERROR [alembic.util.messaging] New upgrade operations detected: [('add_column', None, 'products', Column('sku', String(length=40), table=<products>, nullable=False))] FAILED: New upgrade operations detected: [('add_column', None, 'products', Column('sku', String(length=40), table=<products>, nullable=False))]Check:The command exits non-zero, so a pull request with a model change but no migration can't merge.
-
18Harden the image
Migrations ship inside the image, so the exact artifact you deploy also runs
alembic upgrade head.WEB_CONCURRENCYsets the number of uvicorn workers. The exec-formCMDmakes uvicorn PID 1, so it receivesSIGTERM, finishes in-flight requests (up to 20 s) and exits cleanly. Update.dockerignoreto also exclude.envand.github.Dockerfile # syntax=docker/dockerfile:1 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 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 FROM python:3.12-slim RUN useradd --create-home --uid 10001 app WORKDIR /app COPY --from=build --chown=app:app /app/.venv /app/.venv # Migrations ship in the image so the same artifact can run `alembic upgrade head` before a release. COPY --chown=app:app alembic.ini ./ COPY --chown=app:app migrations ./migrations ENV PATH="/app/.venv/bin:$PATH" \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ WEB_CONCURRENCY=2 USER app EXPOSE 8000 HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \ CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz', timeout=2)"] # Exec form: uvicorn is PID 1 and receives SIGTERM, finishes in-flight requests, then exits. CMD ["uvicorn", "catalog.main:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log", "--timeout-graceful-shutdown", "20"] -
19Run migrations as a release step, then the API
migrateruns once and exits; the API starts only if it completed successfully. The API container has a read-only filesystem (only/tmpis writable), no Linux capabilities, no privilege escalation and resource limits. The password must come from.env: Compose refuses to start without it.compose.yaml and .env.example # A production-like stack on one machine: migrations run once, then the API starts. x-app-env: &app-env ENVIRONMENT: prod DATABASE_URL: postgresql+psycopg://catalog:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db:5432/catalog LOG_LEVEL: INFO services: db: image: postgres:18-alpine environment: POSTGRES_DB: catalog POSTGRES_USER: catalog POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} volumes: - pgdata:/var/lib/postgresql healthcheck: test: ["CMD-SHELL", "pg_isready -U catalog -d catalog"] interval: 2s timeout: 3s retries: 15 migrate: image: ${IMAGE:-catalog-api}:${TAG:-local} build: . command: ["alembic", "upgrade", "head"] environment: *app-env depends_on: db: condition: service_healthy api: image: ${IMAGE:-catalog-api}:${TAG:-local} build: . environment: *app-env ports: - "${API_PORT:-8000}:8000" depends_on: migrate: condition: service_completed_successfully read_only: true tmpfs: - /tmp security_opt: - no-new-privileges:true cap_drop: - ALL stop_grace_period: 30s restart: unless-stopped deploy: resources: limits: cpus: "1" memory: 512M volumes: pgdata: # .env.example # Copy to .env and change the values. Never commit .env. POSTGRES_PASSWORD=change-me API_PORT=8000 -
20See it refuse to start without a secret
Run docker compose up -dExpected output
error while interpolating services.api.environment.DATABASE_URL: required variable POSTGRES_PASSWORD is missing a value: Set POSTGRES_PASSWORD in .env error while interpolating services.db.environment.POSTGRES_PASSWORD: required variable POSTGRES_PASSWORD is missing a value: Set POSTGRES_PASSWORD in .env error while interpolating services.migrate.environment.DATABASE_URL: required variable POSTGRES_PASSWORD is missing a value: Set POSTGRES_PASSWORD in .env error while interpolating x-app-env.DATABASE_URL: required variable POSTGRES_PASSWORD is missing a value: Set POSTGRES_PASSWORD in .env
-
21Start the stack
Stop
catalog-pgfirst (docker rm -f catalog-pg) if it still uses port 5432 for something else you need.Run cp .env.example .env # then set a strong POSTGRES_PASSWORD docker compose up -d --build --wait docker compose ps -a --format "table {{.Service}}\t{{.State}}\t{{.Status}}" docker compose logs migrate --no-log-prefixExpected output
... SERVICE STATE STATUS api running Up 12 seconds (healthy) db running Up 16 seconds (healthy) migrate exited Exited (0) 12 seconds ago INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.runtime.migration] Running upgrade -> 3a9c14a040bc, create products
Check:migrateexited with status 0 and the API is healthy. -
22Follow a request through the logs
Run curl -s localhost:8000/readyz curl -s -D - -X POST localhost:8000/products -H 'Content-Type: application/json' \ -H 'X-Request-ID: order-flow-42' -d '{"name": "Coffee mug", "price_cents": 1299}' | grep -i 'x-request-id\|^{' curl -s localhost:8000/products/7 curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/docs docker compose logs api --no-log-prefix | tail -3Expected output
{"status":"ready"} x-request-id: order-flow-42 {"name":"Coffee mug","price_cents":1299,"id":1} {"detail":"Product not found"} 404 {"time": "2026-11-26T01:51:30.586+00:00", "level": "INFO", "logger": "catalog", "message": "request", "request_id": "order-flow-42", "method": "POST", "path": "/products", "status": 201, "duration_ms": 31.2} {"time": "2026-11-26T01:51:30.594+00:00", "level": "INFO", "logger": "catalog", "message": "request", "request_id": "d8ef2c34e7954bd0b27c9bbd22d925d4", "method": "GET", "path": "/products/7", "status": 404, "duration_ms": 2.8} {"time": "2026-11-26T01:51:30.599+00:00", "level": "INFO", "logger": "catalog", "message": "request", "request_id": "2d07d1e89cfb491a960e8cb35f751c93", "method": "GET", "path": "/docs", "status": 404, "duration_ms": 0.3}Check:The request ID you sent is in the response header and in the log line.
/docsis off in prod. -
23Take the database away
Run docker compose stop db curl -s -w ' %{http_code}\n' localhost:8000/healthz curl -s -w ' %{http_code}\n' localhost:8000/readyz docker compose start db sleep 4 curl -s -w ' %{http_code}\n' localhost:8000/readyz curl -s localhost:8000/productsExpected output
{"status":"ok"} 200 {"detail":"database unavailable"} 503 {"status":"ready"} 200 [{"name":"Coffee mug","price_cents":1299,"id":1}]Check:The container stays alive (liveness 200) while it reports not ready (503), and recovers on its own when the database is back. The log shows one
WARNINGline:readiness check failed. -
24Check the container's restrictions
Run docker compose exec api sh -c 'touch /app/x; touch /tmp/ok && echo tmp-writable; id'Expected output
touch: cannot touch '/app/x': Read-only file system tmp-writable uid=10001(app) gid=10001(app) groups=10001(app)
-
25Stop it gracefully
Docker sends
SIGTERM. Each worker finishes its requests and runs the app's shutdown, then the parent exits.Run docker compose stop api docker compose logs api --no-log-prefix | tail -6Expected output
{"time": "2026-11-26T01:51:42.118+00:00", "level": "INFO", "logger": "uvicorn.error", "message": "Finished server process [8]"} INFO: Waiting for child process [9] {"time": "2026-11-26T01:51:42.130+00:00", "level": "INFO", "logger": "uvicorn.error", "message": "Waiting for application shutdown."} {"time": "2026-11-26T01:51:42.130+00:00", "level": "INFO", "logger": "uvicorn.error", "message": "Application shutdown complete."} {"time": "2026-11-26T01:51:42.130+00:00", "level": "INFO", "logger": "uvicorn.error", "message": "Finished server process [9]"} INFO: Stopping parent process [1]Check:Two worker processes shut down cleanly. The plain
INFO:lines come from uvicorn's supervisor process, which never imports the app and so keeps uvicorn's default format. -
26Add the CI pipeline
On every pull request: lint, format check, migrations applied to a real Postgres,
alembic checkfor drift, and the tests. After that, the image is built and smoke-tested. Push to GitHub to run it; the pull request shows both jobs..github/workflows/ci.yml name: ci on: pull_request: push: branches: [main] permissions: contents: read jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:18-alpine env: POSTGRES_DB: catalog POSTGRES_USER: catalog POSTGRES_PASSWORD: ci-only ports: - 5432:5432 options: >- --health-cmd "pg_isready -U catalog -d catalog" --health-interval 2s --health-timeout 3s --health-retries 15 env: DATABASE_URL: postgresql+psycopg://catalog:ci-only@localhost:5432/catalog steps: - uses: actions/checkout@v5 - uses: astral-sh/setup-uv@v6 with: version: "0.13.10" - run: uv sync --locked - run: uv run ruff check - run: uv run ruff format --check - name: Migrations apply cleanly and match the models run: | uv run alembic upgrade head uv run alembic check - run: uv run pytest image: needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - run: docker build -t catalog-api:${{ github.sha }} . - name: Smoke test the image run: | docker run -d --name smoke -p 8000:8000 -e DATABASE_URL=sqlite:////tmp/smoke.db catalog-api:${{ github.sha }} for i in $(seq 1 20); do curl -fsS localhost:8000/healthz && exit 0 sleep 1 done docker logs smoke exit 1Check:Both jobs pass on GitHub. Every command in the
testjob was run locally against Postgres while recording this lab; the workflow itself wasn't run on GitHub.
Clean up
Remove the stack, its data volume, the image and the development database:
docker compose down -v
docker image rm catalog-api:local
docker rm -f catalog-pg
docker compose ps -a should list nothing for this project.
In production
This lab is the production checklist made concrete. The remaining work is mostly about releasing safely and seeing what's happening once it runs.
What changes
| In this lab | In production |
|---|---|
migrate service in Compose |
A migration job in the deploy pipeline (Kubernetes Job, Cloud Run job, ECS task) that must succeed before traffic moves |
| Migrations can add and drop anything | Expand and contract: add columns first, deploy code that uses them, remove old ones in a later release, so old and new versions run side by side |
.env file |
A secret manager, rotated credentials and separate database users for migrations and for the app |
JSON logs in docker compose logs |
Central logging with retention, dashboards on status codes and latency, and alerts on error rate |
| Request IDs | Full distributed tracing (OpenTelemetry) across services and the database |
docker compose stop |
Orchestrator rolling updates using /readyz, with terminationGracePeriodSeconds longer than the app's shutdown timeout |
| You read the checks pass | Required status checks, image scanning, signed images and deploys that roll back automatically |
Liveness and readiness, used correctly
Kubernetes livenessProbe → /healthz, readinessProbe → /readyz. Cloud Run and load balancers use the
readiness signal to route traffic. Never point a liveness probe at a dependency check: a database blip would
restart every instance at once.
Production checklist
- Configuration from the environment, validated at start-up; prod refuses unsafe settings
- Secrets only from a secret manager or
.envoutside Git;.env.exampledocuments them - Structured JSON logs with request IDs; no secrets or personal data in logs
- Separate liveness and readiness endpoints with the right meaning
- Schema changes only through reviewed migrations;
alembic checkin CI; expand-and-contract for live changes - Migrations run once per release, before new code takes traffic
- Container: non-root, read-only filesystem, no capabilities, resource limits, health check
- Graceful shutdown within the platform's grace period
- CI on every pull request; images built once and promoted through environments
- Backups tested by restoring them; alerts on errors, latency and saturation
Learn the concepts
- Python Try...Except · Python Tutorial
- Python Testing with pytest · Python Tutorial
- Observability and Operations · Course
- Docker from Basics to Production · Course