StackPractices
intermediate By Mathias Paulenko

Docker Compose: Multi-Service Local Development

Master Docker Compose for local development: multi-service environments, networking, volumes, profiles, overrides, hot reload, debugging, test stacks, and the helper scripts that make it all pleasant to use.

Topics: devops

Introduction

Docker Compose lets you describe an entire application — services, networks, volumes — in one YAML file and start it all with docker compose up. Instead of five terminal tabs and a README full of setup steps, a new teammate clones the repo and has a working stack in minutes.

You need Docker installed: Docker Desktop on Windows/macOS, or the engine plus the Compose plugin on Linux (Colima and OrbStack are lighter alternatives on macOS). One note before the YAML: the version: field you still see in older tutorials is ignored by Compose V2 — leave it out.

This guide covers the pieces that matter for local dev: service definitions, networking, the three kinds of volumes, override files, profiles for optional tooling, hot reload, a full multi-service stack, helper scripts, test environments, and debugging.

Basic docker-compose.yml

Start small — one app container, a database, and a cache. This is enough structure to grow on:

# docker-compose.yml
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=development
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp
      - REDIS_URL=redis://redis:6379
    volumes:
      - .:/app
      - /app/node_modules  # Anonymous volume prevents host override
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
    command: npm run dev

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: myapp
    ports:
      - "5432:5432"
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    command: redis-server --appendonly yes

volumes:
  db-data:
  redis-data:

Three details worth noticing here. depends_on with condition: service_healthy makes the app wait for Postgres to accept connections — plain depends_on only waits for the container to start, which is the classic “connection refused on first boot” bug. The anonymous /app/node_modules volume stops your host’s node_modules (or an empty dir) from shadowing the packages installed inside the image. And the named db-data volume means docker compose down won’t wipe your data — you need down -v for that.

Development Dockerfile

The app image for local dev is intentionally simple — no multi-stage build, no production hardening. Just the runtime and your package manifest:

# Dockerfile.dev
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

EXPOSE 3000

CMD ["npm", "run", "dev"]

Notice there’s no COPY . . — your source code arrives via bind mount, so edits on the host show up instantly inside the container. For the production version, see multi-stage builds and the Docker in Production guide.

Networking

Compose gives you DNS-based service discovery for free: every service on the same network is reachable by its service name. Your app connects to postgresql://db:5432 — no localhost, no container IPs, no /etc/hosts hacks.

# All services join a default network named after the project.
# Each service reaches the others by service name as hostname.

services:
  app:
    # reaches db at: postgresql://db:5432
    # reaches redis at: redis://redis:6379
    networks:
      - default

When services shouldn’t all see each other, define custom networks and pick who joins which:

services:
  frontend:
    image: nginx:alpine
    networks:
      - frontend-net

  backend:
    image: my-backend
    networks:
      - frontend-net  # Can reach frontend
      - backend-net   # Can reach db

  db:
    image: postgres:16
    networks:
      - backend-net   # Only backend can reach db

networks:
  frontend-net:
    driver: bridge
  backend-net:
    driver: bridge
    internal: true  # No external access — db is fully isolated

The internal: true flag is worth remembering: the database can’t reach the internet and nothing outside the network can reach it. For local dev this is a cheap way to approximate production segmentation.

Volumes

Three kinds of mounts do three different jobs in a dev environment:

services:
  app:
    volumes:
      # Bind mount: host directory → container (hot reload)
      - .:/app
      - ./config:/app/config:ro  # Read-only mount

      # Anonymous volume: prevents host override of a specific path
      - /app/node_modules

      # Named volume: persistent data managed by Docker
      - app-cache:/app/.cache

  db:
    volumes:
      - db-data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
      # init scripts run on first start only (when db-data is empty)

volumes:
  db-data:
    driver: local
  app-cache:

The rule of thumb: bind mounts for your source code (instant edits, hot reload), anonymous volumes to protect container-managed directories like node_modules from the bind mount, and named volumes for data that must survive docker compose down.

The init-scripts trick on the database mounts SQL or shell files into /docker-entrypoint-initdb.d — Postgres runs them alphabetically the first time it creates the data directory. To re-run them, wipe the volume first (docker compose down -v).

Override Files

Compose automatically merges docker-compose.yml with docker-compose.override.yml when both exist. The base file holds the shared shape; the override carries dev-only settings — bind mounts, debug ports, verbose logging. For other environments you pick files explicitly with -f.

