<p>I am trying to run a command in mongo deployment file like below -</p>

<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo-deployment
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: mongo-pod
  template:
    metadata:
      labels:
        app: mongo-pod
    spec:
      containers:
      - name: mongo-container
        image: mongo
        ports:
        - containerPort: 27017
          name: mongo
        volumeMounts:
        - name: mongo-persistent-storage
          mountPath: /data/db
        command:
          - "bash"
          - "-c"
          - |
            mongo --eval "db.getSiblingDB('admin').createUser({user : \"$user123\", pwd  : \"$pass\", roles: [ { role: 'root', db: 'admin' } ]});"
      volumes:
      - name: mongo-persistent-storage
        persistentVolumeClaim:
          claimName: mongo-pv-claim
</code></pre>

<p>as you can see i want to given access control for multiple users in command,
but i get the following error in pods logs and pods goes into error state -</p>

<pre><code>MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
2019-09-21T15:42:39.549+0000 E  QUERY    [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2019-09-21T15:42:39.550+0000 F  -        [main] exception: connect failed
2019-09-21T15:42:39.550+0000 E  -        [main] exiting with code 1
</code></pre>

<p>any idea why i keep getting this?</p>

<p>Thanks</p>

<p>Try this:</p>

<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo-deployment
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: mongo-pod
  template:
    metadata:
      labels:
        app: mongo-pod
    spec:
      containers:
      - name: mongo-container
        image: mongo
        ports:
        - containerPort: 27017
          name: mongo
        volumeMounts:
        - name: mongo-persistent-storage
          mountPath: /data/db
        env:
        - name: MONGO_INITDB_ROOT_USERNAME
          value: user
        - name: MONGO_INITDB_ROOT_PASSWORD
          value: password
      volumes:
      - name: mongo-persistent-storage
        persistentVolumeClaim:
          claimName: mongo-pv-claim
</code></pre>

<p>It will create user <code>user</code> and password <code>password</code> for <code>admin</code> database, you can find more on <a href="https://hub.docker.com/_/mongo" rel="nofollow noreferrer">dockerhub</a>.</p>
