0
0
FastapiHow-ToBeginner · 3 min read

How to Use Gunicorn with FastAPI for Production Deployment

To use gunicorn with fastapi, run Gunicorn specifying Uvicorn workers with the command gunicorn -w 4 -k uvicorn.workers.UvicornWorker module_name:app. This runs your FastAPI app with multiple worker processes for better performance in production.
📐

Syntax

The basic command to run FastAPI with Gunicorn uses Uvicorn workers. Here is the syntax:

  • gunicorn: The server to run your app.
  • -w 4: Number of worker processes (4 is common for multi-core CPUs).
  • -k uvicorn.workers.UvicornWorker: Use Uvicorn worker class to run ASGI apps like FastAPI.
  • module_name:app: Python module and FastAPI app instance to run.
bash
gunicorn -w 4 -k uvicorn.workers.UvicornWorker module_name:app
💻

Example

This example shows a simple FastAPI app in main.py and how to run it with Gunicorn using Uvicorn workers.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello from FastAPI with Gunicorn!"}

# Save this as main.py

# Run with:
# gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
Output
When you visit http://127.0.0.1:8000/ you will see JSON: {"message": "Hello from FastAPI with Gunicorn!"}
⚠️

Common Pitfalls

Common mistakes when using Gunicorn with FastAPI include:

  • Not specifying the Uvicorn worker class (-k uvicorn.workers.UvicornWorker), which causes Gunicorn to fail because it cannot run ASGI apps by default.
  • Using the wrong module or app name in the command, leading to import errors.
  • Not installing uvicorn or gunicorn in your environment.
  • Running Gunicorn without enough workers for your CPU, causing poor performance.

Wrong command example:

gunicorn main:app

This will fail because Gunicorn needs the Uvicorn worker for ASGI apps.

Correct command:

gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
📊

Quick Reference

Summary tips for using Gunicorn with FastAPI:

  • Always use -k uvicorn.workers.UvicornWorker to run FastAPI apps.
  • Set -w to the number of CPU cores for better concurrency.
  • Ensure your app instance is correctly referenced as module_name:app.
  • Install dependencies with pip install fastapi uvicorn gunicorn.
  • Use environment variables or config files for advanced Gunicorn settings.

Key Takeaways

Use Gunicorn with Uvicorn workers to run FastAPI apps in production.
Specify the worker class with -k uvicorn.workers.UvicornWorker for ASGI support.
Set the number of workers (-w) based on your CPU cores for better performance.
Always reference your FastAPI app as module_name:app in the Gunicorn command.
Install all required packages: fastapi, uvicorn, and gunicorn.