HANDS-ON LAB Beginner

Production Docker Compose: Reverse Proxy Nginx, Healthchecks & Volume Persistence

Run backend APIs securely behind an Nginx reverse proxy, configure docker healthchecks, and persist database storage safely across updates.

Vibe DevOps·· ~7 min read
Docker EngineDocker ComposeNginxPython 3SQLite

Key Takeaways & Prerequisites

  • Never expose internal API ports directly to the host network; isolate services inside dedicated Docker bridge networks.
  • Configure Docker healthchecks on both upstream API and database containers to ensure deterministic dependency startup ordering.
  • Use depends_on with condition: service_healthy instead of naive container startup ordering to prevent upstream connection refused errors.
  • Mount static assets via read-only (:ro) volumes into Nginx to offload asset serving from the API backend directly to the web server.

Architecture & Execution Flow

  1. 01 →Isolated BridgePrivate internal communication
  2. 02 →Healthcheck Probesservice_healthy condition
  3. 03 →Static Asset OffloadRead-only volume mounting
  4. 04 →Graceful ReloadingZero-downtime Nginx reload
Table of Contents

Running a container is not the same as deploying an application. Operational edge cases emerge almost immediately: Nginx boots before the API and serves HTTP 502 Bad Gateway responses, recreating a container leads to silent data loss, or an internal API is unintentionally exposed to the entire public network interface.

This lab builds a minimal production-like stack to isolate and address all three failure modes. Nginx functions as a reverse proxy, a Python API persists a counter state to SQLite, and data lifecycle is decoupled from container lifecycles. No cloud accounts, external frameworks, or dedicated database servers are required.

Scope: This is a localized sandbox environment for architectural validation, not a turnkey production deployment. It lacks TLS termination, authentication, rate limiting, and multi-replica scalability. Do not use this stateful counter design for mission-critical workloads. These exercises require Docker Engine and the Docker Compose plugin; never assume a stack is operational simply because the Compose YAML passes syntax validation.

1. Architecture and Directory Layout

Initialize a dedicated project directory, such as compose-lab, containing four files:

compose-lab/
├── app.py
├── Dockerfile
├── compose.yaml
└── nginx.conf

Prerequisites include Docker Engine, the docker compose CLI plugin, curl, and sufficient disk space to pull base images. Verify your installation by running docker version—both client and server daemons must be reachable. Resolve any daemon socket connectivity issues before proceeding.

Compose provisions an isolated bridge network by default, enabling service discovery via embedded DNS service names. Consequently, the upstream target is api:8000, not localhost:8000: inside the Nginx container namespace, localhost resolves strictly to the loopback interface of Nginx itself.[3]

2. Minimal API Implementation Focused on Operational Visibility

Save the following implementation as app.py. GET /healthz executes an end-to-end database probe; GET /counter reads the persistent state; POST /counter increments the counter by one. State mutations are restricted to POST requests.

import json
import os
import sqlite3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
DATA_DIR.mkdir(parents=True, exist_ok=True)
DB = DATA_DIR / "counter.db"
with sqlite3.connect(DB) as db:
    db.execute("CREATE TABLE IF NOT EXISTS counter (id INTEGER PRIMARY KEY, value INTEGER NOT NULL)")
    db.execute("INSERT OR IGNORE INTO counter VALUES (1, 0)")

class Handler(BaseHTTPRequestHandler):
    def handle_request(self, increment=False):
        if self.path not in ("/healthz", "/counter"):
            self.send_json(404, {"error": "not found"})
            return
        if increment and self.path != "/counter":
            self.send_json(405, {"error": "method not allowed"})
            return
        try:
            with sqlite3.connect(DB, timeout=3) as db:
                if self.path == "/healthz":
                    db.execute("SELECT 1").fetchone()
                    result = {"status": "ok"}
                else:
                    if increment:
                        db.execute("UPDATE counter SET value = value + 1 WHERE id = 1")
                    value = db.execute("SELECT value FROM counter WHERE id = 1").fetchone()[0]
                    result = {"value": value}
            self.send_json(200, result)
        except sqlite3.Error:
            self.send_json(503, {"error": "database unavailable"})

    def send_json(self, status, value):
        payload = json.dumps(value).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        self.handle_request()

    def do_POST(self):
        self.handle_request(increment=True)

