If you take a look at:
you will notice that there are two variables used in the docker-entrypoint.sh
:
- MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD
You can use them to setup root user. For example you can use following docker-compose.yml
file:
mongo-container:
image: mongo:3.4.2
environment:
# provide your credentials here
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
ports:
- "27017:27017"
volumes:
# if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
# no --auth is needed here as presence of username and password add this option automatically
command: mongod
Now when starting the container by docker-compose up
you should notice following entries:
...
I CONTROL [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose
to entrypoint):
#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."
Entrypoint script will be executed and additional users will be created.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…