2

What is the recommended way to communicate between the pods belonging to the same statefulset?

In my case, kubernetes services exposes an POST API. So when someone hits this API, the pod which is getting the request should pass the request to other pods in the same statefulset as well.

Since I am using statefulset, if I have three pods, and lets say the names of the pods are Pod1, Pod2 and Pod3 and if I tie these pods to an headless service say MyService, I would be able to reach pods via Pod1.MyService, Pod2.MyService, Pod3.MyService. I can iterate through the Pod id and copy the request to all pods. But in this case, I should not pass this request to the pod which have received the request. Say in case Pod2 receives the API request, it should pass the request to Pod1 and Pod3.

Is there anyway to implement this in Go using Kubernetes client? Pointing me to any example of this kind would also help.

Jonas
  • 121,568
  • 97
  • 310
  • 388

1 Answers1

0

Let the pod be aware of its own identity by reflecting the name via a fieldRef to an environment variable.

Example of the template part of a StatefulSet manifest:

  template:
    metadata:
      labels:
        app: my-distributed-app
    spec:
      containers:
        - name: my-distributed-app
          image: my-image
          env:
            - name: REPLICA_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name

Here the pod name is available to the instance as REPLICA_NAME. You probably also need to let the instance know how many replicas there are, but I don't know a good automatic way to do that, you could set a variable for that as well, e.g.

env:
  - name: REPLICAS
    value: "3"
Jonas
  • 121,568
  • 97
  • 310
  • 388