Here's a working solution that creates admin-user
user with a password, additional database (test-database
), and test-user
in that database.
Dockerfile:
FROM mongo:4.0.3
ENV MONGO_INITDB_ROOT_USERNAME admin-user
ENV MONGO_INITDB_ROOT_PASSWORD admin-password
ENV MONGO_INITDB_DATABASE admin
ADD mongo-init.js /docker-entrypoint-initdb.d/
mongo-init.js:
db.auth('admin-user', 'admin-password')
db = db.getSiblingDB('test-database')
db.createUser({
user: 'test-user',
pwd: 'test-password',
roles: [
{
role: 'root',
db: 'test-database',
},
],
});
The tricky part was to understand that *.js files were run unauthenticated.
The solution authenticates the script as the admin-user
in the admin
database. MONGO_INITDB_DATABASE admin
is essential, otherwise the script would be executed against the test
db. Check the source code of docker-entrypoint.sh.