4

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"

Jack Murphy
  • 2,952
  • 1
  • 30
  • 49

1 Answers1

6

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.

Chris Becke
  • 34,244
  • 12
  • 79
  • 148
  • My environment variable is treating {{.Task.Slot}} it as a {{.Task.Slot}} String – Sarthak Bansal Oct 22 '22 at 21:23
  • environment variables are always strings. – Chris Becke Oct 24 '22 at 13:25
  • I've tried the above example but I was getting an error when trying to deploy using deploy --compose-file docker-compose.yaml . This was resolved by adding single quotes to template. e.g. `REPLICA: '{{.Task.Slot}}'` – alobar Aug 10 '23 at 09:09