A service is the definition of one part of your application, such as a web server or a database. Compose creates one or more containers from that definition.
Image or build
Each service needs a source for its container. Use image to pull a ready-made image, or build to build one from a Dockerfile.
services:
web:
image: nginx:alpine
ports:
- "8080:80"
restart: unless-stopped
worker:
build: ./worker
command: ["python", "worker.py"]ports uses HOST:CONTAINER order, so port 8080 on your machine reaches port 80 in the container. command replaces the default command of the image. restart: unless-stopped restarts the container when it exits or after a daemon restart, unless you stopped it. The other policies are no (the default), always and on-failure.
Working with one service
Most commands accept a service name.
docker compose psNAME IMAGE SERVICE STATUS PORTS
demo-web-1 nginx:alpine web Up 2 minutes 0.0.0.0:8080->80/tcpColumns are shortened here and vary between releases. Other everyday commands:
docker compose logs -f web
docker compose exec web sh
docker compose stop web
docker compose run --rm web nginx -vexec runs a command inside a container that is already running. run starts a new one-off container from the service definition, and --rm removes it afterwards.
Applying changes
After you edit the file, run docker compose up -d again. Compose recreates the containers whose configuration changed and leaves the others alone. docker compose restart only restarts existing containers, so it does not apply edits to the file.
If you changed source code used by build, rebuild too:
docker compose up -d --buildYou can start several containers for one service with docker compose up -d --scale worker=3. This does not work well for a service with a fixed host port, because only one container can use that port.
Try it
Run an nginx:alpine service on port 8080. Look at it with docker compose ps, follow its logs while you request the page, and open a shell with exec. Then change the host port to 8081, run docker compose up -d, and check the PORTS column again.
Check your understanding
Compose Services
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.