<p>I have a working mongoDB deployment on minikube and I have managed to create a database , collection as well as a user (same as the user referenced in yaml) to do backups on that database.</p>
<p>In the yaml file for my backup cron job I need to specify a <strong>MONGODB_URI</strong> parameter and quite frankly I am at a loss as to the exact convention for getting this (where exactly do you get the value).</p>
<p>As a check I have done a <code>kubectl exec -it &lt;pod_name&gt;</code> so that I can check <em>if I am going to put the correct URI beforehand</em>. After running kubectl exec -it &lt;pod_name&gt; at the prompt that follows I tried the following :</p>
<p>1.</p>
<pre><code>mongosh mongodb://aaa:abc123@mongodb-service.default.svc.cluster.local:27017/plaformdb/?directConnection=true
</code></pre>
<p>Not working I get error :</p>
<pre><code>Current Mongosh Log ID: 62938b50880f139dad4b19c4
Connecting to:          mongodb://mongodb-service.default.svc.cluster.local:27017/platformdb/?directConnection=true&amp;appName=mongosh+1.4.2
MongoServerSelectionError: Server selection timed out after 30000 ms
</code></pre>
<ol start="2">
<li></li>
</ol>
<pre><code>mongosh mongodb://aaa:abc123@mongodb-service.svc.cluster.local:27017/platformdb?directConnection=true
</code></pre>
<p>Not working also I get error:</p>
<pre><code>MongoNetworkError: getaddrinfo ENOTFOUND mongodb-service.svc.cluster.local
</code></pre>
<ol start="3">
<li></li>
</ol>
<pre><code>mongosh mongodb://aaa:abc123@mongodb-deployment-757ffdfdr5-thuiy.mongodb-service.default.svc.cluster.local:27017/platformdb
</code></pre>
<p>Not working I get an error :</p>
<pre><code>Current Mongosh Log ID: 62938c93829ft678h88990
Connecting to:          mongodb://mongodb-deployment-757ccdd6y8-thhhh.mongodb-service.default.svc.cluster.local:27017/platformdb?directConnection=true&amp;appName=mongosh+1.4.2
MongoNetworkError: getaddrinfo ENOTFOUND mongodb-deployment-757ffdd5f5-tpzll.mongodb-service.default.svc.cluster.local
</code></pre>
<p>This however is the recommended way according to the :<a href="https://www.mongodb.com/docs/kubernetes-operator/master/tutorial/connect-from-inside-k8s/" rel="nofollow noreferrer">docs</a></p>
<p><strong>Expected:</strong></p>
<p>I should be able to log in to the database once I run that command.</p>
<p>This is how my deployment is defined :</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-deployment
  labels:
    app: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
      - name: mongodb
        image: mongo
        imagePullPolicy: &quot;IfNotPresent&quot;
        ports:
          - containerPort: 27017
        env:
            - name: MONGO_INITDB_ROOT_USERNAME
              valueFrom:
                secretKeyRef:
                  name: mongodb-secret-amended
                  key: mongo-root-username
            - name: MONGO_INITDB_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mongodb-secret-amended
                  key: mongo-root-password
        volumeMounts: 
            - mountPath: /data/db
              name: mongodb-vol
      volumes:
      - name: mongodb-vol
        persistentVolumeClaim:
          claimName: mongodb-claim
---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  selector:
    app: mongodb
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017 
</code></pre>
<p>And I need to specify MONGODB_URI in this cron job :</p>
<pre><code>---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: mongodump-backup
spec:
  schedule: &quot;0 */6 * * *&quot; #Cron job every 6 hours
  startingDeadlineSeconds: 60
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 2
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: mongodump-backup
              image: golide/backupsdemo
              imagePullPolicy: &quot;IfNotPresent&quot;
              env:
                - name: DB_NAME
                  value: &quot;microfunctions&quot;
                - name:  MONGODB_URI
                  value: mongodb://aaa:abc123@host-mongodb:27017/dbname
              volumeMounts:
                - mountPath: &quot;/mongodump&quot;
                  name: mongodump-volume
              command: ['sh', '-c',&quot;./dump.sh&quot;]
          restartPolicy: OnFailure
          volumes:
            - name: mongodump-volume
              persistentVolumeClaim:
                claimName: mongodb-backup
</code></pre>
<p><strong>UPDATE</strong>
I have tried the suggested solutions on my localhost minikube but I am still getting errors :</p>
<pre><code>mongo mongodb://aaa:abc123@mongodb-service:27017/platformdb?