# docker-compose.yml — base configuration (shared across environments)
services:
  app:
    build: .
    environment:
      - NODE_ENV=development
    ports:
      - "3000:3000"
# docker-compose.override.yml — local dev overrides (auto-loaded)
services:
  app:
    volumes:
      - .:/app
      - /app/node_modules
    command: npm run dev
    environment:
      - NODE_ENV=development
      - DEBUG=app:*
    ports:
      - "3000:3000"
      - "9229:9229"  # Node.js debugger
# docker-compose.prod.yml — production-like config (explicit -f flag)
# Usage: docker compose -f docker-compose.yml -f docker-compose.prod.yml up
services:
  app:
    volumes: []  # Remove bind mounts
    command: node server.js
    environment:
      - NODE_ENV=production
    ports:
      - "80:3000"
    restart: always
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: '1.0'
          memory: 512M

Two practical rules. First, auto-merge is a dev convenience — anything sensitive like production settings should require the explicit -f so nobody boots prod config by accident. Second, volumes: [] in the prod file clears inherited bind mounts, which is the most common “why does prod behave like dev” surprise. The override environments recipe goes deeper on merge semantics and covers the fully-separate-stacks strategy for dev and prod.

Profiles

Profiles mark services as optional. Everything without a profile starts by default; profiled services only boot when you ask for them — perfect for tooling you want available but not always running:

# docker compose --profile debug up
# docker compose --profile monitoring up

services:
  app:
    # No profile — always starts
    build: .

  db:
    # No profile — always starts
    image: postgres:16

  mailhog:
    # Only starts with --profile debug
    image: mailhog/mailhog
    profiles: [debug]
    ports:
      - "1025:1025"
      - "8025:8025"

  prometheus:
    image: prom/prometheus
    profiles: [monitoring]
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml

  grafana:
    image: grafana/grafana
    profiles: [monitoring]
    ports:
      - "3001:3000"

A mail catcher under debug, a metrics stack under monitoring, a slow integration suite under test — the base docker compose up stays fast while everything stays one flag away.

Hot Reload Setup

Hot reload is the whole point of the bind-mount setup: edit on the host, the process inside the container restarts. Each stack needs its own watcher.

Node.js with nodemon

services:
  app:
    build: .
    volumes:
      - .:/app
      - /app/node_modules
    command: npx nodemon --watch src --ext ts,json --exec "node --import tsx src/index.ts"
    environment:
      - NODE_ENV=development
    ports:
      - "3000:3000"

Python with uvicorn auto-reload

services:
  api:
    build: .
    volumes:
      - .:/app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/src
    environment:
      - PYTHONUNBUFFERED=1
    ports:
      - "8000:8000"

Java with Spring Boot DevTools

services:
  app:
    build: .
    volumes:
      - ./target:/app/target
    command: java -jar -Dspring.devtools.restart.enabled=true target/app.jar
    environment:
      - SPRING_DEVTOOLS_RESTART_TRIGGER_FILE=/app/target/.trigger
    ports:
      - "8080:8080"

One caveat on Windows and macOS: bind mounts go through a filesystem sharing layer, so watching thousands of files can lag. If your watcher feels slow, enable delegated or cached consistency on the mount (- .:/app:cached) or switch the watcher to polling.

Multi-Service Full Stack Application

Here’s the shape most real projects end up with — frontend, backend, worker, database, cache, and a reverse proxy in front:

Docker Compose local stack — nginx routes to frontend and backend; backend and worker reach db and redis through the backend network
services:
  frontend:
    build: ./frontend
    volumes:
      - ./frontend:/app
      - /app/node_modules
    command: npm run dev -- --host 0.0.0.0
    ports:
      - "5173:5173"
    environment:
      - VITE_API_URL=http://localhost:3000/api
    depends_on:
      - backend

  backend:
    build: ./backend
    volumes:
      - ./backend:/app
      - /app/node_modules
    command: npm run dev
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp
      - REDIS_URL=redis://redis:6379
      - JWT_SECRET=dev-secret
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

  worker:
    build: ./backend
    volumes:
      - ./backend:/app
      - /app/node_modules
    command: npm run worker
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp
      - REDIS_URL=redis://redis:6379
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: myapp
    ports:
      - "5432:5432"
    volumes:
      - db-data:/var/lib/postgresql/data
      - ./db-init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data

  nginx:
    image: nginx:alpine
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    ports:
      - "80:80"
    depends_on:
      - frontend
      - backend

volumes:
  db-data:
  redis-data:

Two things in this file earn their keep. The worker service reuses the backend’s build context and source with a different command — no separate image to maintain. And JWT_SECRET=dev-secret is fine for local dev but flags the pattern: real secrets belong in a .env file that stays out of git (see Docker secrets management).

Workflow Helpers

A couple of small scripts turn Compose from “list of commands to remember” into “clone and run”.

Health-checked startup script

depends_on handles ordering inside Compose, but a first-boot script that waits, migrates, and seeds saves every teammate a page of instructions:

#!/bin/bash
# start-dev.sh

docker compose up --build -d

echo "Waiting for services..."
until docker compose exec -T db pg_isready -U postgres >/dev/null 2>&1; do
  sleep 1
done

echo "Running migrations..."
docker compose exec api npx prisma migrate dev

echo "Seeding data..."
docker compose exec api npm run seed

echo "Ready! API: http://localhost:3000"

Seed data script

#!/bin/bash
# seed-dev.sh — reset and repopulate the dev database

set -e

echo "Resetting database..."
docker compose exec -T db psql -U postgres -d app \
  -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"

echo "Running migrations..."
docker compose exec -T api npx prisma migrate dev --reset --force

echo "Seeding users..."
docker compose exec -T db psql -U postgres -d app <<'SQL'
INSERT INTO users (email, name, created_at) VALUES
  ('alice@example.com', 'Alice', NOW()),
  ('bob@example.com', 'Bob', NOW()),
  ('admin@example.com', 'Admin', NOW());
SQL

Makefile

Tab-completion for your whole team, and CI can call the same targets:

# Makefile
.PHONY: up down restart logs ps clean rebuild seed test

up:
	docker compose up -d

down:
	docker compose down

restart:
	docker compose restart

logs:
	docker compose logs -f --tail=100

clean:
	docker compose down -v --remove-orphans

rebuild:
	docker compose up -d --build --force-recreate

seed:
	./seed-dev.sh

test:
	docker compose -f docker-compose.yml -f docker-compose.test.yml up \
	  --abort-on-container-exit --exit-code-from api

shell:
	docker compose exec api /bin/sh

db-shell:
	docker compose exec db psql -U postgres -d app

Test Environments

Compose works for CI too — a dedicated override file swaps in test settings, and --abort-on-container-exit --exit-code-from makes the exit status of your test container drive the whole up command:

# docker-compose.test.yml
services:
  api:
    build:
      dockerfile: Dockerfile.test
    environment:
      - NODE_ENV=test
      - DATABASE_URL=postgres://postgres:secret@db:5432/app_test
    command: ["npm", "run", "test:integration"]

  db:
    environment:
      POSTGRES_DB: app_test

  # Keep nginx and worker out of the test run
  nginx:
    profiles:
      - never
  worker:
    profiles:
      - never
# Run integration tests — exits with the test container's code
docker compose -f docker-compose.yml -f docker-compose.test.yml up \
  --abort-on-container-exit --exit-code-from api

Setting profiles: [never] is a neat trick: the service exists in the file but only starts under a profile nobody passes — no need to maintain a separate “test” compose file that duplicates everything.

Resource Limits

On a shared dev machine, an unbounded worker can quietly eat half your RAM. deploy.resources applies limits even outside Swarm:

# docker-compose.yml — add to each service that needs a ceiling
services:
  api:
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 256M

  db:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 1G

Give the database more headroom than the app — Postgres slowing down makes the whole stack feel broken while everything reports healthy.

Debugging

Node.js debugging

services:
  app:
    command: node --inspect=0.0.0.0:9229 src/index.js
    ports:
      - "3000:3000"
      - "9229:9229"  # Debugger port — attach from your IDE

Python debugging with debugpy

services:
  api:
    command: python -m debugpy --listen 0.0.0.0:5678 --wait-for-client src/main.py
    ports:
      - "8000:8000"
      - "5678:5678"

Java remote debugging

services:
  app:
    command: java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar
    ports:
      - "8080:8080"
      - "5005:5005"

The pattern is the same everywhere: start the debugger listening on 0.0.0.0 (not localhost — localhost inside the container won’t see connections coming through the port mapping), publish the debug port, then attach VS Code or your IDE to it.

Useful Commands

# Start all services (foreground)
docker compose up

# Start in background (detached)
docker compose up -d

# Start specific services only
docker compose up app db

# Start with a profile
docker compose --profile monitoring up

# Rebuild images and start
docker compose up --build

# Follow logs (all services / one service / last N lines)
docker compose logs -f
docker compose logs -f app
docker compose logs --tail=100 app

