Defining Multiple Services
Compose lets several services share a network so they can reach each other by service name, wiring up a full application.
The real power of Compose appears when you define several services that work together. Compose puts them on a shared network automatically, so they reach each other by service name.
A typical web app stack
Consider an API that talks to a Postgres database. In the API's configuration, the database host is simply db — the name of the database service.
Building your own image
Instead of a prebuilt image, a service can use build: to build from a local Dockerfile, so your source code becomes part of the stack.
Example
services:
api:
build: .
ports:
- "3000:3000"
environment:
DATABASE_URL: postgres://postgres:secret@db:5432/app
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
POSTGRES_DB: app
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:When to use it
- A full-stack team defines api, web, and db services in one compose file so the frontend, backend, and database all start together.
- A developer overrides only the api service with docker compose up api to restart it after a code change without touching the database.
- A microservices team scales up a worker service to three instances with docker compose up --scale worker=3.
More examples
Three-service application stack
Defines three services that share the default Compose network and can reach each other by service name.
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: secret
api:
build: ./api
ports:
- "3000:3000"
environment:
DATABASE_URL: postgres://postgres:secret@db:5432/app
web:
build: ./web
ports:
- "8080:80"Start only one service
Restarts a single service without disturbing the others, useful when iterating on one component.
# Rebuild and restart only the api service
docker compose up -d --build api
# Check its logs immediately
docker compose logs -f apiScale a service horizontally
Runs three replicas of the worker service side by side, each with its own container.
docker compose up -d --scale worker=3
docker compose ps
Discussion