Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run multiple instances of the same service with docker compose?

I want to run 3 instances of docker image which runs on some port. I want the ports of all the 3 instances exposed to the host. I want to be able to control which of the host ports is mapped to the container.

First I tried creating 3 different services in docker-compose.yml. This worked but isn't preferable.

Second I create a single service in docker-compose.yml Then I tried to control the exposed port via enviroment variables. But when I create the second container, docker removes the first container I created.

I cannot used the scale option because it maps the exposed ports to random port on host.

myservice:
    image: myimage:latest
    container_name: service-${PORT}
    volumes:
      - ${DIR}:/data
    ports:
      - "${PORT:-8011}:8011"
      - "${ADMINPORT:-8012}:8012"
like image 433
Deepak Kar Avatar asked Mar 04 '23 11:03

Deepak Kar


1 Answers

you can set the ports range to use with scale option of compose:

ports: - "8011-8013:8011"

start it:

docker-compose up --scale myservice=3

then the containers will use port 8011, 8012 and 8013

like image 138
LinPy Avatar answered Mar 06 '23 04:03

LinPy