if __name__ == "__main__":
    host = os.environ.get("API_HOST", "0.0.0.0")
    port = int(os.environ.get("API_PORT", "8000"))
    ThreadingHTTPServer((host, port), Handler).serve_forever()

The service relies entirely on the Python standard library, eliminating package installation overhead during build time. While SQLite is suitable for a single-replica test environment, network-mounting a single SQLite database file across distributed compute nodes is an anti-pattern and does not constitute a High Availability (HA) architecture.

3. Hardened, Non-Root Container Image Packaging

Save the following as Dockerfile:

FROM python:3.13-slim
WORKDIR /app
COPY app.py .
RUN mkdir -p /data && chown 10001:10001 /data
USER 10001:10001
ENV PYTHONUNBUFFERED=1
EXPOSE 8000
CMD ["python", "app.py"]

The build context strictly copies necessary assets instead of using an unconstrained COPY . ., preventing .git artifacts, local backups, or sensitive credentials from leaking into image layers. The EXPOSE instruction is purely operational metadata; it does not publish or bind ports to the host interface.

Note that floating upstream image tags can drift over time. In enterprise production pipelines, scan images for vulnerabilities, pin immutable cryptographic digests (SHA-256), and establish scheduled base-image patching cadences rather than treating tags as immutable release artifacts.

4. Upstream Orchestration and Reverse Proxy Configuration

Save the following as nginx.conf:

server {
    listen 80;
    server_name _;
    location / {
        proxy_pass http://api:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_connect_timeout 3s;
        proxy_read_timeout 10s;
    }
}

Save the following orchestration spec as compose.yaml:

name: devops-compose-lab
services:
  api:
    build: .
    restart: unless-stopped
    volumes:
      - appdata:/data
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).read()"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 10s
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"
  web:
    image: nginx:1.28-alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      api:
        condition: service_healthy
    restart: unless-stopped
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"
volumes:
  appdata:

The API service intentionally omits host ports bindings. Nginx routes traffic internally across the isolated Compose bridge network. Host port 8080 is strictly bound to the loopback interface (127.0.0.1), mitigating accidental public exposure via the host's external LAN/WAN interfaces.

Standard Compose dependency modeling only blocks until a container process starts, not until the application runtime is ready to accept traffic. Defining condition: service_healthy gates ingress proxy initialization behind an active healthcheck probe.[1] Note that transitioning to an unhealthy state does not trigger an automated restart under restart: unless-stopped; the restart policy handles process exits and host reboots, not application-level health check degradation.

5. Deployment and Layer-by-Layer Verification

docker compose config --quiet
docker compose up -d --build --wait --wait-timeout 90
docker compose ps
curl --fail http://127.0.0.1:8080/healthz
curl --fail -X POST http://127.0.0.1:8080/counter
curl --fail http://127.0.0.1:8080/counter

docker compose config validates schema syntax, but does not guarantee artifact buildability. The up --wait flag will trigger a timeout if the upstream API fails to satisfy its health probe constraints. Receiving an HTTP 200 on /healthz and successfully retrieving counter values confirms the full data path: Host → Nginx → API → SQLite, verifying application layer readiness beyond mere process execution.

For triage and root cause analysis:

docker compose logs --tail=80 api web
docker compose exec web nginx -t
docker compose exec api python -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8000/healthz').status)"
  • API health probe succeeds internally, but Nginx returns HTTP 502: Inspect upstream service resolution, bridge network DNS, and port routing before attempting database troubleshooting.
  • Permission denied on /data: Verify volume mount ownership permissions against the runtime UID configured in the image. Do not remediate by running insecure chmod -R 777 overrides.
  • API returns HTTP 503: Inspect underlying database locks, storage availability, and stdout logs; a running process state does not guarantee successful request execution.

