How to Use Docker Compose for Multi-Container Applications: A Step-by-Step Guide
Docker Compose simplifies running multi-container apps by defining services, networks, and volumes in a single YAML file. Instead of managing each container individually, you orchestrate them together. This tutorial walks you through creating a basic web app with a frontend, backend, and database using Compose.
First, install Docker Compose (it’s included with Docker Desktop). Create a docker-compose.yml file in your project root. This file defines the services your app needs.
1. Define Services in docker-compose.yml
Each service maps to a container image. For example, a web app using Node.js and PostgreSQL:
- Specify
webservice with build context and port mapping. - Add
dbservice using the postgres image with environment variables for credentials. - Use
depends_onto ensure db starts before web.
Example snippet:
services:
web:
build: .
ports: - "3000:3000"
depends_on: - db
db:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
2. Manage Networking and Volumes
Compose automatically creates a default network for your services, so they can communicate by service name. For persistent data, define volumes:
- Add a top-level
volumes:section. - Reference it in the db service with
volumes: - postgres_data:/var/lib/postgresql/data.
3. Run and Scale Your App
Use docker-compose up -d to start all services in detached mode. To scale a service (e.g., multiple web instances):
- Run
docker-compose up --scale web=3 -d(ensure no port conflicts). - Stop everything with
docker-compose down.
With Docker Compose, you can define, share, and reproduce your entire multi-container stack effortlessly. Start with a simple YAML file and iterate from there.