How to scale services with Docker Compose?
· Category: Docker
Short answer
Use docker compose up --scale service=N to run multiple instances of a service. For more declarative scaling, use the deploy.replicas key in your Compose file.
Steps
- Ensure the service does not bind a fixed host port.
- Run
docker compose up -d --scale web=3. - Verify with
docker compose ps. - Use a load balancer or reverse proxy to distribute traffic.
Example
services:
web:
image: myapp
deploy:
replicas: 3
Or via CLI:
docker compose up -d --scale web=3
Tips
- Avoid host port mappings when scaling to prevent binding conflicts.
- Use a reverse proxy like Traefik or Nginx to route traffic to scaled instances.
deploy.replicasis primarily for Swarm but is supported in Compose for local testing.
Common issues
- Scaling a service with a fixed
portsmapping fails due to port conflicts. - Session affinity may break if the application stores state locally per container.
- Logs from scaled services are prefixed with the container name for identification.