Application Hosting15 min read•Updated November 2026

How to Deploy a FastAPI Application on a VPS with Uvicorn and Nginx

Quick answer

To deploy FastAPI on a VPS: install Python and Nginx, put your app in a virtual environment, run it with Uvicorn bound to 127.0.0.1:8000 under a systemd service (so it starts on boot and restarts on failure), and configure Nginx as a reverse proxy on ports 80/443 with a free Let's Encrypt certificate. Start with about one Uvicorn worker per vCore and keep secrets in an environment file readable only by the service user.

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 N it 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

AreaWhat to do
Docs exposureDisable /docs and /redoc in production if the API is not public: FastAPI(docs_url=None, redoc_url=None)
CORSList exact allowed origins; never combine allow_origins=["*"] with credentials
DatabaseUse a connection pool sized to workers × pool size below the database's max connections
Background workSend long tasks to a queue (Celery, RQ, ARQ) instead of BackgroundTasks for anything that must survive restarts
Rate limitingAdd limit_req in Nginx for login and expensive endpoints
Logsjournalctl -u api; ship to a central store if you run several servers
Health checkMonitor /health from outside with an uptime checker
MemoryAdd 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.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — AMD28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthWebsites, small APIs, bots, staging and VPN serversOrder
VPS 2 — AMD416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,299/monthWooCommerce, Node.js/Python backends, Docker Compose stacks, CI runnersOrder
VPS 3 — AMD832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,499/monthProduction databases, high-traffic sites, multi-container appsOrder
VPS 4 — AMD1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,899/monthLarge production workloads, SaaS platforms, analytics, in-memory cachesOrder

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.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — Intel28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthBusiness websites, small apps, scheduled jobs and botsOrder
VPS 2 — Intel416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,169/monthBusiness software, mid-size databases, several sites on one serverCheck stock
VPS 3 — Intel832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,249/monthERP/CRM stacks, heavier databases, multiple production appsCheck stock
VPS 4 — Intel1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,299/monthHigh-memory workloads and consolidated production serversCheck 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

ProblemCheck
502 Bad GatewayIs the service running? systemctl status api, curl 127.0.0.1:8000/health; read journalctl -u api
Service exits immediatelyWrong WorkingDirectory or module path, missing package in the venv, unreadable .env
Client IP shows 127.0.0.1Add --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 LargeRaise client_max_body_size in Nginx
504 on long requestsRaise proxy_read_timeout, or better, move the work to a background job

Frequently Asked Questions

Is Uvicorn alone enough for production?
Uvicorn with --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?
It is an established pattern, but current Uvicorn versions include their own process manager via --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?
Start with one per vCore and measure CPU and memory under realistic load. Async endpoints handle many concurrent requests per worker, so you rarely need the (2 × cores) + 1 rule used for synchronous servers.
Where should I store secrets for a FastAPI app?
In an environment file such as /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?
Uvicorn does not know the original request used HTTPS. Send 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?
Yes, for most small and medium APIs. Bind PostgreSQL to localhost, size 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?
The app itself often uses under 100–200 MB per worker, but real usage depends on your dependencies and data. Add the database and any cache, then leave headroom. 8 GB comfortably fits an API, PostgreSQL and Redis for many projects.
How do I deploy FastAPI updates without downtime?
Run two Uvicorn instances on different ports behind an Nginx upstream and restart them one at a time, or use a blue-green layout with two release directories and switch Nginx between them.
Should I disable the /docs page in production?
If the API is internal or private, yes: create the app with docs_url=None, redoc_url=None. Public APIs can keep the docs, ideally behind authentication.
Which SkyRainCloud VPS is best for a FastAPI backend?
Start with the 2 vCore / 8 GB AMD EPYC or Intel Xeon plan for a single API with its database. Move to 4 vCores / 16 GB when you add more workers, Redis or background jobs. AMD EPYC suits highly concurrent APIs that scale across many workers.
Instant UPI • ₹649/mo
Fast KVM Cloud Provisioning