Practical Examples of Docker Compose Usage
In this section, we'll explore some practical examples of how to use Docker Compose to manage your applications.
Example 1: Deploying a Web Application and Database
Let's say we have a web application that requires a MySQL database. We can create a docker-compose.yml
file to define and manage this setup:
version: "3"
services:
web:
image: myapp/web:latest
ports:
- "80:8080"
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- db-data:/var/lib/mysql
volumes:
db-data:
In this example, we have two services: web
and db
. The web
service runs our web application, while the db
service runs a MySQL database. The depends_on
field ensures that the web
service starts after the db
service.
To deploy this application, we can run the following commands:
docker-compose up -d
This will start the application in detached mode, allowing you to continue using the terminal.
Example 2: Scaling a Service
Suppose we want to scale our web application to handle more traffic. We can use the docker-compose scale
command to do this:
docker-compose scale web=3
This will scale the web
service to 3 replicas, allowing us to distribute the load across multiple containers.
Example 3: Deploying a Multi-tier Application
Docker Compose is particularly useful for managing multi-tier applications, such as a web application with a frontend, backend, and database. Here's an example:
version: "3"
services:
frontend:
image: myapp/frontend:latest
ports:
- "80:80"
depends_on:
- backend
backend:
image: myapp/backend:latest
environment:
DB_HOST: db
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- db-data:/var/lib/mysql
volumes:
db-data:
In this example, we have three services: frontend
, backend
, and db
. The frontend
service depends on the backend
service, and the backend
service depends on the db
service. This ensures that the application is deployed in the correct order.
By using Docker Compose, you can easily manage the deployment and scaling of your multi-tier applications, making it a powerful tool for container-based development and deployment.