How to Configure FastAPI for Production: Best Practices
FastAPI for production, run it with an ASGI server like Uvicorn behind a process manager such as Gunicorn for better performance and reliability. Use environment variables for configuration, enable HTTPS via a reverse proxy, and set proper logging and timeout settings.Syntax
Production FastAPI apps typically run with Gunicorn managing multiple Uvicorn worker processes. The basic command syntax is:
gunicorn -k uvicorn.workers.UvicornWorker -w [workers] -b [host:port] [module]:[app]
Here, -k specifies the worker class, -w the number of workers, -b the bind address, and [module]:[app] points to your FastAPI app instance.
gunicorn -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000 main:app
Example
This example shows a simple FastAPI app configured to run with Gunicorn and Uvicorn workers. It uses environment variables for configuration and includes logging setup.
from fastapi import FastAPI import os import logging app = FastAPI() logging.basicConfig(level=logging.INFO) @app.get("/") async def read_root(): logging.info("Root endpoint called") return {"message": "Hello, production FastAPI!"} if __name__ == "__main__": import uvicorn host = os.getenv("HOST", "0.0.0.0") port = int(os.getenv("PORT", 8000)) uvicorn.run(app, host=host, port=port)
Common Pitfalls
Running FastAPI with the built-in server in production: The built-in uvicorn.run() is for development only and lacks robustness for production.
Not using multiple workers: Single worker limits concurrency and performance.
Ignoring environment variables: Hardcoding config makes deployments inflexible and insecure.
Missing HTTPS setup: Serving HTTP without TLS exposes data and credentials.
## Wrong way (development server in production): # uvicorn main:app --host 0.0.0.0 --port 8000 ## Right way (production): # gunicorn -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000 main:app
Quick Reference
- Use
GunicornwithUvicornWorkerfor production. - Set worker count based on CPU cores (usually 2-4 per core).
- Configure environment variables for host, port, and secrets.
- Use a reverse proxy like
NGINXfor HTTPS and load balancing. - Enable logging and monitor app health.