I am trying to build this app https://github.com/dwgebler/node-express-example. I want to use it as a template for making a Mongodb http express server. I tried to build the docker compose file in this repo which looks like this (modified slightly):
version: "3.8"
services:
database:
image: mongo
container_name: mongo-database
restart: always
volumes:
- "mongodata:/data/db"
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
ports:
- "8081:8081"
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: example
ME_CONFIG_MONGODB_SERVER: mongo-database
web:
image: node:16-alpine
container_name: node-server
restart: always
user: "node"
ports:
- "9443:443"
volumes:
- "./app:/var/app/"
working_dir: "/var/app"
environment:
NODE_ENV: dev
DB_USER: root
DB_PASSWORD: example
DB_NAME: mongo-database
command: "./wait.sh mongo-database 27017 'npm start'"
volumes:
mongodata:
But when I run the command docker compose up -d in the same directory as the docker-compose.yml file, I get this in the "node-server" container logs:
Mongo started
MongoError: Authentication failed.
at MessageStream.messageHandler (/var/app/node_modules/mongodb/lib/cmap/connection.js:272:20)
at MessageStream.emit (node:events:513:28)
at processIncomingData (/var/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
at MessageStream._write (/var/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
at writeOrBuffer (node:internal/streams/writable:391:12)
at _write (node:internal/streams/writable:332:10)
at MessageStream.Writable.write (node:internal/streams/writable:336:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed'
}
Why am I getting a MongoError: Authentication failed? Notice that I set
DB_USER: root
DB_PASSWORD: example
DB_NAME: mongo-database
In the web
section of the docker file which matches the MONGO_INITDB_ROOT_USERNAME
, MONGO_INITDB_ROOT_PASSWORD
, from the database section and I set DB_NAME
to mongo-database
which matches the database section name. So why isn't it authenticating?
CodePudding user response:
MONGO_INITDB_ROOT_USERNAME
and PASSWORD
create a user in the Mongo admin database. Your connection string tries to authenticate against the mongo-database
database and it can't find the user. There are messages in the Mongo logs that tell you this.
To fix it, you need to authenticate against the admin database by adding authSource=admin
to your connection string, like this
const uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@mongo-database/${process.env.DB_NAME}?retryWrites=true&writeConcern=majority&authSource=admin`;