Part 5 Β· Chapter 16

Python & FastAPI Deployment

From local uvicorn to production ASGI with Gunicorn, Supervisor, and Docker.

What you'll learn in this chapter

  • Why you should never run python app.py directly in production
  • The difference between WSGI and ASGI β€” and why it matters for FastAPI
  • Virtual environments and reproducible dependency management
  • Gunicorn with Uvicorn workers β€” the production-standard Python server setup
  • The Gunicorn config file for clean, version-controlled configuration
  • Supervisor β€” keeping your Python process alive across restarts
  • Dockerising a FastAPI application with best-practice layer caching
  • Database migrations with Alembic β€” never touch production data by hand
  • Flask deployment differences and when to use each framework

The Restaurant Kitchen Analogy

Imagine a busy restaurant. You have a brilliant head chef β€” that is your Python application, the code that does the actual work. Now imagine the front-of-house: customers walk in, place orders, and wait for food. The people who take those orders and deliver food back to the tables are the waiters β€” that is your ASGI/WSGI server.

If you only have one waiter, customers wait in a single queue. That waiter can only handle one table at a time. If a table's order is complex and takes ten minutes, everyone else is blocked. This is what happens when you run python app.py or uvicorn main:app without multiple workers β€” it is a restaurant with a brilliant chef but only one waiter.

Gunicorn is the restaurant manager who hires multiple waiters (worker processes). Each worker is a complete, independent Python process that can handle requests in parallel. Five workers means five requests can be handled simultaneously. If one worker crashes (the waiter spills something), Gunicorn replaces them immediately. The restaurant keeps running.

🍽️ The Restaurant Kitchen

Python app = the chef (the talent, the business logic)
Uvicorn = one waiter (fast, async, handles one request path at a time)
Gunicorn = the restaurant manager (runs many waiters in parallel, restarts fallen ones, manages the floor)
Nginx = the front door host (greets everyone, handles SSL, directs traffic to the right section)

WSGI vs ASGI β€” The Two Worlds of Python Web

Python's web ecosystem has two competing standards for how web servers talk to Python applications. Understanding which one your framework uses determines how you deploy it.

WSGI vs ASGI Comparison
────────────────────────────────────────────────────────────────────
                    WSGI                        ASGI
────────────────────────────────────────────────────────────────────
Full name    Web Server Gateway Interface   Async Server Gateway
             (PEP 3333, 2003)               Interface (2019)

Model        Synchronous                    Asynchronous

Concurrency  Multiple processes             Multiple coroutines
             (Gunicorn workers)             per worker + multiple workers

Frameworks   Flask, Django (sync)           FastAPI, Starlette,
                                            Django 4+ (async views)

Server       Gunicorn, uWSGI               Uvicorn (single),
                                            Gunicorn + UvicornWorker (multi)

Best for     Traditional CRUD APIs,         High-concurrency APIs,
             Django monoliths               WebSockets, streaming,
                                            async database calls
────────────────────────────────────────────────────────────────────

FastAPI is built entirely on ASGI. It is fast, modern, and supports Python's async/await syntax natively. For production deployment, you run it with Gunicorn acting as the process manager, but you swap out Gunicorn's default synchronous workers for Uvicorn workers β€” which are asynchronous. This gives you the best of both worlds: Gunicorn's process management stability with Uvicorn's async performance.

πŸ“– FastAPI's Performance Advantage

FastAPI is one of the fastest Python web frameworks ever benchmarked, on par with Node.js and Go for many workloads. This is because it is built on Starlette (an ASGI framework) and Pydantic (fast data validation). When a request comes in and waits for a database query, an async worker can switch to handling another request in the meantime β€” no thread is sitting idle. Traditional WSGI workers block during I/O.

A Production-Ready FastAPI Application

Before we talk about deployment, let's establish a clean application structure. Every production FastAPI app should use the lifespan context manager for startup and shutdown logic, expose a /health endpoint, and read configuration from environment variables:

# main.py β€” production-ready FastAPI application
from fastapi import FastAPI, HTTPException
from contextlib import asynccontextmanager
from pydantic_settings import BaseSettings
import os

# Settings β€” read from environment variables automatically
class Settings(BaseSettings):
    database_url: str
    secret_key: str
    app_version: str = "1.0.0"
    debug: bool = False

    class Config:
        env_file = ".env"

