Docker Compose Basics

Docker Compose is a tool for defining and running multi-container Docker applications using a simple, declarative YAML configuration file (docker-compose.yml).

1. Why Use Docker Compose?

Instead of typing 5 different docker run commands with long flags for your database, API, cache, and frontend every time you start work, Docker Compose starts your entire application stack with a single command: docker compose up!

2. Anatomy of `docker-compose.yml`

version: '3.8'

services:
  # Service 1: Web Frontend
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=development
      - DB_HOST=db
    volumes:
      - .:/app
      - /app/node_modules
    depends_on:
      - db

  # Service 2: PostgreSQL Database
  db:
    image: postgres:15-alpine
    restart: always
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: secretpassword
      POSTGRES_DB: myappdb
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

# Named Volumes declaration
volumes:
  pgdata:

Next Up

Learn how to build a full multi-container stack: Node.js/Python API + MongoDB/Postgres + Redis cache.

Next Lesson: Multi-Container Stack →