Skip to main content

Deploy FastAPI on Linux — complete production setup

TL;DR

Complete guide to deploying a FastAPI application on Linux with Uvicorn, systemd, nginx, and SSL.

Key facts

Topology
FastAPI on Linux

TL;DR

This guide covers deploying a FastAPI application on Linux with Uvicorn, systemd, nginx, and SSL — a production-grade setup suitable for APIs and microservices.

Prerequisites

  • Ubuntu 24.04 or any modern Linux distribution
  • Python 3.11+
  • A domain name pointing to your server

Step 1 — System preparation

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-venv python3-pip build-essential

Step 2 — Deploy the application

sudo mkdir -p /var/www/fastapi-app
sudo chown $USER:$USER /var/www/fastapi-app
cd /var/www/fastapi-app
git clone git@github.com:yourorg/fastapi-app.git .
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

Verify the app starts:

uvicorn main:app --host 0.0.0.0 --port 8000
curl http://localhost:8000/health

Step 3 — Systemd service

Create /etc/systemd/system/fastapi.service:

[Unit]
Description=FastAPI Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/fastapi-app
ExecStart=/var/www/fastapi-app/venv/bin/uvicorn main:app \
    --host 0.0.0.0 \
    --port 8000 \
    --workers 4 \
    --access-log \
    --log-level info
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=/var/www/fastapi-app/.env

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start fastapi
sudo systemctl enable fastapi
sudo systemctl status fastapi

Step 4 — nginx reverse proxy

server {
    listen 80;
    server_name api.example.com;

    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_read_timeout 60s;
    }
}
sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Step 5 — SSL and firewall

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d api.example.com
sudo ufw allow 'Nginx Full'
sudo ufw allow OpenSSH
sudo ufw enable

Performance tuning

For high-throughput APIs, set workers to 2 * CPU_CORES + 1. For WebSocket support, use a single worker with uvloop:

pip install uvloop httptools
uvicorn main:app --loop uvloop --http httptools --workers 1

With Reflex

Connect Reflex to monitor your FastAPI deployment continuously. Reflex tracks Uvicorn process health, response times, error rates, and system resources. It can execute zero-downtime restarts, auto-scale workers based on load, and recover from crashes — all with a full audit trail. See How it works.