FastAPI makes building APIs fast, but uvicorn main:app --reload on your laptop is not a production deployment. In production you need the app to start at boot, restart after crashes, run several worker processes, sit behind a web server that handles TLS and slow clients, and keep secrets out of your code. This guide builds that setup on a fresh Ubuntu 24.04 or Debian 12 VPS, step by step, with configuration you can copy.
The Production Architecture
Client ──HTTPS──▶ Nginx (:443) ──HTTP──▶ Uvicorn workers (127.0.0.1:8000) ──▶ PostgreSQL / Redis
│
└─ TLS, HTTP/2, request buffering, static files, rate limits
- Uvicorn is the ASGI server that runs your FastAPI code. With
--workers Nit starts N processes so you use several CPU cores. - systemd supervises Uvicorn: starts it at boot, restarts it on failure and collects its logs.
- Nginx terminates HTTPS, buffers slow clients, serves static files and forwards API requests to Uvicorn over localhost.
Uvicorn listens only on 127.0.0.1, so the app is never directly exposed to the internet.
Step 1: Prepare the Server
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-venv python3-pip nginx git
sudo adduser --system --group --home /opt/api api
A dedicated api system user means a bug in the app cannot touch the rest of the server. If you have not secured SSH and the firewall yet, do that first. Our UFW guide covers the firewall in ten minutes.
Step 2: Deploy the Code and Virtual Environment
sudo -u api git clone https://github.com/your-org/your-api.git /opt/api/app
sudo -u api python3 -m venv /opt/api/venv
sudo -u api /opt/api/venv/bin/pip install --upgrade pip
sudo -u api /opt/api/venv/bin/pip install -r /opt/api/app/requirements.txt
Your requirements.txt should include fastapi and uvicorn[standard] (or fastapi[standard], which pulls in Uvicorn). The [standard] extra installs uvloop and httptools, which Uvicorn uses automatically for better performance. Pin versions so a deploy never pulls in an unexpected major upgrade.
A minimal app for testing, in /opt/api/app/main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}
Quick check before going further:
sudo -u api /opt/api/venv/bin/uvicorn main:app --app-dir /opt/api/app --host 127.0.0.1 --port 8000
curl http://127.0.0.1:8000/health # in a second terminal
Step 3: Store Configuration and Secrets
Keep database URLs and API keys out of Git. Put them in an environment file that only the service can read:
sudo tee /opt/api/.env >/dev/null <<'EOF'
DATABASE_URL=postgresql://api:change-me@127.0.0.1:5432/api
SECRET_KEY=generate-a-long-random-value
EOF
sudo chown api:api /opt/api/.env
sudo chmod 600 /opt/api/.env
Read them in your app with os.environ or pydantic-settings. systemd loads the file in the next step.
Step 4: Run Uvicorn with systemd
Create /etc/systemd/system/api.service:
[Unit]
Description=FastAPI application
After=network.target
[Service]
User=api
Group=api
WorkingDirectory=/opt/api/app
EnvironmentFile=/opt/api/.env
ExecStart=/opt/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=always
RestartSec=3
# Basic sandboxing
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now api
sudo systemctl status api
journalctl -u api -f
--proxy-headers with --forwarded-allow-ips 127.0.0.1 tells Uvicorn to trust the X-Forwarded-For and X-Forwarded-Proto headers from Nginx only, so request.client.host shows the real visitor IP and generated URLs use https.
How many workers?
FastAPI's async endpoints handle many concurrent requests inside one process, so you need far fewer workers than a synchronous framework. Start with one worker per vCore, then measure. Each worker is a separate Python process with its own memory, typically tens to a few hundred MB depending on your dependencies, so check free -h after scaling up. If your endpoints call blocking libraries (synchronous database drivers, heavy CPU work), define them with plain def so FastAPI runs them in a thread pool, or move heavy work to a background queue.
Step 5: Configure Nginx as a Reverse Proxy
Create /etc/nginx/sites-available/api:
upstream fastapi {
server 127.0.0.1:8000;
keepalive 32;
}
server {
listen 80;
server_name api.example.com;
client_max_body_size 10m;
location / {
proxy_pass http://fastapi;
proxy_http_version 1.1;
proxy_set_header Connection "";
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/api /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo ufw allow 'Nginx Full'
If your API uses WebSockets, add a separate location for those paths with proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "upgrade";. The empty Connection header above is for keep-alive to the upstream and would break WebSocket upgrades.
Step 6: Enable HTTPS
Point an A record for api.example.com at the VPS, then:
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot --nginx -d api.example.com
sudo certbot renew --dry-run
Certbot adds the certificate and an HTTP-to-HTTPS redirect. The full process, including wildcard certificates and Cloudflare, is in our Let's Encrypt guide.
Step 7: Deploy Updates Safely
cd /opt/api/app
sudo -u api git pull
sudo -u api /opt/api/venv/bin/pip install -r requirements.txt
# run database migrations here, e.g. alembic upgrade head
sudo systemctl restart api
curl -fsS https://api.example.com/health
A restart drops in-flight requests for a moment. That is acceptable for many internal APIs. For zero-downtime releases, run two instances on different ports behind the Nginx upstream and restart them one at a time.
Production Checklist
| Area | What to do |
|---|---|
| Docs exposure | Disable /docs and /redoc in production if the API is not public: FastAPI(docs_url=None, redoc_url=None) |
| CORS | List exact allowed origins; never combine allow_origins=["*"] with credentials |
| Database | Use a connection pool sized to workers × pool size below the database's max connections |
| Background work | Send long tasks to a queue (Celery, RQ, ARQ) instead of BackgroundTasks for anything that must survive restarts |
| Rate limiting | Add limit_req in Nginx for login and expensive endpoints |
| Logs | journalctl -u api; ship to a central store if you run several servers |
| Health check | Monitor /health from outside with an uptime checker |
| Memory | Add a small swap file as a safety net (see our swap guide) |
Alternative: Run It in Docker
If you already ship containers, the same architecture works with Docker: run the app container with uvicorn as the command, publish it only on localhost (-p 127.0.0.1:8000:8000) and keep Nginx in front, either on the host or as another container. Publishing on localhost matters because Docker's port rules bypass UFW.
SkyRainCloud Plans for This Workload
FastAPI itself is light; your database, background jobs and traffic decide the plan. A single API with PostgreSQL on the same server runs well on 2 vCores / 8 GB. Choose 4 vCores / 16 GB when you add workers, Redis or heavier queries, and AMD EPYC when you scale out to many Uvicorn workers.
AMD EPYC 7C13 VPS
Dedicated KVM vCores on AMD EPYC 7C13 (up to 3.70 GHz) with DDR4 ECC memory, NVMe SSD and an unmetered 1 Gbps port.
| Plan | vCores | RAM | Storage | Network | Price | Good for | Buy |
|---|---|---|---|---|---|---|---|
| VPS 1 — AMD | 2 | 8 GB DDR4 ECC | 40 GB NVMe SSD | 1 Gbps, unmetered | ₹649/month | Websites, small APIs, bots, staging and VPN servers | Order |
| VPS 2 — AMD | 4 | 16 GB DDR4 ECC | 80 GB NVMe SSD | 1 Gbps, unmetered | ₹1,299/month | WooCommerce, Node.js/Python backends, Docker Compose stacks, CI runners | Order |
| VPS 3 — AMD | 8 | 32 GB DDR4 ECC | 150 GB NVMe SSD | 1 Gbps, unmetered | ₹2,499/month | Production databases, high-traffic sites, multi-container apps | Order |
| VPS 4 — AMD | 16 | 64 GB DDR4 ECC | 250 GB NVMe SSD | 1 Gbps, unmetered | ₹4,899/month | Large production workloads, SaaS platforms, analytics, in-memory caches | Order |
Intel Xeon Platinum 8269CY VPS
KVM VPS on Intel Xeon Platinum 8269CY (up to 3.80 GHz Turbo) with DDR4 ECC memory, NVMe SSD, full root access and an unmetered 1 Gbps port.
| Plan | vCores | RAM | Storage | Network | Price | Good for | Buy |
|---|---|---|---|---|---|---|---|
| VPS 1 — Intel | 2 | 8 GB DDR4 ECC | 40 GB NVMe SSD | 1 Gbps, unmetered | ₹649/month | Business websites, small apps, scheduled jobs and bots | Order |
| VPS 2 — Intel | 4 | 16 GB DDR4 ECC | 80 GB NVMe SSD | 1 Gbps, unmetered | ₹1,169/month | Business software, mid-size databases, several sites on one server | Check stock |
| VPS 3 — Intel | 8 | 32 GB DDR4 ECC | 150 GB NVMe SSD | 1 Gbps, unmetered | ₹2,249/month | ERP/CRM stacks, heavier databases, multiple production apps | Check stock |
| VPS 4 — Intel | 16 | 64 GB DDR4 ECC | 250 GB NVMe SSD | 1 Gbps, unmetered | ₹4,299/month | High-memory workloads and consolidated production servers | Check stock |
Prices are monthly in INR as listed on the SkyRainCloud store (verified 2026-11-14). Stock and final pricing are shown on the product page at checkout.
Troubleshooting
| Problem | Check |
|---|---|
| 502 Bad Gateway | Is the service running? systemctl status api, curl 127.0.0.1:8000/health; read journalctl -u api |
| Service exits immediately | Wrong WorkingDirectory or module path, missing package in the venv, unreadable .env |
| Client IP shows 127.0.0.1 | Add --proxy-headers --forwarded-allow-ips 127.0.0.1 and the X-Forwarded-For header in Nginx |
| Redirects go to http:// | Pass X-Forwarded-Proto from Nginx and enable proxy headers in Uvicorn |
| 413 Request Entity Too Large | Raise client_max_body_size in Nginx |
| 504 on long requests | Raise proxy_read_timeout, or better, move the work to a background job |
Frequently Asked Questions
Is Uvicorn alone enough for production?
--workers can serve production traffic, but put Nginx in front for TLS, slow-client buffering, static files and rate limiting, and run it under systemd so it restarts automatically.Should I use Gunicorn with Uvicorn workers?
--workers, which is simpler. Use Gunicorn if you rely on its specific features, such as its hooks or graceful reload behaviour.How many Uvicorn workers should I run?
Where should I store secrets for a FastAPI app?
/opt/api/.env owned by the service user with mode 600, loaded by systemd's EnvironmentFile=. Never commit secrets to Git.Why does FastAPI generate http:// URLs behind Nginx?
X-Forwarded-Proto from Nginx and start Uvicorn with --proxy-headers --forwarded-allow-ips 127.0.0.1.Can I run FastAPI and PostgreSQL on the same VPS?
shared_buffers for the RAM you have, and keep the database port closed in the firewall. Split them onto separate servers when either needs more resources.How much RAM does a FastAPI app need?
How do I deploy FastAPI updates without downtime?
Should I disable the /docs page in production?
docs_url=None, redoc_url=None. Public APIs can keep the docs, ideally behind authentication.