Docker Labs · Lab 3 of 6

A Multi-Service App with Docker Compose

Run a Node.js web app with PostgreSQL and Redis from one Compose file: health checks, start-up ordering, an env file, a named volume for the database, and the difference between `down` and `down -v`.

Environment
Local
Level
Intermediate
Time
About 40 min
Cost
Free

You will build

A three-service stack that starts in the right order, reports healthy, keeps its database across restarts, and is described entirely in files you can commit.

Before you start

Members can save this page, take notes and track progress. See membership · Sign in

The web app counts page views twice: in Redis (fast, but no volume) and in PostgreSQL (with a volume). Watching which counter survives a restart is the point of the lab.

Container IDs, image IDs, timestamps and sizes will differ on your machine; everything else should match.

Project structure

lab-stack/
├── compose.yaml
├── .env.example        # copy to .env (git-ignored)
├── .gitignore
└── web/
    ├── Dockerfile
    ├── .dockerignore
    ├── package.json
    ├── package-lock.json
    └── server.js

Download starter filesDownload finished project

Steps

  1. 1Write the web app

    It connects to both services, creates its table on start, and serves / and /health.

    web/server.js
    import http from "node:http";
    import pg from "pg";
    import { createClient } from "redis";
    
    const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
    const cache = createClient({ url: process.env.REDIS_URL });
    await cache.connect();
    await db.query("CREATE TABLE IF NOT EXISTS visits (id serial PRIMARY KEY, at timestamptz DEFAULT now())");
    
    const server = http.createServer(async (req, res) => {
      if (req.url === "/health") {
        res.end("ok");
        return;
      }
      const hits = await cache.incr("hits");
      await db.query("INSERT INTO visits DEFAULT VALUES");
      const { rows } = await db.query("SELECT count(*)::int AS visits FROM visits");
      res.setHeader("Content-Type", "application/json");
      res.end(JSON.stringify({ hits, visits: rows[0].visits }));
    });
    
    server.listen(3000, () => console.log("web listening on :3000"));
    
  2. 2Declare the dependencies

    Commit a lock file so every build installs exactly the same versions. Download package-lock.json with the starter files, or generate it with npm install --package-lock-only in web/.

    web/package.json
    {
      "name": "lab-stack-web",
      "version": "1.0.0",
      "private": true,
      "type": "module",
      "scripts": {
        "start": "node server.js"
      },
      "dependencies": {
        "pg": "^8.16.0",
        "redis": "^5.8.0"
      }
    }
    
  3. 3Containerise the web app

    npm ci installs exactly what the lock file says. USER node drops root before the app starts.

    web/Dockerfile
    FROM node:24-alpine
    WORKDIR /app
    COPY package.json package-lock.json ./
    RUN npm ci --omit=dev
    COPY server.js ./
    USER node
    EXPOSE 3000
    CMD ["node", "server.js"]
    
  4. 4Describe the stack

    depends_on with condition: service_healthy waits for real readiness, not just "container started". Database credentials come from .env; $$ escapes a $ so the variable is read inside the container.

    compose.yaml
    services:
      web:
        build: ./web
        ports:
          - "8080:3000"
        environment:
          DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
          REDIS_URL: redis://cache:6379
        depends_on:
          db:
            condition: service_healthy
          cache:
            condition: service_healthy
        healthcheck:
          test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
          interval: 5s
          timeout: 3s
          retries: 5
        restart: unless-stopped
    
      db:
        image: postgres:18-alpine
        env_file: .env
        volumes:
          - pgdata:/var/lib/postgresql
        healthcheck:
          test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
          interval: 5s
          timeout: 3s
          retries: 10
    
      cache:
        image: redis:8-alpine
        healthcheck:
          test: ["CMD", "redis-cli", "ping"]
          interval: 5s
          timeout: 3s
          retries: 5
    
    volumes:
      pgdata:
    
  5. 5Configure secrets outside Git

    .env holds the real values and is git-ignored; .env.example documents which values are needed.

    .env.example
    POSTGRES_USER=shop
    POSTGRES_PASSWORD=change-me
    POSTGRES_DB=shop
    
  6. 6Start it

    Create your local .env, then start everything. Compose builds the web image, starts the database and cache, waits until both are healthy, then starts the web app.

    Run
    cp .env.example .env
    docker compose up -d --build
    

    Expected output

    ...
     Container lab-stack-db-1 Started
     Container lab-stack-db-1 Waiting
     Container lab-stack-cache-1 Waiting
     Container lab-stack-cache-1 Healthy
     Container lab-stack-db-1 Healthy
     Container lab-stack-web-1 Starting
     Container lab-stack-web-1 Started
    Check:

    web starts only after db and cache report Healthy.

  7. 7Check health and use it

    Run
    docker compose ps --format 'table {{.Name}}\t{{.Service}}\t{{.Status}}\t{{.Ports}}'
    curl -s localhost:8080/
    curl -s localhost:8080/
    

    Expected output

    NAME                SERVICE   STATUS                    PORTS
    lab-stack-cache-1   cache     Up 16 seconds (healthy)   6379/tcp
    lab-stack-db-1      db        Up 16 seconds (healthy)   5432/tcp
    lab-stack-web-1     web       Up 11 seconds (healthy)   0.0.0.0:8080->3000/tcp, [::]:8080->3000/tcp
    {"hits":1,"visits":1}
    {"hits":2,"visits":2}
    Check:

    All three services show (healthy). Only web publishes a port.

    Hint

    If web shows (health: starting), wait a few seconds: health checks run every 5 seconds.

  8. 8Look inside the services

    Run
    docker compose logs web
    docker compose exec db psql -U shop -d shop -c "SELECT count(*) FROM visits;"
    docker compose exec cache redis-cli get hits
    

    Expected output

    web-1  | web listening on :3000
     count
    -------
         2
    (1 row)
    
    2
  9. 9down keeps the volume

    docker compose down removes containers and the network, but not named volumes.

    Run
    docker compose down
    docker volume ls --filter name=lab-stack
    docker compose up -d --wait
    curl -s localhost:8080/
    

    Expected output

    ...
     Network lab-stack_default Removed
    DRIVER    VOLUME NAME
    local     lab-stack_pgdata
    ...
    {"hits":1,"visits":3}
    Check:

    visits continued at 3 (PostgreSQL has a volume); hits restarted at 1 (Redis has none).

  10. 10down -v deletes the data

    -v also removes named volumes. Never run it against a stack whose data you need.

    Run
    docker compose down -v
    docker volume ls --filter name=lab-stack
    

    Expected output

    ...
     Volume lab-stack_pgdata Removed
     Network lab-stack_default Removed
    DRIVER    VOLUME NAME
  11. 11Remove the built image

    Run
    docker image rm lab-stack-web
    

