我正在为MongoDB容器扩展docker-compose.yml。我想添加一些初始数据。
docker-compose.yml
看起来像这样:
version: '3.1'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: root
volumes:
- mongo-data:/data/db:cached
- ./fixtures/mongo_import.js:/docker-entrypoint-initdb.d/mongo_import.js
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: root
ME_CONFIG_BASICAUTH_USERNAME: root
ME_CONFIG_BASICAUTH_PASSWORD: root
volumes:
mongo-data:
driver: local
当我运行此脚本时,在mongo容器日志中出现错误,提示用户root不存在。
所以我创建了一个mongo_import.js脚本,它看起来像这样:
db.auth('root', 'root')
db = db.getSiblingDB('licensing')
db.createUser({
user: 'root',
pwd: 'root',
roles: [
{
role: 'root',
db: 'admin',
},
],
});
它不起作用。当我转到该容器中的shell并运行mongo mongo_import.js
时,我得到:
# mongo mongo_import.js
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b148691b-d585-48e9-9cdd-1d58ad4a4294") }
MongoDB server version: 4.0.10
Error: Authentication failed.
2019-05-31T10:21:36.788+0000 E QUERY [js] Error: couldn't add user: not authorized on licensing to execute command { createUser: "root", pwd: "xxx", roles: [ { role: "root", db: "admin" } ], digestPassword: true, writeConcern: { w: "majority", wtimeout: 600000.0 }, lsid: { id: UUID("b148691b-d585-48e9-9cdd-1d58ad4a4294") }, $db: "licensing" } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1491:15
@mongo_import.js:5:1
failed to load: mongo_import.js
我在做什么错了?
答案 0 :(得分:1)
您必须添加
MONGO_INITDB_DATABASE=admin
您的环境变量。
如果使用.js
脚本,则必须使用变量MONGO_INITDB_DATABASE
定义auth数据库。
如果您未设置此值,则脚本将在test
数据库中进行身份验证。