23. Deploying FastAPI to Production
Taking your FastAPI application from development to production requires careful consideration of performance, security, reliability, and scalability. This module covers production deployment strategies using Gunicorn + Uvicorn workers, process management, and cloud deployment options. To test these examples, you will need a production server or cloud account.
Production Server: Gunicorn + Uvicorn
While Uvicorn is great for development, production deployments typically use Gunicorn as a process manager with Uvicorn workers for optimal performance.
pip install gunicorn uvicorn gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:app gunicorn -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 app.main:app gunicorn -w 4 -k uvicorn.workers.UvicornWorker --timeout 120 --max-requests 1000 app.main:app
Worker Configuration
The number of workers should be (2 x CPU cores) + 1. For a 4-core server, use 9 workers. This formula balances CPU utilization and context switching overhead.
Environment Configuration
Use different settings for production vs development.
# app/config.py from pydantic_settings import BaseSettings class Settings(BaseSettings): ENVIRONMENT: str = "development" @property def DEBUG(self) -> bool: return self.ENVIRONMENT == "development" @property def RELOAD(self) -> bool: return self.ENVIRONMENT == "development" DATABASE_URL: str @property def DATABASE_POOL_SIZE(self) -> int: return 20 if self.ENVIRONMENT == "production" else 5 SECRET_KEY: str ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 BACKEND_CORS_ORIGINS: list[str] = [] @property def CORS_ORIGINS(self) -> list[str]: if self.ENVIRONMENT == "production": return self.BACKEND_CORS_ORIGINS return ["http://localhost:3000"] class Config: env_file = ".env" settings = Settings()
Production Dockerfile
FROM python:3.11-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m -u 1000 fastapi && chown -R fastapi:fastapi /app
USER fastapi
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000", "app.main:app"]
Deploying to Cloud Platforms
Heroku Deployment
# Procfile web: gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:app git push heroku main
Render Deployment
# render.yaml
services:
- type: web
name: fastapi-app
runtime: python
buildCommand: pip install -r requirements.txt
startCommand: gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:app
envVars:
- key: DATABASE_URL
fromDatabase:
name: my-db
property: connectionString
- key: SECRET_KEY
sync: false
Health Check Endpoint
Health checks are essential for load balancers and container orchestrators.
from fastapi import FastAPI, Depends from sqlalchemy import text from datetime import datetime app = FastAPI() @app.get("/health") async def health_check(db: Session = Depends(get_db)): try: db.execute(text("SELECT 1")) db_status = "healthy" except Exception: db_status = "unhealthy" return { "status": "healthy" if db_status == "healthy" else "degraded", "timestamp": datetime.now().isoformat(), "database": db_status, "version": settings.VERSION } @app.get("/health/live") async def liveness_probe(): return {"status": "alive"} @app.get("/health/ready") async def readiness_probe(db: Session = Depends(get_db)): checks = {} try: db.execute(text("SELECT 1")) checks["database"] = "healthy" except Exception as e: checks["database"] = f"unhealthy: {str(e)}" all_healthy = all(v == "healthy" for v in checks.values()) status_code = 200 if all_healthy else 503 return JSONResponse( status_code=status_code, content={"status": "ready" if all_healthy else "not_ready", "checks": checks} )
Production Monitoring with Prometheus
from prometheus_fastapi_instrumentator import Instrumentator from prometheus_client import Counter, Histogram, Gauge app = FastAPI() Instrumentator().instrument(app).expose(app) REQUEST_COUNT = Counter("http_requests_total", "Total HTTP requests", ["method", "endpoint", "status"]) REQUEST_LATENCY = Histogram("http_request_duration_seconds", "HTTP request latency", ["method", "endpoint"]) ACTIVE_CONNECTIONS = Gauge("active_connections", "Number of active connections") @app.middleware("http") async def metrics_middleware(request: Request, call_next): ACTIVE_CONNECTIONS.inc() start = time.time() response = await call_next(request) duration = time.time() - start REQUEST_COUNT.labels(method=request.method, endpoint=request.url.path, status=response.status_code).inc() REQUEST_LATENCY.labels(method=request.method, endpoint=request.url.path).observe(duration) ACTIVE_CONNECTIONS.dec() return response
Knowledge Check
Ready to test your understanding of 23. Deploying FastAPI to Production?