DEV Community

Young Gao
Young Gao

Posted on

Docker Compose for Development: The Setup Every Backend Dev Needs

Docker Compose for Development: The Setup Every Backend Dev Needs

You need PostgreSQL, Redis, and your API running locally. Installing each natively leads to version conflicts and "works on my machine" problems. Docker Compose fixes this.

Basic Setup

# docker-compose.yml
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://dev:dev@db:5432/myapp
      REDIS_URL: redis://cache:6379
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    volumes:
      - .:/app
      - /app/node_modules

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: dev
      POSTGRES_PASSWORD: dev
      POSTGRES_DB: myapp
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: pg_isready -U dev
      interval: 5s
      retries: 5

  cache:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  pgdata:
Enter fullscreen mode Exit fullscreen mode

Key Patterns

Health checks: Use depends_on with condition: service_healthy so your API waits for the database to accept connections, not just start.

Named volumes: pgdata persists database data across container restarts. Without it, you lose all data on docker compose down.

Bind mounts with exclusion: Mount your source code (.) but exclude node_modules with an anonymous volume. This prevents host/container version conflicts.

Development Hot Reload

# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["npx", "tsx", "watch", "src/index.ts"]
Enter fullscreen mode Exit fullscreen mode

Useful Commands

docker compose up -d        # Start all services
docker compose logs -f api  # Follow API logs
docker compose exec db psql -U dev myapp  # Connect to DB
docker compose down -v      # Stop and remove volumes
Enter fullscreen mode Exit fullscreen mode

Part of my Production Backend Patterns series. Follow for more practical backend engineering.


You Might Also Like

Follow me for more production-ready backend content!


If this helped you, buy me a coffee on Ko-fi!

Top comments (0)