AskReference
ProcessIntermediate

How do you run FastAPI with Gunicorn and Uvicorn workers, and what is the command?

Install the required packages and run Gunicorn with the Uvicorn worker class: `pip install "uvicorn[standard]" gunicorn` and then `gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000`. This starts a top-level Gunicorn process managing four Uvicorn worker subprocesses sharing port 8000. Adjust the host, port, or number of workers as needed.

The command uses Gunicorn as a process supervisor with a special Uvicorn worker class, since FastAPI is based on ASGI and Gunicorn by itself is a WSGI server. The `main:app` argument points to the `app` FastAPI object defined in `main.py`. The quotes around `uvicorn[standard]` protect the shell from interpreting the brackets. This method is usually preferred over running Uvicorn directly with multiple workers because Uvicorn's own `--workers` option does not provide full process management. The Gunicorn documentation suggests that 4 to 12 worker processes are typically enough to handle hundreds or thousands of requests per second.

Key points

  • Install dependencies with: pip install "uvicorn[standard]" gunicorn
  • Run with: gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
  • Gunicorn supervises Uvicorn worker subprocesses, all sharing the same port
  • main:app refers to the FastAPI instance named app in main.py
  • Change --workers, --host, or --port to suit your needs
Source:FastAPI: Modern Python Web Development· Production· p. 203–209

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook