I am recently facing a weird problem regarding mongod container. I have a server machine whose IP address is 17.17.17.17. In that machine I am trying to deploy my Mongo DB, and I want it to be accessible from other machines. I have used the following command to deploy mongo db and allowed the port 27017 in the firewall.
docker run -d
--name mongo
-p 27017:27017
-v /path/to/mongo:/data/db
-e MONGO_INITDB_ROOT_USERNAME=root
-e MONGO_INITDB_ROOT_PASSWORD=password
mongo:latest
The mongo db container is running but when I try to access it from other machine either via mongosh or via a nodejs process (mongoose library) it is not accessible.
I am using the following command to access mongodb deployed in this machine from other machine:
mongosh --host 17.17.17.17. --port 27017 --username root --password password --authenticationDatabase admin
This shows authentication error everytime and in the server machine logs, it says it is not getting any user named root in the admin database.
In the nodejs , I am using the following urls to connect to the mongodb:
mongodb://root:[email protected]:27017/test?authSource=admin
mongodb://root:[email protected]:27017/admin?authSource=admin
Again, it fails to connect to the mongodb.
However, if I do not use any kind of authentication to deploy mongo db, it can be accessed both via mongoose and nodejs.
For example if I use this:
docker run -d
--name mongo
-p 27017:27017
-v /path/to/mongo:/data/db
mongo:latest
It is accessible both via mongosh and nodejs library from other machines.
Can anyone tell me what is the main problem here?
2
Answers
The image description on Docker Hub says that
MONGO_INITDB_ROOT_USERNAME
andMONGO_INITDB_ROOT_PASSWOR
have no effectSince you are using a persistent volume, I guess that you runned Mongo for the first time without authentication and then you restarted Mongo with authentication enabled but using the same volume. Just retry with a new volume.
I suggest you don’t use persistent volume like that. Instead, you should use
volumes
withdocker-compose
. Because here it is explained, you will face a lot of problems: permission,… or like @Pino’ answerYou can reference my config with docker-compose. You just create a simple
docker-compose.yml
file and rundocker-compose up -d
. Anddocker-compose down
stop and remove containers. Default, networks and volumes defined as external are never removed.After, you can interact with Mongo DB by mongosh or Mongo Compass GUI
You can read more about
volumes
to understand docker manages volume. Volumes was stored at\wsl.localhostdocker-desktop-datadatadockervolumes
in my windows machine