I have been trying to setup password to mongodb
My docker-compose file is
version: "3"
services:
mongo:
image: mongo
ports:
- "27016: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,
MongoDB shell version v4.2.7 connecting to: mongodb://localhost:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("71ec853d-3a05-4367-aa9f-d0a69217fb7d") } MongoDB server version: 4.2.7 Server has startup warnings: 2020-06-16T17:43:51.837+0000 I STORAGE [initandlisten] 2020-06-16T17:43:51.837+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine 2020-06-16T17:43:51.837+0000 I STORAGE [initandlisten] ** See
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
Its the same when I try to access from outside using a node app. (Running node app too using docker-compose)
mongo mongodb://root:password@mongo:27017/example
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:27016/example?authSource=admin
This worked and successfully added data to example db
You should try connecting to mongodb://root:password@localhost:27016/example
from outside the container as you mapped the 27017 port of your docker container to your host's 27016 port.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With