0
0
FastapiHow-ToBeginner · 4 min read

How to Configure FastAPI for Production: Best Practices

To configure 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.

bash
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.

python
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)
Output
{"message": "Hello, production FastAPI!"}
⚠️

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.

bash
## 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 Gunicorn with UvicornWorker for 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 NGINX for HTTPS and load balancing.
  • Enable logging and monitor app health.

Key Takeaways

Run FastAPI with Gunicorn and Uvicorn workers for production stability and performance.
Avoid using the built-in Uvicorn server alone in production environments.
Use environment variables to manage configuration securely and flexibly.
Set up HTTPS with a reverse proxy like NGINX to protect data in transit.
Configure logging and monitor your app to catch issues early.