Docker Community Forums

Share and learn in the Docker community.

How to simply scale a docker-compose service and pass the index and count to each?

I’m looking for a way to scale up a docker-compose service & saw the --scale option but could not find any method to get the index & count within each container.

Here’s a simplified compose file:

version: '2.1'
services:
  my_thing:
    restart: always
    build: .
    entrypoint: /entry.sh
    depends_on:
      - database
  database:
    restart: always
    image: postgres:12.1-alpine
    ...

If I did docker-compose up my_thing --scale 5 within the entry I’d like to be able
to see which instance I am (1 to 5) & how many instances there are in total (5 in this example).

I need this as the API ‘my_thing’ connects to needs this information to delegate events to each instance.

For example my entry could be

echo "Hello I'm container $index of $count";

& then when I run docker-compose up my_thing --scale 5 (note that I’d prefer not to hard-code the the count)

Then each container would respectively run the entry & output:

Hello I'm container 1 of 5
Hello I'm container 2 of 5
Hello I'm container 3 of 5
... and so on

If any container crashed I’d like it restarted knowing it’s index.

Is this possible or do I need to figure out some alternative or build my own tooling?

P.s.
If there’s any example of how to do something like this with docker swarm that may help too.