<p>I'm writing an application to be deployed to Kubernetes where I want each pod to hold
a TCP connection to all the other pods in the replica set so any container can notify the other
containers in some use case. If a pod is added, a new connection should be created between it and all
the other pods in the replica set.</p>

<p>From a given pod, how do I open a TCP connection to all the other pods? I.e., how do I discover all
their IP addresses?</p>

<p>I have a ClusterIP Service DNS name that points to these pods by selector, and that's the mechanism
I've thought of trying to use so far. E.g., open a TCP connection to that DNS name repeatedly in a
loop, requesting a container ID over the connection each time, pausing when I've gotten say at least
three connections for each container ID. Then repeating that every minute or so to get new pods that
have been added. A keepalive could be used to remove connections to pods that have gone away.</p>

<p>Is there a better way to do it?</p>

<p>If it matters, I'm writing this application in Go.</p>

<blockquote>
  <p>E.g., open a TCP connection to that DNS name repeatedly in a loop, requesting a container ID over the connection each time, pausing when I've gotten say at least three connections for each container ID. Then repeating that every minute or so to get new pods that have been added.</p>
</blockquote>

<p>This does not sounds like a solid solution.</p>

<p>Kubernetes does <strong>not</strong> provide the functionality that you are looking for out-of-the-box.</p>

<p><strong>Detect pods</strong></p>

<p>A possible solution is to query the Kubernetes API Server, for the pods matching your <em>selector</em> (labels). Use <a href="https://github.com/kubernetes/client-go" rel="nofollow noreferrer">client-go</a> and look at e.g. <a href="https://github.com/kubernetes/client-go/blob/master/examples/in-cluster-client-configuration/main.go#L53" rel="nofollow noreferrer">example on how to list Pods</a>. You may want to <em>watch</em> for new pods, or query regularly.</p>

<p><strong>Connect to Pods</strong></p>

<p>When you know the <em>name</em> of a pod that you want to connect to, you can use <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pods" rel="nofollow noreferrer">DNS to connect to pods</a>.</p>
