Search code examples
mongodbdockerdocker-compose

MongoDb authentication failing on accessing database while using docker?


I have been trying to setup password to mongodb

My docker-compose file is

version: "3"
services:
    mongo:
        image: mongo
        ports:
            - "27017:27017"
        volumes:
            - ./data:/data/db
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=password
            - MONG_INITDB_DATABASE=example

Now after running the docker container, when I try after going inside the container

mongo mongodb://root:password@localhost:27017

It connects successfully,

but when I try

mongo mongodb://root:password@localhost:27017/example

authentication fails. MongoDB shell version v4.2.7 connecting to: mongodb://localhost:27017/example?compressors=disabled&gssapiServiceName=mongodb 2020-06-16T17:51:08.226+0000 E QUERY [js] Error: Authentication failed. : connect@src/mongo/shell/mongo.js:341:17


Solution

  • Not sure why it was not mentioned in any blog or tutorial but according to official docs, https://docs.mongodb.com/manual/reference/connection-string/#components

    /defaultauthdb  
    Optional. The authentication database to use if the connection string includes username:password@ authentication credentials but the authSource option is unspecified.
    
    If both authSource and defaultauthdb are unspecified, the client will attempt to authenticate the specified user to the admin database.
    

    So what finally worked was adding authSource, without authSource mongod tries to find the creds in /example db thus giving error, after adding authSource

    mongodb://root:password@localhost:27017/example?authSource=admin
    

    This worked and successfully added data to example db