Docker compose examples
Writing Docker Compose YAML files involves defining the services, networks, volumes, and other components of a multi-container application using a simple and declarative syntax. Docker Compose YAML files typically follow a specific structure and include various sections to specify the desired state of the application environment. Here's an explanation of how to write Docker Compose YAML files:
- Service Definitions:
- The "services" section is where you define the individual services (containers) that make up your application.
- Each service is identified by a unique name and includes configuration options such as image, ports, volumes, environment variables, and dependencies.
- Example service definition:
services:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html
db:
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: my_database
- The "networks" and "volumes" sections allow you to define custom networks and volumes for your application.
- Networks provide communication channels between containers, while volumes provide persistent storage for container data.
- Example network and volume definitions:
networks:
my_network:
volumes:
my_volume:
- You can specify environment variables for your services using the "environment" or "env_file" options.
- Environment variables can be defined globally for all services or individually for specific services.
- Example environment variable definitions:
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: my_database
- Docker Compose allows you to override configuration options for different environments (e.g., development, testing, production) using separate YAML files or command-line arguments.
- Overrides can be applied at the service level or globally for all services.
- Example configuration override:
services:
web:
image: my_custom_image:latest
- You can scale services horizontally by specifying the desired number of container replicas using the "scale" option.
- Scaling is useful for distributing workload across multiple containers and improving application performance.
- Example service scaling:
services:
web:
image: nginx:latest
scale: 3
- Docker Compose automatically manages dependencies between services based on the order of service definitions in the YAML file.
- You can explicitly define service dependencies using the "depends_on" option or link services together using the "links" option.
- Example dependency and link definitions:
services:
web:
image: nginx:latest
db:
image: mysql:latest
depends_on:
- web
By following this structure and syntax, you can write Docker Compose YAML files to define the configuration and behavior of your multi-container applications.