docker run starts one container from one long command. An application usually needs several containers, a network between them and a volume or two. Docker Compose reads all of that from one file, compose.yaml, and creates it with one command.
compose.yaml ──► docker compose up ──► network hello_default
container hello-web-1 (nginx:1.27)
container hello-cache-1 (redis:7.4)The smallest useful file
services:
web:
image: nginx:1.27
ports:
- "8080:80"
cache:
image: redis:7.4services is the only required top-level key. Each key under it is a service: a named container definition. The fields map to docker run flags:
docker run | compose.yaml |
|---|---|
--name web | the service key web: |
nginx:1.27 | image: nginx:1.27 |
-p 8080:80 | ports: ["8080:80"] |
-e KEY=value | environment: |
-v data:/data | volumes: |
--network app | networks: |
Names Compose chooses
The project name defaults to the name of the directory holding compose.yaml. Everything Compose creates carries it:
| Object | Name | In ~/hello |
|---|---|---|
| Container | <project>-<service>-<n> | hello-web-1 |
| Default network | <project>_default | hello_default |
| Named volume | <project>_<volume> | hello_data |
Every service joins <project>_default, and Docker's DNS resolves service names on it. From web, the hostname cache reaches Redis. No --network or --link is needed.
Start, list, stop
Run Compose commands in the directory that holds compose.yaml.
docker compose up -d[+] Running 3/3
✔ Network hello_default Created 0.1s
✔ Container hello-web-1 Started 0.3s
✔ Container hello-cache-1 Started 0.3s-d runs the containers in the background. Without it, Compose attaches to their logs until you press Ctrl+C.
docker compose psNAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
hello-cache-1 redis:7.4 "docker-entrypoint.s…" cache 2 seconds ago Up 2 seconds 6379/tcp
hello-web-1 nginx:1.27 "/docker-entrypoint.…" web 2 seconds ago Up 2 seconds 0.0.0.0:8080->80/tcpdocker compose ps lists only this project's containers. docker ps lists every container on the host, so it shows them too.
docker compose down[+] Running 3/3
✔ Container hello-cache-1 Removed 0.5s
✔ Container hello-web-1 Removed 0.5s
✔ Network hello_default Removed 0.1s