settings = Settings()

# Lifespan: startup and shutdown logic
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: connect to DB, warm caches, load models
    print("Starting up...")
    yield
    # Shutdown: close connections, flush buffers
    print("Shutting down...")

app = FastAPI(
    title="My API",
    version=settings.app_version,
    lifespan=lifespan,
    docs_url=None if not settings.debug else "/docs",  # hide docs in prod
)

@app.get("/health")
async def health():
    return {
        "status": "ok",
        "version": settings.app_version,
    }

@app.get("/")
async def root():
    return {"message": "Hello World"}

Virtual Environments and Dependency Management

Python's package system installs libraries globally by default. This is a disaster for servers β€” different applications may need different versions of the same library, and a global install means they fight. Virtual environments solve this: each project gets its own isolated Python environment with its own packages.

Think of virtual environments like separate toolboxes. One project needs hammer v1.0, another needs hammer v2.0. Without separate toolboxes, they'd clash. With virtual environments, each project has its own hammer.

# Create a virtual environment (do this once per project)
python3 -m venv venv

# Activate it (you must activate before installing or running)
source venv/bin/activate      # Linux / macOS
venv\Scripts\activate         # Windows PowerShell

# Your shell prompt now shows (venv) β€” you are inside the environment

# Install your dependencies
pip install fastapi uvicorn gunicorn pydantic-settings sqlalchemy alembic

# Pin exact versions for reproducibility
pip freeze > requirements.txt

# On deployment server, install from requirements.txt
pip install -r requirements.txt

# Deactivate when done
deactivate
πŸ’‘ Use pip freeze for production, not pip install

pip freeze captures the exact version of every installed package, including transitive dependencies. A requirements.txt generated by pip freeze will install exactly the same library versions on the deployment server as on the developer's machine. Never leave version ranges in production requirements files β€” a new minor version of a library can contain breaking changes.

Running with Gunicorn and Uvicorn Workers

Development uses a single Uvicorn process with hot-reload enabled. Production uses Gunicorn managing a pool of Uvicorn workers. The classic rule of thumb for worker count is (2 Γ— CPU cores) + 1. For a 2-core server, that is 5 workers. For a 4-core server, 9 workers.

# Development: single process, auto-reload on file changes
uvicorn main:app --reload --port 8000

# Production: Gunicorn managing 4 Uvicorn workers
gunicorn main:app \
  --worker-class uvicorn.workers.UvicornWorker \
  --workers 4 \
  --bind 0.0.0.0:8000 \
  --timeout 120 \
  --keepalive 5 \
  --access-logfile /var/log/myapp/access.log \
  --error-logfile /var/log/myapp/error.log \
  --log-level info

The --timeout 120 flag means Gunicorn will kill and restart a worker if it does not respond within 120 seconds. This protects against hung workers caused by slow database queries or infinite loops. The --keepalive 5 flag tells Gunicorn to hold open idle HTTP connections for 5 seconds, which reduces latency for clients making multiple requests.

The Gunicorn Configuration File

Just like PM2 has an ecosystem.config.js, Gunicorn has a Python configuration file. Store this in your repository alongside your code:

# gunicorn.conf.py
import multiprocessing

# Worker configuration
workers = multiprocessing.cpu_count() * 2 + 1  # auto-detect cores
worker_class = "uvicorn.workers.UvicornWorker"
worker_connections = 1000     # max simultaneous connections per worker

# Server socket
bind = "0.0.0.0:8000"
backlog = 2048                # pending connection queue size

# Process management
timeout = 120
keepalive = 5
max_requests = 1000           # restart worker after N requests (prevents memory leaks)
max_requests_jitter = 50      # randomise restart time to avoid thundering herd
preload_app = True           # load app before forking workers (faster startup)

# Logging
accesslog = "/var/log/myapp/access.log"
errorlog = "/var/log/myapp/error.log"
loglevel = "info"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'

Start Gunicorn pointing at this config file:

gunicorn main:app -c gunicorn.conf.py
πŸ”„ max_requests and Memory Leaks

