初始化Docker MongoDB数据库时出错

sqxo8psd  于 2022-12-18  发布在  Docker
关注(0)|答案(1)|浏览(264)

我正在使用/docker-entrypoint-initdb.d/init-mongo.js上装载的以下脚本初始化Docker上的MongoDB 5.0 DDBB:

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

但是,它似乎不再与MongoDB 6.0一起工作,我在DDBB日志中收到以下消息:

MongoServerError: Authentication failed.

我找不到正确的方法,我知道旧的mongo shell在这个版本中被mongosh取代了,也许语法已经不再有效了,但是我在阅读了大量的文档后找不到任何建议。
关于如何在Docker上初始化MongoDB 6.0 DDBB有什么线索吗?

rjjhvcjd

rjjhvcjd1#

我不认为您需要在初始化脚本中显式调用db.auth();如果我从初始化脚本中删除db.auth()行,那么我有:

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

我把它放在initdb.d/init-mongo.js中,然后用下面的docker-compose.yaml启动Mongo:

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

这一切似乎都工作正常:Mongo启动后,我可以连接并验证RecipientService数据库是否已创建:

$ 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

相关问题