dockerdocker-swarmdocker-containerswarm

While inside a docker swarm container, how do i determine which replica number a container is?


Given that I have a docker swarm service named Whale with a replica count of 10

When the container starts

How can the runtime program determine which replica number it is?

IE: "I am whale replica 3 of 10"


Solution

  • The easiest way would be to tell it by an environment variable and make use of the template parameters supported by docker service create.

    The compose syntax would look like this.

    services:
      replicated-service:
        environment:
          REPLICA: "{{.Task.Slot}}"
    

    If you need to use it as part of the command or entrypoint which does not support the expansion of Go Templates. You can utilize the value within a shell. (Note that healthcheck.test does not require this workaround as it defaults to CMD-SHELL)

    services:
      replicated-service:
        image: alpine/socat
        hostname: whale{{.Task.Slot}}
        entrypoint: [
          "/bin/sh", 
          "-c", 
          "exec socat tcp-listen:9092,fork TCP:whale$$REPLICA:9092"
        ]
        environment:
          REPLICA: "{{.Task.Slot}}"
        healthcheck:
          test: socat /dev/null TCP:whale$$REPLICA:9092
        deploy:
          replicas: 2
    

    Also note the $$ to escape the $ from YAML processing.