Docker Tutorial · Docker Compose · Lesson 19 of 26
Docker Compose Basics
Describe a multi-container app in compose.yaml and run it with one command.
compose.yaml
Compose describes services, their images or builds, ports, environment, volumes and networks in one file:
services:
web:
build: .
ports: ["8000:8000"]
environment:
REDIS_HOST: cache
cache:
image: redis:8-alpine
docker compose up -d creates a network for the project, starts the services (each reachable by its service
name), and docker compose down removes them again. Add -v to also delete named volumes.
trap 'docker compose -p rc-demo down -v > /dev/null 2>&1' EXIT
cat > compose.yaml <<'EOF'
services:
cache:
image: redis:8-alpine
counter:
image: redis:8-alpine
command: sh -c 'sleep 1; for i in 1 2 3; do redis-cli -h cache incr hits; done'
depends_on: [cache]
EOF
docker compose -p rc-demo up -d cache > /dev/null 2>&1
docker compose -p rc-demo run --rm counter 2>/dev/null
docker compose -p rc-demo ps --format '{{.Service}}: {{.State}}'
Output
1 2 3 cache: running
Run this on your computer — see “Get Started” for setup.
See Compose overview.
Test yourself
How do Compose services reach each other?
By localhostBy service name, on the network Compose creates for the projectOnly through published portsThrough volumes
Show answer
Answer: By service name, on the network Compose creates for the project
Compose puts all services on a project network with DNS for service names.