Docker Compose Builder · VPS / FastAPI + Nginx

Docker Compose FastAPI + PostgreSQL + Nginx VPS Production Stack Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for VPS / FastAPI + Nginx with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (Python FastAPI)
name: fastapi_vps_prod

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    expose:
      - "8000"
    environment:
      DB_HOST: postgres
      DB_PORT: "5432"
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - app_network

  nginx:
    image: nginx:1.27-alpine
    restart: unless-stopped
    ports:
      - "127.0.0.1:80:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - api
    networks:
      - app_network

  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${DB_DATABASE:-app_db}
      POSTGRES_USER: ${DB_USERNAME:-app}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_strong}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-app} -d $${POSTGRES_DB:-app}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
Service Boot Orderbridge: app_network
postgres(healthy)apinginx

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    api will wait until postgres pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=postgres (port 5432). Inside the "api" container, 127.0.0.1/localhost points only to "api" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (pg_isready)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (VPS / FastAPI + Nginx)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

2026/11/22 21:05:11 [error] 29#29: *18 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.8, server: api.example.com, upstream: "http://172.21.0.3:8000/api/health"

Container Boot Ordering, Bridge DNS & Persistence for VPS / FastAPI + Nginx

Deploying a self-contained FastAPI + PostgreSQL 16 + Nginx stack onto a single Ubuntu or Debian VPS with Docker Compose is one of the most practical production setups for startups and indie SaaS products. Instead of installing Python virtualenvs, PostgreSQL packages, and systemd daemons directly on the host OS, every runtime stays pinned, reproducible, and rollback-safe inside containers.

The biggest security hazard on a Dockerized VPS is accidentally publishing internal ports like "5432:5432" or "8000:8000". Even if you enabled ufw default deny incoming and only allowed ports 22, 80, and 443, Docker injects DNAT rules directly into iptables BEFORE UFW rules run; leaving PostgreSQL wide open to the entire internet. Using expose: on api and postgres while publishing only Nginx on 80/443 (or 127.0.0.1 when an outer host Nginx terminates TLS) completely eliminates the UFW bypass trap.

Equally critical is pairing PostgreSQL 16's native pg_isready healthcheck with depends_on condition: service_healthy on FastAPI, AND configuring Nginx with Docker's embedded resolver 127.0.0.11 valid=30s. Together, those two patterns guarantee FastAPI never crashes waiting for PostgreSQL on boot, and Nginx never returns stale-IP 502 Bad Gateway errors when you rebuild the FastAPI container during zero-downtime releases.

Running Uvicorn/Gunicorn bound to 0.0.0.0:8000 inside the api container with --proxy-headers --forwarded-allow-ips="172.16.0.0/12" (or the exact Docker bridge subnet) ensures FastAPI recognizes real client IPs and HTTPS schemes forwarded by the Nginx container without trusting untrusted internet headers.

Finally, mount PostgreSQL storage onto a named db_data volume backed by a daily cron pg_dump script offloaded to S3 or Cloudflare R2 so a single VPS remains both fast and disaster-recoverable.

Treat your VPS docker-compose.yml and nginx/default.conf as versioned infrastructure-as-code in Git so staging and production stay 100% reproducible. Before every deployment, run docker compose config --quiet and confirm via ss -tulpn that only intended ingress ports listen publicly, keeping PostgreSQL and Uvicorn safely locked inside app_network behind Docker's embedded DNS resolver.

Step-by-Step VPS / FastAPI + Nginx Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Configure FastAPI Container Entrypoint With Gunicorn + Uvicorn Workers

    Dockerfile

    Bind Gunicorn to 0.0.0.0:8000 inside the container (never 127.0.0.1 inside Docker, or the Nginx container cannot reach it) and trust X-Forwarded-* headers from the private Docker network.

    Dockerfiledockerfile
    FROM python:3.12-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    COPY ./app ./app
    EXPOSE 8000
    CMD ["gunicorn", "app.main:app", "-k", "uvicorn.workers.UvicornWorker", "--workers", "4", "--bind", "0.0.0.0:8000", "--forwarded-allow-ips", "*"]
  2. 2Configure Nginx Container With Docker DNS Resolver 127.0.0.11

    nginx/default.conf

    Use variable-based proxy_pass with resolver 127.0.0.11 so recreating the FastAPI container never leaves Nginx pointing at a dead container IP.

    nginx/default.confnginx
    server {
        listen 80;
        server_name _;
    
        location / {
            resolver 127.0.0.11 valid=30s ipv6=off;
            set $api_upstream http://api:8000;
            proxy_pass $api_upstream;
            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;
        }
    }
  3. 3Verify No Database Ports Are Exposed Publicly on the VPS

    terminal (VPS host)

    After bringing the stack up, inspect listening sockets with ss -tulpn to confirm port 5432 and port 8000 are NOT bound to 0.0.0.0.

    terminal (VPS host)bash
    docker compose up -d --build
    docker compose ps
    sudo ss -tulpn | grep -E "5432|8000|80"
  4. 4Schedule Automated Off-Host PostgreSQL Backups

    /usr/local/bin/backup-pg.sh

    Stream compressed pg_dump backups directly from the running postgres container without pausing traffic or exposing port 5432.

    /usr/local/bin/backup-pg.shbash
    #!/usr/bin/env bash
    set -euo pipefail
    docker compose -f /srv/app/docker-compose.yml exec -T postgres \
      pg_dump -U app -d app_db | gzip > "/var/backups/app_db_$(date +%F).sql.gz"

Common VPS / FastAPI + Nginx Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

Docker Bypassing Ubuntu UFW Firewall on Published 5432 Ports

Adding ports: ["5432:5432"] allows anyone on the internet to brute-force your PostgreSQL container even when ufw status shows port 5432 denied. Always use expose: ["5432"] or 127.0.0.1:5432:5432.

Pitfall 2

Nginx Container Failing to Boot Because "api" Is Not Up Yet

If Nginx uses static proxy_pass http://api:8000; and starts while api is still waiting on Postgres healthchecks, Nginx exits with "host not found in upstream." Always use resolver 127.0.0.11 + set $api_upstream.

Pitfall 3

Unbounded Docker JSON Container Logs Filling VPS Disk Space

By default, Docker stores container stdout logs forever without rotation. Configure logging: driver: json-file with max-size: "10m" and max-file: "3" (or daemon.json defaults) so busy Nginx/FastAPI logs never exhaust VPS disk space.

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Should SSL certificates live inside the Nginx Docker container or on a host Nginx?
Both work cleanly. If you run multiple projects on one VPS, terminating Certbot SSL on a host Nginx and binding each Compose project to 127.0.0.1:PORT keeps certificate renewal centralized and avoids port 80/443 conflicts.
Why did Nginx return 502 Bad Gateway right after docker compose up -d --build api?
Rebuilding api assigns it a new internal Docker bridge IP. Without resolver 127.0.0.11 and variable proxy_pass in nginx/default.conf, Nginx keeps routing to the old container IP until restarted.
How do I inspect the exact merged YAML Docker Compose executes?
Run docker compose config. It validates indentation, interpolates every .env variable, and prints the exact canonical Compose Specification YAML before starting any containers.
Can I add Celery workers and Redis to this VPS stack later?
Yes; simply toggle Redis 7 and Include Background Queue Worker in the interactive builder above to generate the expanded stack with matching service_healthy dependencies.
Browse all 10 Compose stacks →