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:
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.
1Configure FastAPI Container Entrypoint With Gunicorn + Uvicorn Workers
DockerfileBind 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.
DockerfiledockerfileFROM 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", "*"]2Configure Nginx Container With Docker DNS Resolver 127.0.0.11
nginx/default.confUse 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.confnginxserver { 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; } }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)bashdocker compose up -d --build docker compose ps sudo ss -tulpn | grep -E "5432|8000|80"4Schedule Automated Off-Host PostgreSQL Backups
/usr/local/bin/backup-pg.shStream 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.
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.
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.
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.
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:
Fix Docker Compose .env substitution bugs and broken bcrypt hashes. Detect unescaped $ characters, spaces around =, and .env vs env_file differences locally.
Prevent 502 Bad Gateway and Nginx startup crashes in Docker Compose using resolver 127.0.0.11 and variable proxy_pass for dynamic container restarts.
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.
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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose Laravel Octane + PostgreSQL 16 + Reverb WebSockets Guide
Generate a Docker Compose stack for Laravel Octane, PostgreSQL 16, Redis 7, and Laravel Reverb WebSockets with pg_isready healthchecks and firewall safety.
Docker Compose WordPress + MariaDB 11 + Redis + Nginx Healthcheck Guide
Build a fast Docker Compose stack for WordPress, MariaDB 11, Redis 7 object cache, and Nginx using built-in healthcheck.sh and redis-cli ping probes.
Docker Compose ASP.NET Core 8/9 + PostgreSQL 16 + Redis Cache Guide
Generate a Docker Compose config for ASP.NET Core 8/9 Web API, PostgreSQL 16 (Npgsql), and Redis distributed cache with pg_isready and redis-cli healthchecks.