How do you run optional services or multiple replicas of a service in Docker Compose?
Assign a service to a profile so it starts only when requested with --profile. For replicas use docker compose up --scale web=3, which requires the service not to publish a fixed host port.
Explain it simply
Profiles are optional dishes on a menu, such as the extra pizza topping that arrives only if you ask. Scaling is hiring more cooks for the same dish.
A service with profiles: [debug] is skipped in a normal up, and started only with docker compose --profile debug up. Good for admin UIs, test runners or seed jobs. For replicas, docker compose up -d --scale worker=3 starts three containers of worker. A fixed ports: "8080:80" mapping would clash because three containers cannot use one host port, so publish only the container port, or put a reverse proxy in front. Compose gives each replica a name like project-worker-1, and Docker's DNS returns all their IPs for the service name.
Compose scaling is for small setups; Kubernetes handles it properly in production.
Example
# in compose file: adminer: { image: adminer, profiles: ["debug"] }
docker compose up -d # adminer not started
docker compose --profile debug up -d # adminer started
docker compose up -d --scale worker=3
docker compose psWhat to say in the interview
"Profiles mark optional services that start only with --profile. Scaling uses --scale name=N, which needs no fixed host port because replicas would clash. For production-grade scaling I would use an orchestrator like Kubernetes."
Common mistakes
- Scaling a service that publishes a fixed host port.