Skip to main content

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.

flowchart LR A[payment-api] -->|DB_HOST| B[(postgres)] A -->|REDIS_HOST| C[(redis)] B --- V[postgres-data volume] classDef app fill:#DBEAFE,color:#1E293B classDef data fill:#D1FAE5,color:#1E293B class A app class B,C,V data

A realistic service definition

YAML
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

Bash
docker compose up -d --scale payment-api=3
docker compose ps

Remove 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
Security

Do not hardcode secrets under environment in a committed file. Use an ignored .env, Compose secrets, or a secret manager.

Remember

The 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.

Found a mistake, an outdated step or a broken link?