backend / docker / 05_docker_compose.md

Docker Compose

3 interview angles 2 min read source

Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services, networks, and volumes, then use a single command to start everything.


1. Why Use Docker Compose?

Simplifies Multi-Container Management

  • Easily define and run applications that require multiple services (e.g., web server + database).

Consistent Environment

  • Compose ensures the same environment across development, testing, and production.

Single Command Deployment

  • Run docker-compose up to start all services defined in docker-compose.yml.

Networking Made Easy

  • Compose automatically creates a network so containers can communicate by service name.

2. Basic Structure of docker-compose.yml

version: '3.9'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/app
    depends_on:
      - db

  db:
    image: postgres:13
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: mydb

This sets up:

  • A web app built from the current directory.
  • A PostgreSQL database container with credentials.
  • Automatic startup order where the web service waits for the database.

3. Useful Commands

# Start services in the foreground
docker-compose up

# Start services in the background
docker-compose up -d

# Stop services
docker-compose down

# Build or rebuild services
docker-compose build

4. Common Use Cases

  • Local development environments.
  • Testing complex apps with multiple services.
  • CI pipelines that need a full stack setup.

Summary

Docker Compose makes it easy to manage applications with multiple containers by using a single YAML configuration file. It simplifies orchestration, networking, and lifecycle management for containerized apps.

Interview angle

  • “What is Compose for?” - defining and running a multi-container stack locally from one file: app, database, cache, with a shared network and dependency ordering. It’s a development and small-deployment tool, not an orchestrator.
  • “Does depends_on wait for the service to be ready?” - no, only for it to start. Readiness needs a healthcheck with condition: service_healthy, or retry logic in the application. Assuming ordering equals readiness is the classic race.
  • “Compose or Kubernetes?” - Compose for local development and single-host deployments; Kubernetes when you need scheduling, self-healing, rolling updates and horizontal scaling across machines. Using Kubernetes for a single-host app is usually overhead without benefit.