getting count of pods in a StatefulSet at runtime

1/6/2021

Is there a way to get the replica count at runtime within a pod that belongs to a StatefulSet? I have verified that the following answer https://stackoverflow.com/a/54306021/5514015 gives you the hostname of the pod, which includes the pod ordinal number, at runtime, but I would also like to know the number of replicas configured in the StatefulSet. Is this possible to determine?

-- jim
kubernetes
kubernetes-statefulset

1 Answer

1/6/2021

Unfortunately, the number of replicas is not available through the Downward API. But in a StatefulSet, as you say, it is common to need this number.

Proposed ways to get the number:

  • Implement this within your app so that they coordinate, and perhaps can find out it through ordinal identities.
  • Alternatively let your app communicate with the Kubernetes API Server using e.g. client-go, but this ties your application to Kubernetes.

For reliability, you might want to design your app in a way so that it can work (at least for some time) without the Kubernetes control-plane being available, so I would recommend to implement this without the Kubernetes API e.g. the first solution above.

-- Jonas
Source: StackOverflow