- Published on
Managing Multi-Container Applications with Docker Compose
- Authors
- Name
- Hieu Cao
Introduction
Docker Compose is a powerful tool that simplifies the management of multi-container applications. This guide will walk you through creating and managing applications using Docker Compose, providing practical examples to get you started.
What Is Docker Compose?
Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file (docker-compose.yml
) to configure application services, making it easy to manage complex environments.
Benefits of Docker Compose
- Simplified Configuration: Manage all containers in a single YAML file.
- Reproducibility: Ensure consistent environments across development, testing, and production.
- Networking: Automatically creates networks for container communication.
- Scaling: Easily scale services up or down.
Installing Docker Compose
Docker Compose comes bundled with Docker Desktop. To install it on Linux:
sudo apt-get update
sudo apt-get install docker-compose-plugin
Verify the installation:
docker compose version
docker-compose.yml
File
Step 1: Writing a The docker-compose.yml
file defines your application services. Here's an example for a simple web application:
version: '3.8'
services:
web:
image: nginx
ports:
- '8080:80'
app:
build: ./app
volumes:
- ./app:/usr/src/app
command: npm start
Explanation:
version
: Defines the Compose file format version.services
: Lists the application services.web
: Uses the official Nginx image and maps port 8080 to 80.app
: Builds a custom application from the./app
directory and mounts it.
Step 2: Starting the Application
Run the application with:
docker compose up
This command starts all services defined in docker-compose.yml
.
Add the -d
flag to run in detached mode:
docker compose up -d
Step 3: Managing Services
Stop Services
docker compose down
Stops and removes all containers, networks, and volumes defined by the Compose file.
Restart Services
docker compose restart
Restarts all running services.
View Logs
docker compose logs
Shows logs for all services. Use -f
for real-time logs.
Scale Services
docker compose up --scale app=3
Starts three instances of the app
service.
Step 4: Adding a Database Service
Here’s an updated docker-compose.yml
with a database:
version: '3.8'
services:
web:
image: nginx
ports:
- '8080:80'
app:
build: ./app
volumes:
- ./app:/usr/src/app
command: npm start
depends_on:
- db
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
Explanation:
depends_on
: Ensures thedb
service starts beforeapp
.environment
: Sets environment variables for thedb
service.
Conclusion
Docker Compose simplifies the management of multi-container applications, enabling you to define, run, and scale services effortlessly. Whether you're setting up a simple project or a complex stack, Compose ensures a seamless and efficient workflow.