# Stop and remove containers
docker compose down

# Also remove volumes (wipes data) / and images
docker compose down -v
docker compose down -v --rmi all

# Run a one-off command in a running container
docker compose exec app npm run migrate

# Run a one-off command in a fresh container
docker compose run --rm app npm run test

# Restart / inspect a single service
docker compose restart app
docker compose ps
docker compose stats

# Look inside a network
docker network inspect myapp_backend

The two you’ll run daily: docker compose logs -f app to watch one service, and docker compose exec app <cmd> for migrations, REPLs, or a shell.

Performance Tips

  1. Enable BuildKit — it’s the default on modern Docker, but on older installs put it in .env for meaningfully faster builds:
DOCKER_BUILDKIT=1
COMPOSE_DOCKER_CLI_BUILD=1
  1. Cache node_modules in a named volume — survives rebuilds so npm install runs once:
services:
  api:
    volumes:
      - ./api:/app
      - api_node_modules:/app/node_modules

volumes:
  api_node_modules:
  1. Use tmpfs for scratch space — faster than any disk-backed volume, and it vanishes cleanly with the container:
services:
  api:
    tmpfs:
      - /tmp
      - /app/cache

Best Practices

  • For the production side of the same coin, see Complete Guide to Docker in Production.
  • Use bind mounts for source code in dev — that’s what makes hot reload work without rebuilds.
  • Use anonymous volumes for node_modules, .venv — prevents the host mount from shadowing container packages.
  • Use depends_on with condition: service_healthy — the app waits for the DB to accept connections, not just to exist.
  • Use override files for environment-specific config — base file plus auto-merged override for dev.
  • Use profiles for optional services — monitoring, mail catchers, debug tooling.
  • Set restart: unless-stopped on dev databases — they survive a machine reboot.
  • Keep a .dockerignore next to every Dockerfile — node_modules, .git, and build artifacts out of the build context.
  • Pin image versions — postgres:16-alpine, never postgres:latest.
  • Put healthchecks on databases — readiness beats “container started”.
  • Keep credentials in .env and out of git; inject with env_file or Compose’s secret support.
  • Commit docker-compose.yml — reproducible environments for the whole team.

Common Mistakes

  • No anonymous volume for node_modules: the bind mount overwrites container-installed packages with the host’s (or an empty) directory — usually surfaced as “module not found” on first up.
  • depends_on without a healthcheck: the app starts before the DB is ready and crashes on boot.
  • No .dockerignore: the build context ships node_modules and .git to the daemon — slow builds, bloated images.
  • latest tags: images drift between pulls. Pin versions.
  • No named volume for the database: docker compose down is fine, but down -v by a teammate wipes everything. Named volumes at least make the wipe explicit.
  • Exposing every port to the host: only publish what you open in a browser. Internal services already reach each other over the Docker network — publishing 5432 just invites conflicts when two projects both want it.
  • Leaving version: "3.9" in the file: harmless but outdated — Compose V2 ignores it and prints a warning.

See Also

Frequently Asked Questions

What is the difference between bind mounts and named volumes?

Bind mounts map a host directory into the container — great for hot reload, but the container sees exactly what your host has, including an empty or wrong node_modules. Named volumes live under Docker's control and persist independently. Bind mounts for code, named volumes for data.

How does docker-compose.override.yml work?

Compose auto-merges docker-compose.yml with docker-compose.override.yml when both sit in the same directory — override values win, lists concatenate. For other environments, name the files and pass them explicitly: docker compose -f docker-compose.yml -f docker-compose.prod.yml up.

What are Docker Compose profiles for?

Grouping optional services. Services without a profile always start; profiled ones only run with --profile <name>. Ideal for monitoring stacks, mail catchers, or debug tools you want in the same file but not always running.

When should I use Compose instead of Kubernetes?

Compose is single-host: one machine, one YAML, one up. That's exactly what local dev needs. Kubernetes orchestrates containers across a cluster of machines — the right tool for production, overkill for running Postgres next to your laptop's CPU. See the Kubernetes basics guide for when to make the jump.

How do I reset my local environment?

docker compose down -v removes containers and volumes — a clean slate including the database. Keep your data by omitting -v; rebuild everything with docker compose build --no-cache && docker compose up.

How do I run migrations and seeds?

docker compose exec app npm run migrate runs inside the already-running container; docker compose run --rm app npm run migrate spins a fresh one-off container that gets cleaned up on exit. The startup and seed scripts in Workflow Helpers wrap this so nobody has to remember the order.