authSource=admi
n
MongoDB shell version v5.0.8
connecting to: mongodb://mongodb-service:27017/platformdb?authSource=admin&amp;compressors=disabled&amp;gssapiServiceName=mongodb
Error: couldn't connect to server mongodb-service:27017, connection attempt failed: SocketException: Error connecting to mongodb-service:27017 (10.102.216.34:27017) :: caused by :: Connection timed out :
connect@src/mongo/shell/mongo.js:372:17
@(connect):2:6
exception: connect failed
exiting with code 1
</code></pre>
<p>This is giving same error even when I remove the port and use <em><strong>mongodb://aaa:abc123@mongodb-service/platformdb?authSource=admin</strong></em> . I have also tried putting quotes &quot;&quot; around the URL but getting same error.</p>
<p>As a check I tried replicating the exact same scenario on another mongodb deployment with same structure (it also has a headless service). This deploy is on a remote k8s cluster however.
This is what I found out :</p>
<ol>
<li><p>I cannot connect using <em><strong>a user other than the root user</strong></em>. I created a custom user to do the backups:</p>
<pre><code> db.createUser( {user: &quot;aaa&quot;, pwd: &quot;abc123&quot;, roles: [&quot;userAdminAnyDatabase&quot;, &quot;dbAdminAnyDatabase&quot;, &quot;readWriteAnyDatabase&quot;,&quot;backup&quot;], mechanisms:[&quot;SCRAM-SHA-1&quot;]})
</code></pre>
</li>
</ol>
<p><em><strong>NB: I have the same user created also on minikube context</strong></em>.
For this custom user I am getting an Authentication failed error everytime I try to connect :</p>
<pre><code>mongo mongodb://aaa:abc123@mongodb-headless-service:27017/TestDb?

authSource=admin
MongoDB shell version v4.4.7
connecting to: mongodb://mongodb-headless-service:27017/TestDb?authSource=admin&amp;compressors=disabled&amp;gssapiServiceName=mongodb
Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
</code></pre>
<ol start="2">
<li>I can connect using the root user but the connection attempt is intermittent. I have to exit out of the pod sometimes and re-run the command in order to connect.
<em><strong>This seems to be a bug unless Im missing something else obvious.</strong></em></li>
</ol>
<p>The screen below shows a succesful connection then on the subsequent attempt the exact same connection is failing :
<a href="https://i.stack.imgur.com/NiAFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NiAFb.png" alt="BUG" /></a>
On the 1st attempt I managed to login and run a show collections command but once I logout and try to connect I get Authentication Failed. The feature seems unstable at best.</p>

Golide
<p>Given the structure of your <code>Service</code>, you'll need to use the hostname <code>mongodb-service</code> (or <code>mongodb-service.&lt;namesapce&gt;.svc.cluster.local</code>, if you like fully qualified names). The connection URI -- as far as I can tell from <a href="https://www.mongodb.com/docs/manual/reference/connection-string/" rel="nofollow noreferrer">the documentation</a> -- would be:</p>
<pre><code>mongodb://&lt;username&gt;:&lt;password&gt;@mongodb-service/dbname?authSource=admin
</code></pre>
<p>You can also connect successfully like this:L</p>
<pre><code>mongodb://&lt;username&gt;:&lt;password&gt;@mongodb-service/
</code></pre>
<p>Because:</p>
<blockquote>
<p>If [the username and password are] specified, the client will attempt to authenticate the user to the authSource. If authSource is unspecified, the client will attempt to authenticate the user to the defaultauthdb. And if the defaultauthdb is unspecified, to the admin database.</p>
</blockquote>
<hr />
<p>I tested this using a slightly modified version of your <code>Deployment</code> (mostly, I dropped the <code>volumeMounts</code>, because I don't need persistent storage for testing, and I used <code>envFrom</code> because I find that easier in general).</p>
<p>I deployed this using kustomize (<code>kubectl apply -k .</code>) with the following <code>kustomization.yaml</code>:</p>
<pre><code>apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: mongo

commonLabels:
  app: mongodb

resources:
- deployment.yaml
- service.yaml

secretGenerator:
  - name: mongo-credentials
    envs:
      - mongo.env
</code></pre>
<p>This <code>deployment.yaml</code>:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-deployment
spec:
  replicas: 1
  template:
    spec:
      containers:
        - name: mongodb
          image: docker.io/mongo:latest
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 27017
          envFrom:
            - secretRef:
                name: mongo-credentials
</code></pre>
<p>This <code>service.yaml</code>:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017
</code></pre>
<p>And this <code>mongo.env</code>:</p>
<pre><code>MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=secret
</code></pre>
<p>Once everything was up and running, I started a client pod:</p>
<pre><code>kubectl run --image docker.io/mongo:latest mongoc -- sleep inf
</code></pre>
<p>And I was able to start a shell in that pod and connect to the database:</p>
<pre><code>$ kubectl exec -it mongoc -- bash
Current Mongosh Log ID: 6293a4bc534ff40ec737c383
Connecting to:          mongodb://&lt;credentials&gt;@mongodb-service.mongo.svc.cluster.local/?directConnection=true&amp;appName=mongosh+1.4.2
Using MongoDB:          5.0.8
Using Mongosh:          1.4.2
[...]
test&gt;
</code></pre>
