Docker Compose


Docker Compose is a tool provided by Docker to define and manage multi-container applications. It uses a YAML file to describe the services, networks, and volumes required for your application. With Docker Compose, you can specify the configuration and relationships between different containers, simplifying the setup and management of complex application environments.

Key Features:

Advantages of Docker Compose


Why Not Use CLI for Multiple Containers?

Running multiple containers using the Docker CLI can become error-prone and cumbersome:


How Docker Compose Works

Docker Compose uses a YAML file (docker-compose.yml) to define the services, networks, and volumes of an application. When you run the docker-compose up command:


docker-compose.yml

version: "3.8"  # Specifies the Docker Compose file format version
services:
  web:
    image: nginx:latest  # Specifies the image for the 'web' service
    ports:
      - "8080:80"        # Maps port 80 in the container to port 8080 on the host
    volumes:
      - ./html:/usr/share/nginx/html  # Mounts local directory to the container's directory
    networks:
      - my-network        # Connects the service to 'my-network'

  app:
    build:
      context: .          # Uses the current directory to build the image
      dockerfile: Dockerfile  # Specifies the Dockerfile to use
    depends_on:
      - db               # Ensures the 'db' service starts before 'app'
    environment:
      - SPRING_PROFILES_ACTIVE=prod  # Passes environment variables to the container
    ports:
      - "8081:8081"       # Maps port 8081 on the container to port 8081 on the host
    networks:
      - my-network        # Connects the service to 'my-network'

  db:
    image: postgres:13    # Specifies the image for the 'db' service
    volumes:
      - db-data:/var/lib/postgresql/data  # Creates a named volume for persistent storage
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: password  # Passes database credentials to the container
    networks:
      - my-network        # Connects the service to 'my-network'

networks:
  my-network:
    driver: bridge         # Creates a custom bridge network

volumes:
  db-data:                 # Defines a named volume for the database

Explanation of Key Commands: