0

I am creating a docker container for a mongod server following the suggestions made here. My docker compose file looks as follows:

version: '3.2'

services:
  mongo:
    container_name: mongo
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"

I then build and run the container using the docker compose command:

docker-compose up --build

In the start up logs I can see the user being created:

mongo    | 2018-12-03T04:40:00.562+0000 I STORAGE  [conn2] createCollection: 
admin.system.users with generated UUID: ...
mongo    | Successfully added user: {
mongo    |      "user" : "admin",
mongo    |      "roles" : [
mongo    |              {
mongo    |                      "role" : "root",
mongo    |                      "db" : "admin"
mongo    |              }
mongo    |      ]
mongo    | }

When I try to start mongo using the auth for that user, I get an authorization error though:

mongo -u "admin" -p "admin"

2018-12-03T04:47:34.752+0000 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1608:20
@(auth):6:1
@(auth):1:2
exception: login failed

What's the correct command to connect to mongo using the above credentials?

Morne
  • 1,623
  • 2
  • 18
  • 33

2 Answers2

1

There are some pre requisites to configure authentication on mongo:

  • Place this line in mongod.conf

    security:

    authorization: enabled

After this restart your docker and follow the following steps:

  • Connect to mongo via mongo
  • use admin
  • Create a user

    {
        user: "root",
        pwd: "root",
        roles: [ { role: "userAdminAnyDatabase,readWriteAnyDatabase", db: "admin" } ]
    

    } )

  • Exit Mongo shell

    • Provide authentication database to connect to mongo:

mongo admin -u root -proot

Abhimanyu
  • 2,710
  • 2
  • 25
  • 42
  • You can refer this https://medium.com/mongoaudit/how-to-enable-authentication-on-mongodb-b9e8a924efac to get an insight of mongo authentication – Abhimanyu Dec 03 '18 at 05:45
0

In the end I was only missing the authdb flag, so the following mongo command solved my issue:

mongo -u "admin" -p "admin" --authenticationDatabase 'admin'
Morne
  • 1,623
  • 2
  • 18
  • 33