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.
docker-compose up
).Running multiple containers using the Docker CLI can become error-prone and cumbersome:
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:
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
version
: Specifies the Docker Compose file format version.services
: Defines the containers to be managed by Compose.image
: Specifies the Docker image to use for a service.build
: Builds an image using the specified Dockerfile and context.ports
: Maps ports between the host and container.volumes
: Defines persistent storage for containers.depends_on
: Sets up service dependency order.networks
: Connects services to custom networks for communication.