<p>I have the following components up and running in a kubernetes cluster</p>
<ul>
<li>A GoLang Application writing data to a mongodb statefulset replicaset in namespace <code>app1</code></li>
<li>A mongodb replicaset (1 replica) running as a statefulset in the namespace <code>ng-mongo</code></li>
</ul>
<p>What I need to do is, I need to access the mongodb database by the <code>golang</code> application for write/read opeations, so what I did was;</p>
<ol>
<li>Create a headless service for the <code>mongodb</code> in the <code>ng-mongo</code> namespace as below:</li>
</ol>
<pre><code># Source: mongo/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: mongo
  namespace: ng-mongo
  labels:
    app: mongo
spec:
  ports:
  - port: 27017
    targetPort: 27017
    name: mongo
  clusterIP: None
  selector:
    role: mongo
</code></pre>
<ol start="2">
<li>And then I deployed the <code>mongodb</code> statefulset and initialized the replicaset as below:</li>
</ol>
<pre><code>kubectl exec -it mongo-0 -n ng-mongo mongosh
rs.initiate({_id: &quot;rs0&quot;,members: [{_id: 0, host: &quot;mongo-0&quot;}]})


// gives output 
{ ok: 1 }
</code></pre>
<ol start="3">
<li>Then I created an <code>ExternalName</code> service in the <code>app1</code> namespace linking the above mongo service in step 1, look below:</li>
</ol>
<pre><code># Source: app/templates/svc.yaml
kind: Service
apiVersion: v1
metadata:
  name: app1
  namespace: app1
spec:
  type: ExternalName
  externalName: mongo.ng-mongo.svc.cluster.local
  ports:
  - port: 27017
</code></pre>
<ol start="4">
<li>And at last, I instrumented my <code>golang</code> application as follows;</li>
</ol>
<pre><code>// Connection URI 
const mongo_uri = &quot;mongodb://app1&quot; &lt;-- Here I used the app1, as the ExternalName service's name is `app1`

&lt;RETRACTED-CODE&gt;
</code></pre>
<p>And then I ran the application, and checked the logs. Here is what I found:</p>
<blockquote>
<p>2022/11/22 12:49:47 server selection error: server selection timeout, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: mongo-0:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp: lookup mongo-0 on 10.96.0.10:53: no such host }, ] }</p>
</blockquote>
<p><strong>Update: I haven't set any usernames or passwords for the mongodb</strong></p>
<p>Can someone help me why this is happening?</p>

Jananath Banuka
<p>After some digging, I was able to find the issue.</p>
<p>When specifying the <code>host</code> entry for the <code>rs.initiate({})</code>, I should provide the <code>FQDN</code> of the relevant <code>mongodb</code> instance (in my case it is the <code>mongo-0</code> pod). Therefore, my initialisation command should look like this;</p>
<pre><code>rs.initiate({_id: &quot;rs0&quot;,members: [{_id: 0, host: &quot;mongo-0.mongo.ng-mongo.svc.cluster.local:27017&quot;}]})
</code></pre>
