mongo command in kubernetes manifest

9/21/2019

I am trying to run a command in mongo deployment file like below -

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

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 -

MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&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

any idea why i keep getting this?

Thanks

-- Pavan
kubernetes
mongodb

1 Answer

9/23/2019

Try this:

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

It will create user user and password password for admin database, you can find more on dockerhub.

-- FL3SH
Source: StackOverflow