Python applications can accumulate memory over time β€” a phenomenon called a slow memory leak. Even if the leak is tiny per request, after thousands of requests the worker bloats and the server slows. The max_requests setting is a pragmatic solution: restart each worker after it has handled a set number of requests, wiping its memory slate clean. The max_requests_jitter adds randomness so all workers do not restart simultaneously, which would cause a brief traffic spike on the remaining workers.

Supervisor β€” Keeping Gunicorn Running

Gunicorn manages Python workers, but who manages Gunicorn itself? On a bare Linux server, you need a process supervisor. Supervisor is to Python what PM2 is to Node.js β€” it monitors your Gunicorn process and restarts it if it dies. It also starts automatically on system boot.

# Install Supervisor
sudo apt install supervisor

# Create a configuration file for your app
sudo nano /etc/supervisor/conf.d/myapp.conf
; /etc/supervisor/conf.d/myapp.conf
[program:myapp]
command=/var/www/myapp/venv/bin/gunicorn main:app -c /var/www/myapp/gunicorn.conf.py
directory=/var/www/myapp
user=www-data
autostart=true
autorestart=true
stopasgroup=true          ; also stop worker processes when stopping gunicorn
killasgroup=true
stderr_logfile=/var/log/myapp/supervisor.err.log
stdout_logfile=/var/log/myapp/supervisor.out.log
stderr_logfile_maxbytes=50MB
stdout_logfile_maxbytes=50MB
stderr_logfile_backups=5
stdout_logfile_backups=5
environment=DATABASE_URL="postgresql://user:pass@localhost:5432/mydb",SECRET_KEY="..."
# Load the new configuration
sudo supervisorctl reread
sudo supervisorctl update

# Control your application
sudo supervisorctl status myapp
sudo supervisorctl restart myapp
sudo supervisorctl stop myapp
sudo supervisorctl start myapp

# View all supervised processes
sudo supervisorctl status

FastAPI in Docker

Containers are the cleanest way to deploy Python applications. You eliminate the "it works on my machine" problem completely β€” the container image contains your app, its Python version, and every dependency. The key to efficient Docker builds is ordering your COPY instructions so that the expensive pip install step is cached on subsequent builds:

# Dockerfile for FastAPI + Gunicorn + Uvicorn workers

FROM python:3.12-slim

# Create a non-root user for security
RUN groupadd -r appuser && useradd -r -g appuser appuser

WORKDIR /app

# Install dependencies FIRST (Docker will cache this layer)
# Only re-runs pip install when requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code (changes more often than dependencies)
COPY . .

# Switch to non-root user
USER appuser

EXPOSE 8000

CMD ["gunicorn", "main:app", \
     "--worker-class", "uvicorn.workers.UvicornWorker", \
     "--workers", "4", \
     "--bind", "0.0.0.0:8000", \
     "--timeout", "120"]

Build and run:

# Build the image
docker build -t my-fastapi-app .

# Run with environment variables
docker run -d \
  -p 8000:8000 \
  -e DATABASE_URL=postgresql://user:pass@db:5432/mydb \
  -e SECRET_KEY=my-secret \
  --name my-api \
  my-fastapi-app

# Check logs
docker logs -f my-api

# Test the health endpoint
curl http://localhost:8000/health

Database Migrations with Alembic

A common horror story: a developer SSHes into a production database and runs ALTER TABLE manually. The next week, a staging environment is out of sync. Six months later, no one remembers what was changed. The production schema and the application's assumptions diverge silently until something breaks.

