Tuan
Tuan

Reputation: 111

docker-compose create services with a loop

Is it possible to create services in a loop with docker-compose rather than typing all the services by hand? (See example below of creating 100 workers with appropriate ports)

version: '3'
services:
  redis:
    image: redis
  worker1:
    build: .
    ports:
    - "5001:5001"
  worker2:
    build: .
    ports:
    - "5002:5002"
  worker3:
    build: .
    ports:
    - "5003:5003"

  ...

  worker100:
    build: .
    ports:
    - "5100:5100"

Upvotes: 11

Views: 6708

Answers (2)

Panagiotis Drakatos
Panagiotis Drakatos

Reputation: 3214

it's very weird that no one not mentioned it. You can easily use the replicas future just like the below example to create as many replications as you want instead of the for loop it's very useful. Check doc here

version: '3'
services:
  worker:
    image: dockersamples/examplevotingapp_worker
    networks:
      - frontend
      - backend
    deploy:
      mode: replicated
      replicas: 6

You also need to use docker-compose --compatibility up to make Docker accept a deploy section without using swarm

Upvotes: 0

Chris Bailey
Chris Bailey

Reputation: 41

You can probably do it with the --scale option, so if you run docker-compose up --scale worker=100 it should do exactly what you want.

The documentation for docker-compose up references this as follows:

--scale SERVICE=NUM        Scale SERVICE to NUM instances. Overrides the
                           `scale` setting in the Compose file if present.

Upvotes: 4

Related Questions