Uvicorn is an ASGI (Asynchronous Server Gateway Interface) server for Python. It's the recommended server for running FastAPI applications.
# Basic usage
uvicorn main:app --reload
# Custom host and port
uvicorn main:app --host 0.0.0.0 --port 8080
# Number of workers (production)
uvicorn main:app --workers 4
# Log level
uvicorn main:app --log-level debug
# SSL
uvicorn main:app --ssl-keyfile key.pem --ssl-certfile cert.pem
# run.py
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)
Uvicorn fires startup and shutdown events:
@app.on_event("startup")
async def startup():
print("Server is starting...")
@app.on_event("shutdown")
async def shutdown():
print("Server is shutting down...")
--reload, change a line in main.py, and observe the auto-reload. Then run on port 8080 with 2 workers.