Deploying FastAPI in production

Difficulty: Intermediate

Question

How do you deploy a FastAPI application in production?

Answer

A production FastAPI deployment typically involves:

1. ASGI server - Uvicorn is the standard. For multi-core utilization, run Uvicorn workers behind Gunicorn: `gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker`

2. Reverse proxy - Nginx or Caddy in front for SSL termination, static files, load balancing, and request buffering.

3. Docker - Containerize the app with a multi-stage Dockerfile. Use a slim Python image.

4. Process management - Use Docker's restart policy, systemd, or supervisord to keep the app running.

5. HTTPS - Terminate SSL at the reverse proxy level (Let's Encrypt with Certbot or Caddy's auto-SSL).

Cloud options: AWS ECS/Fargate, Google Cloud Run, Azure Container Apps, Railway, Render, or traditional VPS with Docker Compose.

Code examples

Production Dockerfile

# Dockerfile
FROM python:3.12-slim AS base

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

# Run with Uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]

# Or with Gunicorn + Uvicorn workers (recommended)
# CMD ["gunicorn", "main:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker",
#      "--bind", "0.0.0.0:8000"]

Key points

Concepts covered

Uvicorn, Gunicorn, Docker, reverse proxy, HTTPS