Running one container with docker run is easy. Running three, each with its own ports and storage, means long commands that are hard to repeat. Docker Compose lets you write the whole setup in a YAML file and manage it as one unit.
The file
Compose looks in the current directory for compose.yaml (preferred) or compose.yml. The older names docker-compose.yaml and docker-compose.yml still work. Here is a small compose.yaml:
services:
web:
image: nginx:alpine
ports:
- "8080:80"The top-level services key lists the containers you want. Other top-level keys include networks and volumes. Many older files begin with a version: line. Current Compose treats it as obsolete and may warn about it, so leave it out.
YAML uses indentation to show structure. Indent with spaces, never tabs.
Check before you run
docker compose config reads your file, reports mistakes and prints the full configuration as Compose understands it. Use -q to check without printing:
docker compose config -qNo output means the file is valid.
The command is docker compose, with a space. The old standalone docker-compose tool (version 1) is no longer supported.
Start and stop
docker compose up -d[+] Running 2/2
✔ Network demo_default Created
✔ Container demo-web-1 StartedThe -d flag runs the containers in the background. The exact progress display differs between releases.
demo is the project name. By default it comes from the name of the project directory. You can set it with -p, the COMPOSE_PROJECT_NAME variable or a top-level name: key. If your file has another name, point to it with -f:
docker compose -f staging.yaml up -dWhen you are finished, docker compose down stops and removes the project's containers and default network.
Try it
Create a directory called demo, save the example as compose.yaml, and run docker compose config. Start it with docker compose up -d, open http://localhost:8080 or fetch it with curl, then run docker compose down. If the port is already taken, change 8080 to a free one.
Check your understanding
Compose Files
All 3 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.