Configuring the Docker Compose Environment
To use Docker Compose, you need to create a Docker Compose configuration file, typically named docker-compose.yml
, which defines the services, networks, and volumes for your application. This file serves as the blueprint for your multi-container application.
Creating a Docker Compose File
The Docker Compose file is written in YAML format and follows a specific structure. Here's an example of a simple Docker Compose file:
version: "3"
services:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- db-data:/var/lib/mysql
volumes:
db-data:
In this example, the Docker Compose file defines two services: a web server running Nginx and a MySQL database. The web server exposes port 80 and mounts a local directory (./html
) as a volume. The MySQL service uses the mysql:5.7
image and sets the root password as an environment variable. It also mounts a named volume (db-data
) to store the database data.
Configuring Environment Variables
You can also define environment variables in your Docker Compose file to pass configuration settings to your services. For example:
version: "3"
services:
web:
image: myapp/web
environment:
- APP_ENV=production
- DB_HOST=db
- DB_PASSWORD=password
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
In this example, the web service has access to the APP_ENV
, DB_HOST
, and DB_PASSWORD
environment variables, which can be used to configure the application.
Managing Volumes and Networks
Docker Compose also allows you to define and manage volumes and networks for your application. Volumes are used to persist data, while networks are used to connect the services in your application.
Here's an example of how to define a volume and a network in your Docker Compose file:
version: "3"
services:
web:
image: myapp/web
networks:
- frontend
db:
image: mysql:5.7
volumes:
- db-data:/var/lib/mysql
networks:
- backend
volumes:
db-data:
networks:
frontend:
backend:
In this example, the web service is connected to the frontend
network, and the database service is connected to the backend
network. The database service also uses a named volume db-data
to persist its data.
By configuring the Docker Compose environment, you can easily manage the deployment and scaling of your multi-container applications.