Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 386
Jack Murphy Avatar asked Sep 12 '25 17:09

Jack Murphy


1 Answers

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.

like image 92
Chris Becke Avatar answered Sep 14 '25 10:09

Chris Becke