<p>I have created pod with below pod definition which uses mongo official docker image. The expected result here is mongo docker creates user and pwd with env variables <code>MONGO_INITDB_ROOT_USERNAME</code>  and <code>MONGO_INITDB_ROOT_PASSWORD</code> and then it will use <code>/etc/mongo/mongod.conf</code> provided to it from volume. Instead what happens is - on first connection - I am unable to connect saying user does not exist.</p>
<p>The error disappears if I remove the <code>command</code> section. Any Idea how to resolve this issue.</p>
<p>The equivalent docker command works well, but in kubernetes auth does not work if I provide a custom configuration file.</p>
<pre><code>docker run -d -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret --name some-mongo -v /etc/mongo:/etc/mongo -v /etc/ssl/keyfile:/data/db/keyfile  mongo:4.2.23 --config /etc/mongo/mongod.conf
</code></pre>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: mongodb
  labels:
    db: mongodb
spec:
  containers:
    - name: mongodb
      image: mongo:4.2.23
      command:
           - mongod
           - &quot;--config&quot;
           - &quot;/etc/mongo/mongod.conf&quot;
      env:
       - name: MONGO_INITDB_ROOT_USERNAME
         valueFrom:
            secretKeyRef:
              name: mongosecret
              key: user

       - name: MONGO_INITDB_ROOT_PASSWORD
         valueFrom:
            secretKeyRef:
              name: mongosecret
              key: password
      volumeMounts:
          - name: mongodb-keyfile
            mountPath: /etc/ssl
          - name: mongodb-config
            mountPath: /etc/mongo
            readOnly: true
  volumes:
    - name: mongodb-keyfile
      secret:
        secretName: mongodb-keyfile
        defaultMode: 0600
    - name: mongodb-config
      configMap:
        name: mongodb-config
</code></pre>

<p>As per this <a href="https://stackoverflow.com/questions/62018646/unable-to-authenticate-mongodb-deployed-in-kubernetes">SO</a> , As you said Post removing  “command”  from deployment file and it is working Because when you set MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD ENV variables in your manifest. Mongo container will enable --auth by itself. So, you don't need to specify explicitly and check here.</p>
<p>Refer to this <a href="https://stackoverflow.com/questions/34559557/how-to-enable-authentication-on-mongodb-through-docker">SO1</a> , <a href="https://stackoverflow.com/questions/51815216/authentication-mongo-deployed-on-kubernetes">SO2</a> for more information. You can also pass the username and password as <a href="https://kubernetes.io/docs/concepts/configuration/secret/#docker-config-secrets" rel="nofollow noreferrer">secrets</a> .</p>
