On this page
- Uvicorn alone or Gunicorn with Uvicorn workers?
- What should you prepare first?
- How do you create the FastAPI application?
- How do you test the app before making it a service?
- How do you run Uvicorn workers with systemd?
- How do you use Gunicorn as the process manager instead?
- How do you put Nginx in front with WebSocket support?
- How do you secure the API with a firewall and TLS?
- How do you deploy new versions and fix common errors?
- Questions
Uvicorn alone or Gunicorn with Uvicorn workers?
Either is a sound production setup, and the choice mostly comes down to which process manager you prefer. FastAPI is an ASGI framework, so something that speaks ASGI must run it, and Uvicorn is that server.
- uvicorn --workers N: Uvicorn starts N processes and, in current releases, restarts any worker that dies. One package, fewer moving parts.
- gunicorn -k uvicorn_worker.UvicornWorker: Gunicorn manages the processes and each one runs Uvicorn inside. You get Gunicorn features such as graceful reloads on HUP, worker timeouts and changing the worker count at runtime with TTIN and TTOU signals.
- Containers: if an orchestrator already restarts and scales containers, one Uvicorn process per container is often enough.
The worker class used to live at uvicorn.workers.UvicornWorker. That path is deprecated in favour of the separate uvicorn-worker package used below.
What should you prepare first?
Prepare a sudo user, a DNS record such as api.example.net pointing at 198.51.100.24 (and the AAAA record for 2001:db8:4f2a::24), Python 3.10 or newer and Nginx.
# Ubuntu and Debian
sudo apt update
sudo apt install -y python3-venv nginx
# Rocky Linux and AlmaLinux 9 (the default 3.9 is too old for current FastAPI)
sudo dnf install -y python3.12 nginx
sudo systemctl enable --now nginxOn Ubuntu 22.04 the system Python is 3.10, which is still accepted; Ubuntu 24.04, Debian 12 and Debian 13 ship newer versions. If you want an even newer interpreter, the Python, pip and venv guide shows several routes.
How do you create the FastAPI application?
Make a project folder owned by the service user, create the environment and install FastAPI with its standard extras, which bring in Uvicorn with its fast event loop and HTTP parser.
sudo mkdir -p /srv/api
sudo chown deploy:deploy /srv/api
cd /srv/api
python3 -m venv .venv # python3.12 on Rocky and Alma
.venv/bin/pip install --upgrade pip
.venv/bin/pip install "fastapi[standard]" gunicorn uvicorn-worker
.venv/bin/uvicorn --version
cat > main.py <<'EOF'
import os
from fastapi import FastAPI
show_docs = os.getenv("API_DOCS", "0") == "1"
app = FastAPI(
title="Inventory API",
docs_url="/docs" if show_docs else None,
redoc_url=None,
)
@app.get("/health")
async def health():
return {"status": "ok", "pid": os.getpid()}
EOF
.venv/bin/pip freeze > requirements.txtThe pid field is a small trick: repeated requests return different process ids, which proves several workers are answering. The interactive docs are switched off unless API_DOCS=1 is set, so a public server does not publish its schema by accident.
How do you test the app before making it a service?
Run it once in the foreground with the development command, then once with workers, and call it with curl from a second terminal.
cd /srv/api
.venv/bin/fastapi dev main.py # auto reload, port 8000, for testing only
.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 2
# second terminal
for i in 1 2 3 4; do curl -s http://127.0.0.1:8000/health; echo; doneStop each run with Ctrl+C. Use one worker per vCPU as a starting point for async endpoints. If your handlers call blocking libraries or do heavy computation, add workers carefully and watch memory, because each worker imports the whole application.
How do you run Uvicorn workers with systemd?
Keep settings in an environment file and point the unit at the Uvicorn binary inside the environment. The proxy header options make the app see the real client address and scheme sent by Nginx.
sudo tee /etc/api.env >/dev/null <<'EOF'
API_DOCS=0
DATABASE_URL=postgresql://api:change-me@127.0.0.1/inventory
EOF
sudo chmod 600 /etc/api.env
sudo tee /etc/systemd/system/api.service >/dev/null <<'EOF'
[Unit]
Description=FastAPI served by Uvicorn
After=network.target
[Service]
User=deploy
WorkingDirectory=/srv/api
EnvironmentFile=/etc/api.env
ExecStart=/srv/api/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 2 --proxy-headers --forwarded-allow-ips 127.0.0.1
Restart=on-failure
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now api
systemctl status api --no-pager
ss -ltnp | grep 8000systemd reads /etc/api.env as root before dropping to the deploy user, so the mode 600 file is fine. Follow the log with journalctl -u api -f.
How do you use Gunicorn as the process manager instead?
Swap the ExecStart line for a Gunicorn command with the Uvicorn worker class, and add a reload line so code updates can roll out gracefully.
ExecStart=/srv/api/.venv/bin/gunicorn main:app \
--worker-class uvicorn_worker.UvicornWorker \
--workers 2 --bind 127.0.0.1:8000 \
--timeout 60 --graceful-timeout 30 \
--forwarded-allow-ips 127.0.0.1 \
--access-logfile -
ExecReload=/bin/kill -s HUP $MAINPIDsudo systemctl edit --full api # paste the lines above
sudo systemctl restart api
sudo systemctl reload api # later, after deploying new code
ps -o pid,ppid,cmd -u deploy | grep gunicornThe ps output shows one Gunicorn master and its worker children. If a request takes longer than timeout, Gunicorn kills and replaces that worker, which protects the service from stuck handlers.
How do you put Nginx in front with WebSocket support?
Proxy all paths to port 8000 and pass the upgrade headers, so FastAPI WebSocket routes work through the proxy as well as normal HTTP.
map $http_upgrade $connection_upgrade {
default upgrade;
"" close;
}
server {
listen 80;
listen [::]:80;
server_name api.example.net;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 120s;
}
}Save it as /etc/nginx/sites-available/api and link it into sites-enabled on Ubuntu and Debian, or as /etc/nginx/conf.d/api.conf on Rocky and Alma, where you also run sudo setsebool -P httpd_can_network_connect 1. Then test and reload with sudo nginx -t && sudo systemctl reload nginx. A wider look at proxy settings is in the Nginx reverse proxy guide.
How do you secure the API with a firewall and TLS?
Open only SSH, HTTP and HTTPS, then request a certificate with certbot. Uvicorn stays on localhost and needs no firewall rule.
# Ubuntu and Debian
sudo ufw allow OpenSSH
sudo ufw allow "Nginx Full"
sudo ufw enable
sudo apt install -y certbot python3-certbot-nginx
# Rocky and Alma
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload
sudo dnf install -y epel-release && sudo dnf install -y certbot python3-certbot-nginx
sudo certbot --nginx -d api.example.net
curl -s https://api.example.net/healthFor request limits per client, add the zones described in Nginx rate limiting; an API that takes payments or logins benefits from them on day one.
How do you deploy new versions and fix common errors?
Pull the code, install the locked requirements and restart or reload the service.
cd /srv/api
git pull
.venv/bin/pip install -r requirements.txt
sudo systemctl restart api # Uvicorn workers
# or: sudo systemctl reload api # Gunicorn master, graceful
curl -s http://127.0.0.1:8000/health- 502 from Nginx: the service is down or crashed on import; read
journalctl -u api -n 50. - Wrong client IP or http links behind HTTPS: check
--proxy-headersand--forwarded-allow-ips, and that Nginx sends theX-Forwardedheaders. - WebSocket closes at once: the
UpgradeandConnectionheaders orproxy_http_version 1.1are missing. - Memory grows with workers: lower the worker count or move heavy jobs to a queue such as Celery.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
| Plan | Fits because | Size | Monthly | Order from |
|---|---|---|---|---|
| A1-2 | one API with two workers | 1 vCPU, 2 GB RAM, 50 GB NVMe | $7.20/mo | $43.20 for 6 months |
| A2-4 | four workers plus Redis or a database | 2 vCPU, 4 GB RAM, 100 GB NVMe | $14.40/mo | $43.20 for 3 months |
| F2-4 | higher clock speed for request heavy APIs | 2 vCPU, 4 GB RAM, 128 GB NVMe | $14.40/mo | $43.20 for 3 months |
Questions about Deploy FastAPI with Uvicorn workers
Is uvicorn --workers good enough for production?
Yes. Current Uvicorn releases supervise their workers and replace any that exit. Gunicorn adds graceful reloads and worker timeouts, which some teams prefer.
Which import path should the worker class use?
Use uvicorn_worker.UvicornWorker from the uvicorn-worker package. The older uvicorn.workers.UvicornWorker path is deprecated.
What does fastapi run do?
It is a thin command around Uvicorn for production use; fastapi run main.py --workers 2 is similar to the Uvicorn command in this guide, but listens on all addresses by default, so add --host 127.0.0.1 behind a proxy.
Should the /docs page stay online?
Only if the API is meant to be public. Disable it in production, or protect it behind authentication in Nginx, so you do not publish your schema unintentionally.
How many workers fit on a small plan?
A minimal FastAPI worker uses well under 100 MB, but real apps with database drivers and data libraries use more. Measure with ps or free -h and size the count to the RAM you have.
More in Python
- Install Python 3, pip and venv
- Run legacy Python 2 code
- Manage Python projects with Poetry
- Miniconda and Anaconda on a server
- Deploy Flask with Gunicorn and Nginx
- Deploy Django with Gunicorn and Nginx
- Background tasks with Celery and Redis
- Host a Python Discord bot
- Containerise a Python web app
- JupyterLab on a server
- Host a Python Telegram bot