Defining Multi-Container Applications with Compose
Compose File Structure
The Compose file is written in YAML format and typically named docker-compose.yml
. It consists of several key elements:
- Version: Specifies the version of the Compose file format.
- Services: Defines the different services (containers) that make up your application.
- Networks: Configures the networks that your services will use to communicate with each other.
- Volumes: Defines the volumes that your services will use to persist data.
Here's an example of a Compose file that defines a web service and a database service:
version: "3"
services:
web:
image: nginx:latest
ports:
- "8080:80"
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- db-data:/var/lib/mysql
volumes:
db-data:
Defining Services
Each service in the Compose file represents a Docker container. You can specify various configuration options for each service, such as the Docker image to use, environment variables, ports, volumes, and dependencies on other services.
For example, the web
service in the previous example uses the nginx:latest
image, exposes port 80 on the container to port 8080 on the host, and depends on the db
service.
Networking and Volumes
Compose automatically creates a default network for your application, allowing your services to communicate with each other. You can also define custom networks and volumes to control the connectivity and data persistence of your application.
In the example, the db
service uses a named volume db-data
to persist its data, ensuring that the data is not lost when the container is stopped or removed.
Scaling and Deployment
Once you've defined your Compose file, you can use the docker-compose
command-line tool to manage your application. For example, you can use docker-compose up
to start your application, docker-compose scale web=3
to scale the web service to three instances, and docker-compose down
to stop and remove your application.
In the next section, we'll explore how to deploy and manage your Compose applications in more detail.