6. Upstream Fault Injection and Container Re-creation

docker compose stop api
curl -i http://127.0.0.1:8080/healthz
docker compose start api
# Wait for api to reach healthy status in `docker compose ps`, then verify recovery:
curl --fail http://127.0.0.1:8080/healthz

This simulates an intentional upstream failure mode in a controlled environment. When the backend terminates, synthetic probes must fail; do not assume all network drops result in identical, static HTTP status codes.

Capture the current counter value, then force an in-place container re-creation:

curl --fail http://127.0.0.1:8080/counter
docker compose up -d --build --force-recreate api
# The static upstream configuration in Nginx caches IPs: wait for the API to report healthy, then trigger an Nginx reload/restart.
docker compose restart web
curl --fail http://127.0.0.1:8080/counter

The newly provisioned container may receive a new bridge IP address; stale TCP sockets are not preserved across re-creations.[3] This exercise restarts Nginx post-provisioning to re-resolve upstream DNS, acknowledging downtime rather than falsely claiming zero-downtime deployment capabilities. Because the named volume exists independently of container lifecycles, state persists across destructions provided the Compose project name and volume definitions remain intact.[2]

7. Verifiable Backups: Beyond Blind File Copies

Never perform a raw file copy on an active SQLite database, as concurrent writes will lead to silent database corruption. Use SQLite's online Backup API via Python, which guarantees transactional point-in-time snapshots while serving active clients.[4]

mkdir -p backups
docker compose exec -T api python - <<'PY'
import sqlite3
with sqlite3.connect('/data/counter.db') as src:
    with sqlite3.connect('/data/backup.db') as dst:
        src.backup(dst)
PY
docker compose cp api:/data/backup.db ./backups/counter.db
python3 - <<'PY'
import sqlite3
with sqlite3.connect('file:backups/counter.db?mode=ro', uri=True) as db:
    print(db.execute('PRAGMA integrity_check').fetchone()[0])
    print(db.execute('SELECT value FROM counter WHERE id=1').fetchone()[0])
PY

The host requires Python 3 to inspect the extracted artifact. Successful validation requires integrity_check to return ok and the counter payload to match runtime state. Verifying that a backup is readable is the baseline requirement; to fully validate your Disaster Recovery (DR) posture, perform dry-run restores into an isolated staging volume and spin up a canary instance. Storing snapshots on the same underlying physical host provides zero redundancy against node-level hardware failure.

8. Controlled Teardown and Volume Hygiene

docker compose down

The standard teardown command stops and removes containers and isolated bridge networks while leaving named volumes intact. Only run docker compose down -v after confirming that test data can be discarded or that verified backups have been shipped off-host. Avoid executing destructive global cleanup commands like docker system prune --volumes on hosts running shared multi-tenant workloads.

Transitioning from Local Lab to Production

Transitioning this footprint to production environments requires adding TLS termination, zero-trust authentication, full-stack observability (metrics, structured logs, distributed tracing), automated off-site backups, scheduled restore drills, and an immutable, digest-pinned image delivery pipeline. Compose effectively models local service dependencies, but it does not provide native High Availability or hitless canary/rolling rollouts.

For production migrations, proceed to Publishing Container Images to Amazon ECR via GitHub Actions and OIDC, followed by Container Deployment to AWS ECS Fargate. Those guides leverage their own stateless architectures; do not attempt to mount this single-host SQLite persistent volume across multiple ECS Fargate tasks and expect distributed data consistency.

Sources

Cross-referenced against official technical documentation as of October 21, 2026:

[1] https://docs.docker.com/compose/how-tos/startup-order

[2] https://docs.docker.com/engine/storage/volumes

[3] https://docs.docker.com/compose/how-tos/networking

[4] https://docs.python.org/3/library/sqlite3.html

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs