Every argument of uvicorn.run() is keyword-only, except app. uvicorn.Config accepts the same arguments, except app_dir. Most of them have a command-line flag with dashes instead of underscores (ssl_keyfile becomes --ssl-keyfile). Each parameter comes with an example (expand it for the surrounding code) and has an anchor, for example /parameters/#ssl_context_factory.
Application
app
str | ASGI AppYour ASGI application. Can be a string in "module:attribute" format or the application object directly. Use the string with reload or workers.
import uvicorn
from fastapi import FastAPI
app = FastAPI()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)factory
bool FalseTreat app as an application factory (a callable that returns an ASGI app).
import uvicorn
from fastapi import FastAPI
def create_app() -> FastAPI:
return FastAPI()
if __name__ == "__main__":
uvicorn.run("main:create_app", factory=True)app_dir
str current directoryDirectory to add to sys.path when looking for the application module.
import uvicorn
# src/myproject/main.py defines app
if __name__ == "__main__":
uvicorn.run("myproject.main:app", app_dir="src")reset_contextvars
bool FalseRun each ASGI request in a fresh contextvars.Context. Works around a context leak in asyncio (uvloop is not affected). Hides context set during lifespan from request handlers.
from contextvars import ContextVar
import uvicorn
request_id: ContextVar[str] = ContextVar("request_id")
if __name__ == "__main__":
uvicorn.run("main:app", reset_contextvars=True)Socket Binding
host
str "127.0.0.1"Bind socket to this host. Use "0.0.0.0" to make the server available externally.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0") # reachable from other machinesport
int 8000Bind socket to this port. Use 0 to bind to an available port.
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", port=int(os.environ.get("PORT", "8000")))uds
strBind to a UNIX domain socket instead of TCP. Useful for reverse proxy setups.
import uvicorn
# nginx: proxy_pass http://unix:/run/myapp/uvicorn.sock;
if __name__ == "__main__":
uvicorn.run("main:app", uds="/run/myapp/uvicorn.sock")fd
intBind to socket from this file descriptor. Useful for socket activation.
import uvicorn
# Started by a systemd .socket unit (ListenStream=80)
if __name__ == "__main__":
uvicorn.run("main:app", fd=3) # first socket passed by systemdDevelopment
reload
bool FalseEnable auto-reload for development. Watches for file changes and restarts the server. The app must be an import string.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", reload=True)reload_dirs
list[str] current directoryDirectories to watch for file changes when reload is enabled.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", reload=True, reload_dirs=["src", "templates"])reload_delay
float 0.25Delay in seconds between detecting a change and reloading.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", reload=True, reload_delay=1.0)reload_includes
list[str]Glob patterns for files to include in reload watching. Requires watchfiles.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", reload=True, reload_includes=["*.py", "*.html"])reload_excludes
list[str]Glob patterns for files to exclude from reload watching. Requires watchfiles.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", reload=True, reload_excludes=["tests/*", "*.tmp"])Production
workers
int 1Number of worker processes. Reads from $WEB_CONCURRENCY env var if set. Cannot be used with reload. Send SIGHUP to restart workers one at a time without dropping requests.
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", workers=os.cpu_count())env_file
strPath to environment configuration file to load. Requires python-dotenv.
import uvicorn
# .env
# DATABASE_URL=postgresql://localhost/app
if __name__ == "__main__":
uvicorn.run("main:app", env_file=".env")timeout_worker_healthcheck
int 5Timeout in seconds for worker health check.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", workers=4, timeout_worker_healthcheck=10)Logging
log_level
str "info"Logging level: "critical", "error", "warning", "info", "debug", "trace" (case-insensitive).
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", log_level="debug")log_config
str | PathLike | dict LOGGING_CONFIGLogging configuration file path (.json, .yaml or .ini) or a dictionary config. YAML requires PyYAML. None leaves logging untouched.
import uvicorn
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"plain": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"}},
"handlers": {"console": {"class": "logging.StreamHandler", "formatter": "plain"}},
"loggers": {"uvicorn": {"handlers": ["console"], "level": "INFO"}},
}
if __name__ == "__main__":
uvicorn.run("main:app", log_config=LOGGING) # or a .json, .yaml or .ini pathaccess_log
bool TrueEnable or disable access logging.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", access_log=False) # the reverse proxy logs requestsuse_colors
bool auto-detectedEnable or disable colorized log formatting.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", use_colors=False) # plain logs for log collectorsProtocol Implementation
loop
str "auto"Event loop implementation: "auto", "asyncio", "uvloop", "zuvloop" (CPython 3.14+, installed separately), "none".
# pip install uvloop
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", loop="uvloop")http
str "auto"HTTP protocol implementation: "auto", "h11", "httptools", "zttp" (experimental, requires the zttp package).
# pip install httptools
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", http="httptools")http2
bool FalseEnable experimental HTTP/2. Requires http="zttp". h2c upgrade and WebSockets over HTTP/2 are not supported. See HTTP/2.
# pip install "zttp>=0.0.34"
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", http="zttp", http2=True)ws
str "auto"WebSocket protocol implementation: "auto", "none", "websockets-sansio", "wsproto", "websockets" (legacy, deprecated). "auto" picks websockets-sansio when websockets is installed.
# pip install wsproto
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws="wsproto")lifespan
str "auto"Lifespan protocol implementation: "auto", "on", "off".
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", lifespan="off") # no startup or shutdown eventsinterface
str "auto"Application interface type: "auto", "asgi3", "asgi2", "wsgi". "wsgi" is deprecated, wrap WSGI apps with a2wsgi instead.
import uvicorn
class App: # ASGI 2: instantiated with the scope, then called
def __init__(self, scope):
self.scope = scope
async def __call__(self, receive, send):
...
if __name__ == "__main__":
uvicorn.run(App, interface="asgi2")h11_max_incomplete_event_size
int 16384Maximum size of incomplete HTTP events buffer (h11 only).
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", http="h11", h11_max_incomplete_event_size=65536)WebSocket Settings
ws_max_size
int 16777216Maximum WebSocket message size in bytes (16 MB).
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws_max_size=1024 * 1024) # 1 MBws_max_queue
int 32Maximum WebSocket receive queue length (legacy websockets implementation only).
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws="websockets", ws_max_queue=64)ws_ping_interval
float | None 20.0WebSocket ping interval in seconds.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws_ping_interval=30.0)ws_ping_timeout
float | None 20.0WebSocket ping timeout in seconds.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws_ping_interval=30.0, ws_ping_timeout=10.0)ws_per_message_deflate
bool TrueEnable WebSocket per-message compression (legacy websockets implementation only).
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", ws="websockets", ws_per_message_deflate=False)HTTP Settings
root_path
str ""Set the ASGI root_path for applications mounted at a subpath.
import uvicorn
# Behind a proxy that serves the app at https://example.com/api
if __name__ == "__main__":
uvicorn.run("main:app", root_path="/api")proxy_headers
bool TrueTrust X-Forwarded-Proto and X-Forwarded-For from the IPs in forwarded_allow_ips.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", proxy_headers=False) # not behind a proxyforwarded_allow_ips
str | list "127.0.0.1"Comma-separated list of trusted proxy IPs, networks or UNIX socket paths. Reads $FORWARDED_ALLOW_IPS if set, else trusts "127.0.0.1" and "::1". Use "*" to trust all.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", forwarded_allow_ips="10.0.0.0/8") # load balancersserver_header
bool TrueInclude "Server" header in responses.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", server_header=False) # don't advertise uvicorndate_header
bool TrueInclude "Date" header in responses.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", date_header=False)headers
list[tuple[str, str]]Custom HTTP headers to add to all responses.
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
headers=[
("X-Frame-Options", "DENY"),
("X-Content-Type-Options", "nosniff"),
],
)HTTPS / SSL
import uvicorn
# openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -subj "/CN=localhost"
if __name__ == "__main__":
uvicorn.run("main:app", ssl_keyfile="key.pem", ssl_certfile="cert.pem")ssl_certfile
strPath to SSL certificate file for HTTPS support.
import uvicorn
# openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -subj "/CN=localhost"
if __name__ == "__main__":
uvicorn.run("main:app", ssl_certfile="cert.pem", ssl_keyfile="key.pem")ssl_keyfile_password
strPassword to decrypt the SSL key file if encrypted.
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_keyfile_password=os.environ["SSL_KEY_PASSWORD"],
)ssl_version
int ssl.PROTOCOL_TLS_SERVERSSL protocol version to use. To set a minimum TLS version, use ssl_context_factory.
import ssl
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_version=ssl.PROTOCOL_TLS_SERVER, # negotiates the best version
)import ssl
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs="client-ca.pem",
)ssl_ca_certs
strPath to CA certificates file for client certificate verification.
import ssl
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs="client-ca.pem", # CA that signed the client certificates
)ssl_ciphers
str NoneSSL ciphers to use, in OpenSSL cipher list format. None keeps OpenSSL's safe defaults.
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_ciphers="ECDHE+AESGCM:ECDHE+CHACHA20",
)ssl_context_factory
CallableFunction receiving (config, default_ssl_context_factory) and returning an ssl.SSLContext. Use it for mTLS, a minimum TLS version or in-memory certificates. Must be picklable with reload or workers. See custom SSL context.
import ssl
import uvicorn
def tls13_only(config, default_ssl_context_factory):
context = default_ssl_context_factory()
context.minimum_version = ssl.TLSVersion.TLSv1_3
return context
if __name__ == "__main__":
uvicorn.run(
"main:app",
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
ssl_context_factory=tls13_only,
)Resource Limits
limit_concurrency
intMaximum number of concurrent connections or tasks before answering HTTP 503.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", limit_concurrency=1000)limit_max_requests
intMaximum number of requests per worker before terminating and respawning.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", workers=4, limit_max_requests=10000) # caps leakslimit_max_requests_jitter
int 0Jitter to add to limit_max_requests to stagger worker restarts and avoid all workers restarting simultaneously.
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"main:app",
workers=4,
limit_max_requests=10000,
limit_max_requests_jitter=1000, # restart between 10000 and 11000
)backlog
int 2048Maximum number of pending connections in the connection backlog.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", backlog=4096)Timeouts
timeout_keep_alive
int 5Timeout in seconds for keep-alive connections. Behind a load balancer, set it above the balancer's idle timeout.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", timeout_keep_alive=75) # AWS ALB idle timeout is 60stimeout_graceful_shutdown
int NoneTimeout in seconds for graceful shutdown. After this time, connections are forcefully closed. None waits for them.
import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", timeout_graceful_shutdown=25) # Kubernetes waits 30s