In production

Compose is a good production tool for a single host (a small VPS, an internal tool) and the standard way to run a realistic stack on a developer laptop. Larger systems move the same ideas to ECS, Cloud Run or Kubernetes, and replace the database and cache containers with managed services.

What changes

In this lab In production
PostgreSQL and Redis as containers Managed services (RDS / Cloud SQL / Azure Database, ElastiCache / Memorystore) with backups, failover and patching
Password in a .env file A secrets manager (AWS Secrets Manager, GCP Secret Manager, Vault) or Docker/Compose secrets mounted as files
build: ./web on the same machine CI builds, scans and pushes the image; the server only pulls a pinned tag
One compose.yaml A base file plus per-environment overrides (compose.prod.yaml) or a separate deployment manifest
Port 8080 published directly A reverse proxy or load balancer with TLS in front; app ports stay private
restart: unless-stopped The same, plus monitoring that alerts on restart loops and failed health checks
Schema created by the app on start Versioned migrations run as a separate, one-off step before the new version starts

Health checks are a contract

A health check should answer "can this instance serve traffic?" — cheap, fast, no side effects. Platforms use it to order start-up (as depends_on did here), to restart broken instances, and to keep traffic away from instances that aren't ready.

Production checklist

  • Every service has a health check; dependants wait for service_healthy
  • No secrets in compose.yaml or in Git; .env is ignored and documented by .env.example
  • Stateful services use volumes (or managed services) with backups you have tested restoring
  • Only the entry service publishes a port, behind TLS
  • Images are built in CI with a lock file and pulled by an immutable tag
  • Database migrations are a separate deploy step
  • Resource limits are set so one service can't starve the others

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake