Login with root credentials on Mongodb container created using Docker compose

▼魔方 西西 提交于 2019-12-11 16:59:54

问题


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?


回答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




回答2:


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'


来源:https://stackoverflow.com/questions/53587663/login-with-root-credentials-on-mongodb-container-created-using-docker-compose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!