Docker Compose

💤0
Lv 10 XP
← 📦 Containers & Kubernetes · Docker

Docker Compose

Intermediate ⭐ 80 XP ⏱ 18 min #docker#compose#multi-container

Define and run multi-container applications with a single Compose file.

📖Theory

Docker Compose describes a multi-container app in one docker-compose.yml and runs it with a single command. Each service is a container; Compose also manages networks and volumes for them.

Key features: services reach each other by service name on a shared network (db:5432), depends_on orders startup, environment/.env injects config, ports publish to the host, and volumes persist data. docker compose up builds and starts everything; down cleans it up.

🌍Real-World Example
services:
  web:
    build: ./web
    ports: ["8080:80"]
    depends_on: [api]
  api:
    build: ./api
    environment:
      DATABASE_URL: postgres://db:5432/app
  db:
    image: postgres:16
    volumes: ["dbdata:/var/lib/postgresql/data"]
volumes:
  dbdata:
docker compose up --build      # start the whole stack
docker compose logs -f         # tail combined logs
docker compose down            # stop and remove
✍️Hands-On Exercise
  1. Write a Compose file with a web service that depends on an API service.
  2. Add a named volume to persist a database’s data.
  3. Explain how one service reaches another by name.
  4. Use docker compose down -v and describe what -v removes.
🧾Cheat Sheet
TaskCommand / key
Start stackdocker compose up --build
Stop + removedocker compose down
Logsdocker compose logs -f
List servicesdocker compose ps
Service-to-serviceby service name
Persist datanamed volumes:
Startup orderdepends_on
💬Common Interview Questions
How do services in Docker Compose communicate?

Over a shared Compose network, addressing each other by service name (Compose provides DNS), e.g. the api service reaches the database at db:5432.

What does depends_on do — and not do?

It controls start order so a service starts after its dependencies’ containers start. It does not wait for them to be fully ready; use health checks for that.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type