Alembic is the migration tool for SQLAlchemy (Python's most popular ORM). Every change to the database schema becomes a versioned migration script, committed to Git, applied consistently across every environment.

# Initialize Alembic in your project
alembic init alembic

# Autogenerate a migration by comparing your SQLAlchemy models to the DB
alembic revision --autogenerate -m "add users table"

# Review the generated migration file in alembic/versions/
# Then apply all pending migrations
alembic upgrade head

# Roll back one migration step
alembic downgrade -1

# Check current migration version
alembic current

# Show migration history
alembic history

In a Docker Compose or Kubernetes deployment, run migrations as an init step before starting the application. In a Dockerfile, combine the steps using a shell command:

# In Dockerfile CMD β€” run migrations, then start the server
CMD ["sh", "-c", "alembic upgrade head && gunicorn main:app --worker-class uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8000"]
⚠️ Never run migrations from multiple instances simultaneously

If you are running 5 containers and all 5 run alembic upgrade head at startup, they will try to apply the same migration simultaneously and conflict with each other. The solution: run migrations as a dedicated Kubernetes Job or Compose service that must complete before the main application starts, or use a distributed lock. Many teams run migrations in their CI/CD pipeline before deploying new containers.

Flask Deployment

Flask uses WSGI instead of ASGI, but the deployment pattern is nearly identical. You swap out the Uvicorn worker class for Gunicorn's default synchronous workers:

# Flask production deployment (no need for uvicorn workers)
gunicorn app:app \
  --workers 4 \
  --bind 0.0.0.0:5000 \
  --timeout 120 \
  --access-logfile /var/log/myapp/access.log \
  --error-logfile /var/log/myapp/error.log
# Dockerfile for Flask
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["gunicorn", "app:app", "--workers", "4", "--bind", "0.0.0.0:5000"]
πŸ’‘ Django Deployment

Django uses the same Gunicorn pattern as Flask β€” it is WSGI by default (though Django 4+ supports ASGI). The command is gunicorn myproject.wsgi:application. For Django-specific production checklist items: set DEBUG=False, configure ALLOWED_HOSTS, set up STATIC_ROOT and run python manage.py collectstatic, and use a separate media file storage like S3 for user uploads.

The Complete Python Deployment Diagram

Python Production Deployment Stack
────────────────────────────────────────────────────────────────────
Request
  β”‚
  β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Nginx (port 443)                    β”‚  SSL, rate limiting, static files
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚  proxy_pass β†’ 127.0.0.1:8000
                   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Gunicorn (process manager)          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”‚  (2 Γ— CPU cores) + 1 workers
β”‚  β”‚Worker 0 β”‚ β”‚Worker 1 β”‚ β”‚Worker 2β”‚ β”‚  Each = full Python interpreter
β”‚  β”‚Uvicorn  β”‚ β”‚Uvicorn  β”‚ β”‚Uvicorn β”‚ β”‚  Async I/O inside each worker
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
                   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  FastAPI Application                 β”‚  Your code: routes, services, models
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β–Ό                    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  PostgreSQL    β”‚  β”‚  Redis Cache     β”‚
β”‚  (via async    β”‚  β”‚  (for sessions,  β”‚
β”‚  SQLAlchemy)   β”‚  β”‚  rate limiting)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Process supervision: Supervisor (bare metal) or Kubernetes (containers)
────────────────────────────────────────────────────────────────────

Environment Variables and Secrets

Python reads environment variables through os.environ, or more cleanly through Pydantic Settings (for FastAPI) or python-decouple (for any Python project). Both read from environment variables and optionally fall back to a .env file during local development:

# Using pydantic-settings for clean settings management
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    # These are REQUIRED β€” missing = app refuses to start
    database_url: str
    secret_key: str

    # These have defaults
    port: int = 8000
    debug: bool = False
    allowed_origins: list[str] = ["https://myapp.com"]

    model_config = SettingsConfigDict(
        env_file=".env",          # read from .env file in development
        case_sensitive=False,    # DATABASE_URL = database_url = same thing
    )

# Instantiate once at module level β€” shared across the application
settings = Settings()

On the production server, set environment variables through the supervisor config or a systemd EnvironmentFile. Never commit .env files to Git.

Chapter Summary

  • Never run python app.py or plain uvicorn main:app in production β€” these are single-process, single-point-of-failure configurations.
  • WSGI (Flask, Django) is synchronous. ASGI (FastAPI, Starlette) is asynchronous. Your choice determines your server setup.
  • Virtual environments isolate project dependencies. Always use one and pin exact versions with pip freeze.
  • Gunicorn + Uvicorn workers is the production standard for FastAPI: Gunicorn manages processes, Uvicorn workers handle async requests.
  • Worker count rule of thumb: (2 Γ— CPU cores) + 1.
  • Supervisor keeps Gunicorn alive on bare metal servers, restarting it on crashes and enabling it at boot.
  • Docker images should COPY requirements.txt and run pip install before copying application code β€” this exploits Docker layer caching.
  • Alembic manages database schema migrations as versioned, Git-tracked scripts β€” never alter production databases by hand.
  • Use Pydantic Settings to read configuration from environment variables, with automatic validation that catches missing secrets at startup.