How to Deploy FastAPI: Simple Steps for Production
To deploy
FastAPI, use an ASGI server like Uvicorn or Gunicorn with Uvicorn workers. Run your app with uvicorn main:app --host 0.0.0.0 --port 8000 for development, and use process managers or Docker for production deployment.Syntax
Deploying FastAPI involves running your app with an ASGI server. The common syntax is:
uvicorn module_name:app_instance --host 0.0.0.0 --port 8000to start the server.module_nameis the Python file without.py.app_instanceis the FastAPI app object inside that file.--host 0.0.0.0makes the app accessible externally.--portsets the listening port.
bash
uvicorn main:app --host 0.0.0.0 --port 8000
Example
This example shows a simple FastAPI app and how to run it with Uvicorn.
python
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI deployment!"} # Run this with: # uvicorn main:app --host 0.0.0.0 --port 8000
Output
When you visit http://localhost:8000/ you get JSON: {"message": "Hello, FastAPI deployment!"}
Common Pitfalls
- Running FastAPI with the built-in
uvicorn.run()in production is not recommended because it lacks robustness. - Not setting
--host 0.0.0.0makes the app inaccessible from outside localhost. - For production, use
Gunicornwith Uvicorn workers for better process management. - For example,
gunicorn -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000.
bash
## Wrong way (development only): # uvicorn.run(app) ## Right way (production): # gunicorn -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000
Quick Reference
Summary tips for deploying FastAPI:
- Use
Uvicornfor development and quick testing. - Use
Gunicornwith Uvicorn workers for production. - Set
--host 0.0.0.0to allow external access. - Consider Docker or process managers like
systemdorsupervisordfor managing your app in production. - Use HTTPS and reverse proxies like
NGINXfor security and performance.
Key Takeaways
Use Uvicorn to run FastAPI apps with the syntax: uvicorn module:app --host 0.0.0.0 --port 8000.
For production, run FastAPI with Gunicorn and Uvicorn workers for better stability.
Always set the host to 0.0.0.0 to allow external access to your app.
Use process managers or Docker to keep your app running reliably in production.
Secure your deployment with HTTPS and reverse proxies like NGINX.