Docker Compose โ Managing Multi-Container Apps
Easily manage multi-container applications using Docker Compose with one simple command.
1. Introduction
Running a single Docker container is easy, but what if your app needs multiple services, like a web app + database? Managing multiple containers manually can be time-consuming.
๐ Docker Compose solves this by allowing you to define and run multi-container applications with a single command.
In this guide, youโll learn what Docker Compose is, how to write a docker-compose.yml
file, and how to run multiple services efficiently.
2. What is Docker Compose?
Docker Compose is a tool that allows you to:
โ
Define multiple containers in one file (docker-compose.yml
)
โ
Start all containers with one command
โ
Easily manage and scale multi-container applications
3. Why Use docker-compose.yml
?
Instead of running multiple docker run
commands, Compose lets you define all services in a single file.
Without Compose:
docker run -d --name db -e MYSQL_ROOT_PASSWORD=root mysql
docker run -d --name app --link db my-app
You have to manually start each container. ๐
With Compose (Simple & Clean!):
docker-compose up -d
๐ Everything starts with one command!
4. Writing a Basic docker-compose.yml
File
Letโs define a web app + MySQL database using Compose.
Step 1: Create a docker-compose.yml
File
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
app:
image: my-web-app
depends_on:
- db
ports:
- "8080:80"
โ
This file defines two services (app
and db
) that run together.
5. Running Multiple Services with Compose
Step 1: Start All Containers
docker-compose up -d
โ This starts the web app and database at the same time!
Step 2: Check Running Containers
docker-compose ps
Step 3: Stop All Services
docker-compose down
โ This stops and removes all containers at once.
6. Using Environment Variables in Compose
Instead of hardcoding passwords, store them in an environment file.
Step 1: Create a .env
File
MYSQL_ROOT_PASSWORD=mysecretpassword
Step 2: Modify docker-compose.yml
to Use It
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
โ This keeps your credentials secure & configurable.
7. Conclusion
Docker Compose makes managing multi-container apps super easy! Now you can:
โ
Write a docker-compose.yml
file
โ
Run multiple containers with one command
โ
Use environment variables for security
Start using Compose today to simplify your Docker workflow! ๐