5. Testing, Background Jobs & Deployment
Database Migrations (Alembic), Dockerfiles & Deploying Python APIs
Ship Python backends reliably: evolve database schemas safely with Alembic migrations, containerize with a lean Dockerfile, add /health checks, and run multiple Uvicorn workers.
- Explain why versioned schema migrations (Alembic) replace CREATE TABLE IF NOT EXISTS
- Write a lean multi-line Dockerfile for a FastAPI Python backend
- Configure /health endpoints and production ASGI worker settings
Your API works locally and passes pytest. Now how do you ship it to a cloud server—and update your database schema next month without wiping real user data?
1. Architecture: From Git Push to Production Traffic
A reliable deployment pipeline runs schema updates and health checks before routing live user requests to new containers:
pip layer cached
ALTER TABLE safely
Serve 0.0.0.0:8000
Copy requirements.txt before source files so Docker caches pip installs, then run `alembic upgrade head` before routing traffic to /ready.
2. Schema Evolution & Alembic upgrade / downgrade Lifecycle
CREATE TABLE IF NOT EXISTS users (...) only works on day one. Once users already exists with 10,000 real accounts, adding a role column requires an explicit ALTER TABLE users ADD COLUMN role ... migration tracked in Git!
Alembic is Python's standard migration tool (paired with SQLAlchemy):
- Initialize once:
alembic init alembic - Update your SQLAlchemy model (e.g., add
role: Mapped[str]). - Generate a versioned migration script:
alembic revision --autogenerate -m "add user role" - Always inspect the generated
upgrade()anddowngrade()functions, commit to Git, and apply on deploy:
# alembic/versions/0002_add_user_role.py
from alembic import op
import sqlalchemy as sa
def upgrade() -> None:
op.add_column("users", sa.Column("role", sa.String(32), nullable=False, server_default="student"))
def downgrade() -> None:
op.drop_column("users", "role")alembic upgrade head # Applies every pending migration up to latest
alembic downgrade -1 # Reverts the most recent migration if a deploy breaksAlembic tracks the active revision ID in an alembic_version database table so every environment (local, staging, production) applies each migration exactly once.
alembic revision --autogenerate cannot always tell a column rename (name → full_name) apart from dropping name and creating full_name—which would wipe data! Review every migration file, back up production before migrating, and use additive changes first (ADD COLUMN nullable or with a default) for zero-downtime deploys.
3. Layer-Cached & Multi-Stage Dockerfile + .dockerignore
Containers guarantee your API runs with the exact same Python version and wheels everywhere. Start with a .dockerignore file so secrets and local caches never enter your Docker image:
.git
.venv
.env
__pycache__
*.dbNow combine layer caching (COPY requirements.txt before COPY . .), a multi-stage build (builder compiles wheels → lean runtime stays small), and a non-root user:
# --- Stage 1: Builder ---
FROM python:3.12-slim AS builder
WORKDIR /wheels
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels/pkgs -r requirements.txt
# --- Stage 2: Lean Runtime ---
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /wheels/pkgs /pkgs
COPY requirements.txt .
RUN pip install --no-cache-dir --no-index --find-links=/pkgs -r requirements.txt && rm -rf /pkgs
COPY . .
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]- Locally you bind
127.0.0.1. Inside a container, binding127.0.0.1rejects connections from Docker's network bridge and cloud load balancers—always pass--host 0.0.0.0. - Running multiple
--workerswith file-based SQLite can cause write lock contention (database is locked). Use--workers 1for tiny SQLite apps or switchDATABASE_URLto PostgreSQL when scaling to multiple workers/replicas.
4. Production Health Checks (/health vs /ready)
Cloud hosts (Cloud Run, Fly.io, Render, AWS ECS, Kubernetes) probe two endpoints before sending traffic:
GET /health(liveness): returns200 {"status": "ok"}immediately to prove the Python process hasn't deadlocked.GET /ready(readiness): executes a fastSELECT 1database check so load balancers withhold traffic until the database is reachable.
Try It Yourself in the Playground
Simulate a numbered SQLite schema migration runner (schema_migrations table applying v1, v2 idempotently—the exact concept behind Alembic!):
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: In a Dockerfile, why do we COPY requirements.txt . and run pip install before COPY . .?
Quick Checkpoints
Why isn't CREATE TABLE IF NOT EXISTS enough for evolving a production database?
Why must a containerized FastAPI server bind --host 0.0.0.0 instead of 127.0.0.1?