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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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:

Zero-Downtime Deploy: Migrations + Cached Docker Layers
1. Docker Build

pip layer cached

2. alembic upgrade

ALTER TABLE safely

3. GET /ready → 200

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):

  1. Initialize once: alembic init alembic
  2. Update your SQLAlchemy model (e.g., add role: Mapped[str]).
  3. Generate a versioned migration script: alembic revision --autogenerate -m "add user role"
  4. Always inspect the generated upgrade() and downgrade() functions, commit to Git, and apply on deploy:
python
# 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")
bash
alembic upgrade head      # Applies every pending migration up to latest
alembic downgrade -1      # Reverts the most recent migration if a deploy breaks

Alembic tracks the active revision ID in an alembic_version database table so every environment (local, staging, production) applies each migration exactly once.

Never Blindly Trust --autogenerate or Drop Columns Mid-Deploy

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:

text
.git
.venv
.env
__pycache__
*.db

Now combine layer caching (COPY requirements.txt before COPY . .), a multi-stage build (builder compiles wheels → lean runtime stays small), and a non-root user:

dockerfile
# --- 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"]
Always Bind 0.0.0.0 Inside Docker (and Watch SQLite with --workers)
  1. Locally you bind 127.0.0.1. Inside a container, binding 127.0.0.1 rejects connections from Docker's network bridge and cloud load balancers—always pass --host 0.0.0.0.
  2. Running multiple --workers with file-based SQLite can cause write lock contention (database is locked). Use --workers 1 for tiny SQLite apps or switch DATABASE_URL to 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): returns 200 {"status": "ok"} immediately to prove the Python process hasn't deadlocked.
  • GET /ready (readiness): executes a fast SELECT 1 database 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!):

Python 3Try It Live: Versioned Database Migration Runner
Output

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

Check Your Understanding

Why isn't CREATE TABLE IF NOT EXISTS enough for evolving a production database?

Check Your Understanding

Why must a containerized FastAPI server bind --host 0.0.0.0 instead of 127.0.0.1?