VPS Tutorials
Deploy FastAPI on a VPS: Compose, PostgreSQL, Nginx and recovery
Deploy FastAPI and PostgreSQL with Docker Compose, private ports and Nginx HTTPS. Configure non-root containers, health checks, Alembic migrations, verified backups, restoration and safe rollback.

A local fastapi dev command is only the beginning. A public API also needs supervised processes, database readiness, HTTPS, migrations that stop on failure and backups that can be restored. This guide uses a single Linux VPS: Docker Compose runs FastAPI and PostgreSQL 18, the application binds to 127.0.0.1 on the host, and host Nginx terminates HTTPS.
Use it with an existing project or as a deployment skeleton. The source article reports static configuration checks; those are historical checks, not a new deployment test performed for this edition. Resource examples are starting points, not concurrency benchmarks.
Request flow:
浏览器或客户端 -> 80/443 -> Nginx -> 127.0.0.1:8000 -> FastAPI 容器
-> PostgreSQL 容器
Neither PostgreSQL nor port 8000 needs a public host mapping. Expose only the required SSH, HTTP and HTTPS ports.
| Workload | Starting resources | Initial workers | Observe |
|---|---|---|---|
| Testing or infrequent internal API | 1–2 vCPU, 2 GB RAM, 30 GB SSD | 1 | Build memory and free disk |
| Small production API | 2 vCPU, 4 GB RAM, 50 GB SSD | 2 | Memory per process and database connections |
| CPU work or model inference | Size for the actual task | Start at 1 | CPU, model memory and timeouts |
Every worker has its own memory and pools. An application using 500 MB per process can approach 2 GB with four workers before other services. Start with 1–2 and measure real requests rather than multiplying workers automatically.
Prepare:
- Ubuntu 24.04 or another supported Linux distribution;
- Docker Engine and the Compose plugin;
- a hostname pointing to the VPS, such as
api.example.com; - cloud firewall and UFW rules allowing the necessary 22, 80 and 443 access, without exposing 8000 or 5432;
- a project with
/healthzand an initialized Alembic migration environment.
Install Docker using the VPS Docker guide if needed. All project paths below use /opt/fastapi-app. Provision files with an administrator account that can write this root-owned directory; the application container itself runs without root.
Create the deployment and private backup directories:
sudo install -d -o root -g root -m 755 /opt/fastapi-app
cd /opt/fastapi-app
sudo install -d -o root -g root -m 700 backups
Suggested layout:
/opt/fastapi-app/
├── app/
│ ├── __init__.py
│ └── main.py
├── alembic/
├── alembic.ini
├── compose.yaml
├── Dockerfile
├── .dockerignore
├── .env
└── requirements.txt
Build from an official Python image. The old tiangolo/uvicorn-gunicorn-fastapi image is deprecated. If the project uses uv, keep exact dependencies in uv.lock and export before building:
uv add "fastapi[standard]" sqlalchemy "psycopg[binary]" alembic pydantic-settings
uv export --format requirements-txt --no-dev --no-emit-project \
--output-file requirements.txt
Keep Poetry, pip-tools or your existing locking tool when already established. Commit the lockfile and test dependency updates. Confirm Python 3.14 support for the application and all required wheels before choosing the example base image.
Provide a cheap liveness endpoint independent of third-party services:
from fastapi import FastAPI
app = FastAPI()
@app.get("/healthz", include_in_schema=False)
def healthz() -> dict[str, str]:
return {"status": "ok"}
Database readiness can use a separate /readyz. Do not return credentials, connection strings or stack traces. The sample endpoint does not initialize models or migrations: configure Alembic's environment, metadata and PostgreSQL connection in the real project before running its migration service.
Save /opt/fastapi-app/Dockerfile:
FROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid app --home-dir /app app
WORKDIR /app
COPY requirements.txt ./requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
COPY --chown=app:app . .
USER app
EXPOSE 8000
CMD ["fastapi", "run", "app/main.py", "--host", "0.0.0.0", "--port", "8000"]
Use a multi-stage build for compiled dependencies so gcc, headers and package caches stay out of the runtime image. Patch the base image and record the source commit and deployed image identity.
Exclude at least these paths in .dockerignore:
.git
.env
__pycache__/
*.py[cod]
.pytest_cache/
.venv/
backups/
Excluding .env prevents copying secrets into the image; Compose supplies them at runtime.
Generate a database password once, only for a new installation:
cd /opt/fastapi-app
umask 077
db_password=$(openssl rand -base64 36 | tr -d '\n')
cat > .env.partial <<EOF
POSTGRES_DB=fastapi
POSTGRES_USER=fastapi
POSTGRES_PASSWORD=${db_password}
WEB_CONCURRENCY=2
EOF
mv .env.partial .env
chmod 600 .env
unset db_password
Keep .env out of Git and support tickets. Construct a SQLAlchemy URL from separate POSTGRES_HOST, POSTGRES_DB, POSTGRES_USER and POSTGRES_PASSWORD values, using a proper URL builder so @, : and / inside passwords are encoded correctly.
The source configuration for /opt/fastapi-app/compose.yaml is retained below. Correct its PostgreSQL volume before starting it: PostgreSQL 18 images use /var/lib/postgresql/18/docker as PGDATA and declare /var/lib/postgresql as the volume. Replace the db mount postgres_data:/var/lib/postgresql/data with postgres_data:/var/lib/postgresql. See the official image documentation. For an existing installation, locate the actual data and take a verified backup first; changing a mount is not a migration and can make an existing database appear empty.
name: fastapi-production
x-app: &app
image: fastapi-app:local
build:
context: .
env_file:
- .env
environment:
POSTGRES_HOST: db
POSTGRES_PORT: "5432"
depends_on:
db:
condition: service_healthy
networks:
- backend
services:
db:
image: postgres:18-alpine
restart: unless-stopped
stop_grace_period: 1m
env_file:
- .env
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 10
start_period: 30s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
migrate:
<<: *app
command: ["alembic", "upgrade", "head"]
restart: "no"
profiles: ["tools"]
app:
<<: *app
restart: unless-stopped
init: true
command:
- fastapi
- run
- app/main.py
- --host
- 0.0.0.0
- --port
- "8000"
- --workers
- "${WEB_CONCURRENCY:-2}"
- --proxy-headers
- --forwarded-allow-ips=*
ports:
- "127.0.0.1:8000:8000"
read_only: true
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
healthcheck:
test:
- CMD
- python
- -c
- "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3)"
interval: 15s
timeout: 5s
retries: 5
start_period: 20s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
networks:
backend:
volumes:
postgres_data:
Ordinary depends_on controls order, not readiness. service_healthy waits for pg_isready, although a successful readiness probe alone does not prove that application credentials and schema work.
--forwarded-allow-ips=* trusts forwarded information from Nginx. This is appropriate only with the loopback host binding and a trusted backend network; reassess it when exposing the port or attaching other containers. For writable uploads or caches, retain read_only and mount explicit directories with ownership, capacity limits and a backup policy.
Validate the corrected Compose file and build:
cd /opt/fastapi-app
docker compose config --quiet
docker compose build --pull app
docker compose up -d db
docker compose ps
docker compose logs --tail=100 db
Once the database is healthy, run the one-off migration:
docker compose --profile tools run --rm migrate
docker compose up -d app
docker compose ps
docker compose logs --tail=100 app
curl --fail --show-error http://127.0.0.1:8000/healthz
docker image inspect fastapi-app:local --format '{{json .RepoDigests}}'
Never run alembic upgrade head simultaneously in every worker. Stop the release on a migration failure and inspect its logs. During an update, keep the previous application running until a compatible migration succeeds.
Prefer an immutable commit tag over local or latest. A locally built image may have no RepoDigests entry; record its image ID as well as the commit, and use a registry digest when publishing it. Changing postgres:18-alpine to the next major database version does not perform a PostgreSQL upgrade.
Install the host proxy and certificate tooling:
sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw status verbose
Apply matching cloud firewall rules. Replace the example domain and save /etc/nginx/conf.d/fastapi.conf:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
listen [::]:80;
server_name api.example.com;
client_max_body_size 10m;
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_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}
Validate before reloading and request the certificate:
sudo nginx -t
sudo systemctl reload nginx
curl --fail --show-error http://api.example.com/healthz
sudo certbot --nginx -d api.example.com
sudo certbot renew --dry-run
curl --fail --show-error https://api.example.com/healthz
Certbot modifies Nginx to serve HTTPS. Check both A and AAAA records and public reachability on ports 80/443; an incorrect IPv6 record commonly breaks validation. Verify the renewal timer and the dry run.
proxy_read_timeout cannot solve long-running export, video or inference work. Put minute-long tasks in a queue with status polling rather than holding workers and connections indefinitely. Align client_max_body_size with application and CDN upload limits. See Nginx hardening for TLS, headers and rate limits.
Disabling /docs and /openapi.json reduces information exposure, but administrative APIs still need OAuth2, short-lived tokens, mTLS or another suitable authentication method, plus application authorization.
Allow actual frontend origins, required methods and headers. CORS is a browser policy; it does not block curl or server-to-server access. Protect sensitive endpoints with authentication and rate limits.
Migrations need schema privileges; the runtime usually needs only application reads and writes. The example POSTGRES_USER is an initialization administrator, not a least-privilege runtime role. Separate roles according to actual SQL before production. Keep 5432 private and use an SSH tunnel for temporary administration.
Retain mode 600 on .env. Generate independent database, mail, cloud and JWT secrets. Compose env_file does not hide them from users with root or Docker access.
Custom-format dumps support inspection with pg_restore. Save the script as /opt/fastapi-app/backup.sh:
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd /opt/fastapi-app
backup_stamp=$(date -u +%Y%m%dT%H%M%SZ)
backup_file="backups/fastapi-${backup_stamp}.dump"
partial_file="${backup_file}.partial"
test ! -e "$backup_file"
test ! -e "$partial_file"
docker compose exec -T db sh -c \
'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --format=custom --no-owner' \
> "$partial_file"
test -s "$partial_file"
docker compose exec -T db pg_restore --list < "$partial_file" > /dev/null
mv "$partial_file" "$backup_file"
sha256sum "$backup_file" > "${backup_file}.sha256"
printf 'Backup ready: %s\n' "$backup_file"
Run and inspect it:
chmod 700 /opt/fastapi-app/backup.sh
/opt/fastapi-app/backup.sh
ls -lh /opt/fastapi-app/backups
This covers the business database, not .env, Nginx configuration, uploads, role definitions or image identities. Back those up separately with encryption. Copy the completed dump and .sha256 off the VPS; one disk cannot protect against loss of the machine or account. A daily dump can lose nearly a day of changes. For tighter recovery objectives, increase frequency or design WAL archiving. See the backup and restore drill.
This drill creates a temporary database on the same PostgreSQL instance. It checks dump readability, objects and basic queries, not recovery of an entire VPS. Use an isolated instance for large databases to avoid exhausting production disk or I/O:
cd /opt/fastapi-app
backup_file='backups/fastapi-YYYYMMDDTHHMMSSZ.dump'
restore_db="restore_$(date -u +%Y%m%d%H%M%S)"
sha256sum -c "${backup_file}.sha256"
docker compose exec -T db pg_restore --list < "$backup_file" > /dev/null
docker compose exec -T db sh -c \
'createdb -U "$POSTGRES_USER" "'$restore_db'"'
docker compose exec -T db sh -c \
'pg_restore -U "$POSTGRES_USER" -d "'$restore_db'" --no-owner --exit-on-error' \
< "$backup_file"
docker compose exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "'$restore_db'" -c "\\dt"'
Replace the example filename. Check important table counts, uniqueness constraints, recent records and alembic_version. After confirming that the variable points only to the temporary database, remove it:
printf 'temporary database: %s\n' "$restore_db"
docker compose exec -T db sh -c \
'dropdb -U "$POSTGRES_USER" "'$restore_db'"'
unset restore_db
Do not use pg_restore --clean against production. A disaster recovery plan must also document DNS, certificates, uploads, environment values, roles, image version and restoration order.
Observe backup, build, migration and application start separately:
cd /opt/fastapi-app
/opt/fastapi-app/backup.sh
docker compose build --pull app
docker compose --profile tools run --rm migrate
docker compose up -d app
docker compose ps
docker compose logs --tail=100 app
curl --fail --show-error https://api.example.com/healthz
The source lists separate shell commands; do not continue manually after a failure. An automation script needs fail-fast handling. Test APIs and migrations in staging, retain the previous verified image and use backward-compatible schema changes. Reverting an image does not reverse an already applied migration; schedule destructive column removal in a later compatible release.
Back up and rehearse recovery before database patch updates. Major upgrades require a separate migration plan. Never use docker compose down -v as a troubleshooting shortcut: it removes declared data volumes.
Check each layer:
curl -v http://127.0.0.1:8000/healthz
docker compose ps
docker compose logs --tail=200 app
sudo tail -n 100 /var/log/nginx/error.log
sudo ss -lntp 'sport = :8000'
If localhost port 8000 fails, inspect the application, container and binding. If it works but the hostname fails, inspect upstream configuration and SELinux/AppArmor restrictions. Follow the 502/504 checklist.
docker compose ps
docker compose logs --tail=200 db
docker compose exec -T db sh -c \
'pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
docker compose exec -T app getent hosts db
Use db as the database host inside Compose, not 127.0.0.1. Changing .env does not update a password already initialized in the volume; change the database role explicitly and synchronize application configuration.
Check X-Forwarded-Proto, trusted proxy handling and private port exposure. A /api subpath requires matching FastAPI root_path and Nginx path behavior. A separate API subdomain is often simpler.
Inspect memory and connections:
docker stats --no-stream
journalctl -k --since '1 hour ago' | grep -i -E 'oom|killed process'
docker compose exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "select count(*) from pg_stat_activity;"'
Reduce workers under memory pressure and reduce each process's pool when connections multiply. Raising PostgreSQL max_connections alone can increase memory pressure.
- FastAPI Docker deployment: images, locks, workers and deprecated base image;
- Compose startup order:
service_healthyand health checks; - Nginx proxy module:
proxy_passand request headers; - Certbot Nginx guide: certificate issuance and renewal;
- PostgreSQL pg_dump: logical backup behavior and limits;
- Alembic tutorial: migration environment and
upgrade head.
On a test hostname, complete build, migration, health checks, backup and restoration before moving production DNS. Maintain a recoverable backup, a previous image and a migration that runs once per release.