Docker compose
To demonstrate how to use Docker Compose to manage complex application setups, let's create a Docker Compose YAML file for a sample web application consisting of multiple services, including a web server, a database server, and a cache server. We'll define the services, networks, volumes, and other components using Docker Compose syntax.
- Create a Docker Compose YAML file:
Let's create a file named "docker-compose.yml" and define the services for our sample web application:
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "8080:80"
volumes:
- ./html:/usr/share/nginx/html
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: sample_db
volumes:
- db_data:/var/lib/mysql
cache:
image: redis:latest
volumes:
db_data:
- We've defined three services: "web", "db", and "cache".
- The "web" service uses the NGINX image, exposes port 8080 on the host, mounts a volume for static HTML files, and depends on the "db" service.
- The "db" service uses the MySQL 5.7 image, sets environment variables for root password and database name, and mounts a volume for database data storage.
- The "cache" service uses the Redis image.
- We've defined a volume named "db_data" for persisting MySQL data.
After saving the "docker-compose.yml" file, navigate to the directory containing the file in your terminal and run the following command to start the application:
docker-compose up -d
This command will create and start all the services defined in the Docker Compose file in detached mode ("-d"), allowing them to run in the background.
You can verify that the services are running correctly by checking their status and logs using the following commands:
- To view the status of all services:
docker-compose ps
docker-compose logs web
You can access the web application running on port 8080 of your host machine's IP address. Open a web browser and navigate to "http://localhost:8080" or "http://
To stop and remove the containers created by Docker Compose, use the following command:
docker-compose down
This command will stop and remove all containers, networks, and volumes defined in the Docker Compose file.
By following these steps, you can use Docker Compose to manage complex application setups with multiple interconnected services.