0
0
FastapiHow-ToBeginner · 3 min read

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 8000 to start the server.
  • module_name is the Python file without .py.
  • app_instance is the FastAPI app object inside that file.
  • --host 0.0.0.0 makes the app accessible externally.
  • --port sets 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.0 makes the app inaccessible from outside localhost.
  • For production, use Gunicorn with 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 Uvicorn for development and quick testing.
  • Use Gunicorn with Uvicorn workers for production.
  • Set --host 0.0.0.0 to allow external access.
  • Consider Docker or process managers like systemd or supervisord for managing your app in production.
  • Use HTTPS and reverse proxies like NGINX for 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.