Deployment & Production Setup
Deploying FastAPI in production requires performance tuning, security, and scalability. Below is a detailed breakdown of deployment strategies, Dockerization, cloud platforms, HTTPS, and monitoring.
Deploying with Uvicorn + Gunicorn (Production)
FastAPI runs on ASGI servers. For production:
- Uvicorn (ASGI server for FastAPI)
- Gunicorn (process manager for Uvicorn workers)
Installation
pip install uvicorn gunicorn
Run FastAPI with Gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
Flag | Description |
---|---|
-w 4 | 4 worker processes (adjust per CPU cores) |
-k uvicorn.workers.UvicornWorker | Use Uvicorn workers |
Recommended Settings
gunicorn \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:80 \
--timeout 120 \
--log-level info \
main:app
Best Practices:
- Use 2x CPU cores + 1 for worker count.
- Set
--timeout
> FastAPI’s expected response time.
Dockerizing FastAPI Apps (Dockerfile
, docker-compose
)
(A) Basic Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "main:app", "--bind", "0.0.0.0:80"]