Gunicorn helps run your FastAPI app smoothly by managing multiple workers. Uvicorn workers let Gunicorn handle async FastAPI code efficiently.
0
0
Gunicorn with Uvicorn workers in FastAPI
Introduction
You want to run a FastAPI app in production with multiple workers for better performance.
You need to handle many users at the same time without slowing down.
You want to use Gunicorn's process management with FastAPI's async features.
You want to restart workers automatically if they crash.
You want to serve your FastAPI app behind a web server like Nginx.
Syntax
FastAPI
gunicorn -w <number_of_workers> -k uvicorn.workers.UvicornWorker <module_name>:<app_instance>
-w sets how many worker processes Gunicorn runs.
-k uvicorn.workers.UvicornWorker tells Gunicorn to use Uvicorn workers for async support.
Examples
Runs 4 Uvicorn workers from the FastAPI app in
main.py named app.FastAPI
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:appRuns 2 workers for the FastAPI app in
myapi.py.FastAPI
gunicorn -w 2 -k uvicorn.workers.UvicornWorker myapi:appSample Program
This is a simple FastAPI app that returns a greeting message. You run it with Gunicorn using Uvicorn workers to handle multiple requests efficiently.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get('/') async def read_root(): return {"message": "Hello from FastAPI with Gunicorn and Uvicorn workers!"} # To run this app with Gunicorn and Uvicorn workers, use: # gunicorn -w 3 -k uvicorn.workers.UvicornWorker main:app
OutputSuccess
Important Notes
Make sure you install both gunicorn and uvicorn in your environment.
Use an odd number of workers for better load balancing in some cases.
Gunicorn manages worker processes, while Uvicorn handles async requests inside each worker.
Summary
Gunicorn with Uvicorn workers runs FastAPI apps efficiently in production.
Use -w to set worker count and -k uvicorn.workers.UvicornWorker for async support.
This setup improves performance and reliability for real users.