Hvis du kigger på:
- https://github.com/docker-library/mongo/blob/master/4.2/Dockerfile
- https://github.com/docker-library/mongo/blob/master/4.2/docker-entrypoint.sh#L303-L313
du vil bemærke, at der er to variabler brugt i docker-entrypoint.sh
:
- MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD
Du kan bruge dem til at konfigurere root-bruger. For eksempel kan du bruge følgende docker-compose.yml
fil:
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
Nu, når du starter containeren ved at docker-compose up
du bør bemærke følgende poster:
...
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"
}
]
}
For at tilføje brugerdefinerede brugere ud over root, skal du bruge entrypoint-eksekverbare script (placeret under $PWD/mongo-entrypoint dir, som det er monteret i docker-compose
til indgangspunktet):
#!/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 vil blive udført, og yderligere brugere vil blive oprettet.