Docker Compose allows you to define a multi-container environment (like a Web server + Database) in a single file and start them all with one command.
1. The docker-compose.yaml File
Let's look at a typical Compose file for a web application and its database.
docker-compose.yaml:
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "8080:80"
depends_on:
- db
networks:
- app-network
db:
image: postgres:14
environment:
POSTGRES_PASSWORD: mysecretpassword
volumes:
- db-data:/var/lib/postgresql/data
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
db-data:2. Using Docker Compose
Start the Services
Action:
docker-compose up -dResult:
Creating network "my-app_app-network" with driver "bridge"
Creating volume "my-app_db-data" with default driver
Creating my-app_db_1 ... done
Creating my-app_web_1 ... doneCheck Running Services
Action:
docker-compose psResult:
Name Command State Ports
---------------------------------------------------------------------------
my-app_db_1 docker-entrypoint.sh po... Up 5432/tcp
my-app_web_1 /docker-entrypoint.sh n... Up 0.0.0.0:8080->80/tcpStop and Cleanup
Action:
docker-compose downResult:
Stopping my-app_web_1 ... done
Stopping my-app_db_1 ... done
Removing my-app_web_1 ... done
Removing my-app_db_1 ... done
Removing network my-app_app-network(Volumes are not removed by default unless you use docker-compose down -v)
3. Key Compose Features
- Project Names: Docker prefixes network/container names with your folder name (e.g.,
my-app_). - Dependency Management:
depends_onensures services start in order. - Scaling: You can scale a service using
docker-compose up --scale web=3.
Summary
- One file defines your entire application stack.
up: Starts everything.down: Stops and removes everything.- Environment variables, volumes, and networks are all defined in the YAML.