Compose Service
A Compose service is a named entry under services in a Compose file that defines how to run one component of an application: image or build, ports, environment, volumes, networks, and dependencies.
One service, one component
Each key under services: describes a single component, such as payment-api, postgres, or redis. Compose runs one or more containers per service, puts all services on a shared project network, and makes each service name a DNS hostname.
A realistic service definition
services: payment-api: image: payment-api:v3.1.0 ports: - "8080:8080" environment: DB_HOST: postgres env_file: - .env depends_on: postgres: condition: service_healthy restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"] interval: 30s timeout: 5s retries: 3 postgres: image: postgres:16-alpine volumes: - postgres-data:/var/lib/postgresql/data volumes: postgres-data:Scaling a service
docker compose up -d --scale payment-api=3docker compose psRemove container_name from any service you scale, because fixed names cannot be shared by several replicas.
Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| Scaling fails | container_name is set |
Remove it |
| Service cannot reach another | Different networks | Put both on one network |
| Variables missing | Wrong key or file | docker compose config |
| Starts before dependency is ready | No health condition | Add service_healthy |
SecurityDo not hardcode secrets under
environmentin a committed file. Use an ignored.env, Composesecrets, or a secret manager.
RememberThe service name is the hostname other services use, so name it after its role.
Frequently Asked Questions
How is a Compose service different from a docker run command?
A service captures the same settings as docker run flags in version-controlled YAML, adds a DNS name on the project network, and lets Compose manage startup order, scaling, and recreation with one command for the whole stack.
Is a service the same as a container?
No. A service is the definition, and containers are its running instances. A service scaled to three replicas has three containers.
Why does my fixed container_name block scaling?
Container names must be unique, so Compose cannot create a second container with the same name. Remove container_name and let Compose generate names like project-service-1.