I am expanding my docker-compose.yml for MongoDB container. I want to add some initial data.
The docker-compose.yml
looks like this:
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
When I am running this script I get an error in mongo container logs that user root is not existing.
So I have created a mongo_import.js script, it looks like this:
db.auth('root', 'root')
db = db.getSiblingDB('licensing')
db.createUser({
user: 'root',
pwd: 'root',
roles: [
{
role: 'root',
db: 'admin',
},
],
});
It doesn't work. When I go to the shell in this container and run mongo mongo_import.js
I get:
# 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
What am I doing wrong?
You have to add
MONGO_INITDB_DATABASE=admin
to your environment variables.
If you use a .js
script, you have to define the auth database with the variable MONGO_INITDB_DATABASE
.
If you do not set this value, the script will authenticate in test
database.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.