Home > Enterprise >  Error initializing docker MongoDB database
Error initializing docker MongoDB database

Time:12-12

I was using the following script mounted on /docker-entrypoint-initdb.d/init-mongo.js to initialize my MongoDB 5.0DDBB on Docker:

db.auth("admin", "MyPassw0rd_123");
db = db.getSiblingDB("RecipientService");
db.createCollection('RecipientAggregate');
db.createUser({
    user: "wfuser",
    pwd: "MyPassw0rd_",
    roles: [{
            role: "readWrite",
            db: "RecipientService"
        }
    ]
});

However, it doesn't seems to work anymore with MongoDB 6.0, I'm getting the following message in DDBB logs:

MongoServerError: Authentication failed.

I can't find the right way to do it. I know the old mongo shell was deprecated in this version in favor of mongosh, maybe the syntax is not valid anymore, but I'm unable to find any advice after reading tons of docs.

Any clue about how to init a MongoDB 6.0 DDBB on Docker?

CodePudding user response:

I don't think you need to explicitly call db.auth() in your initialization script; if I remove the db.auth() line from your initialization script so that I have:

db = db.getSiblingDB("RecipientService");
db.createCollection('RecipientAggregate');
db.createUser({
    user: "wfuser",
    pwd: "MyPassw0rd_",
    roles: [{
            role: "readWrite",
            db: "RecipientService"
        }
    ]
});

And I place this in initdb.d/init-mongo.js, and then start up Mongo with the following docker-compose.yaml:

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - ./initdb.d:/docker-entrypoint-initdb.d

It all seems to work correctly: once Mongo is up, I can connect and verify that the RecipientService database has been created:

$ docker-compose exec mongo mongosh
Current Mongosh Log ID: 639692e63b75a4305eb53c47
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh 1.6.1
Using MongoDB:          6.0.3
Using Mongosh:          1.6.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test> use admin
switched to db admin
admin> db.auth('root', 'example')
{ ok: 1 }
admin> show dbs
RecipientService    8.00 KiB
admin             100.00 KiB
config             60.00 KiB
local              72.00 KiB
  • Related