19

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?

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

user3818491
  • 498
  • 1
  • 6
  • 16
  • I'd appreciate it the down-voter explained why? This is something I can't find anything on & is looking like docker can't do now. – user3818491 Mar 02 '20 at 12:58
  • I also faced similar problem today. In my case I want to make scaled service instances automatically load a portion of configuration. AFAIK there's no way to do it with compose file v2.0. Partial solution involves some external container which provisions configuration upon request and the service instance can use its HOSTNAME env variable (=container ID) to identify itself. Personally, I decided to just make 20 copies in docker-compose file manually giving each its config through env_file field. – Yuri Pozniak May 11 '20 at 18:41

1 Answers1

13
#!/bin/bash
# get the container IP
IP=`ifconfig eth0 | grep 'inet ' | awk '{print $2}'`

# get the service name you specified in the docker-compose.yml 
# by a reverse DNS lookup on the IP
SERVICE=`dig -x $IP +short | cut -d'_' -f2`

# the number of replicas is equal to the A records 
# associated with the service name
COUNT=`dig $SERVICE +short | wc -l`

# extract the replica number from the same PTR entry
INDEX=`dig -x $IP +short | sed 's/.*_\([0-9]*\)\..*/\1/'`

# Hello I'm container 1 of 5 
echo "Hello I'm container $INDEX of $COUNT"
Amir Razmjou
  • 512
  • 6
  • 10