a. You can use environment variables via terminal:
$ docker run -d --name container_name \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo
If you like to test if everything works:
// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash
// Enter into mongo shell
$ mongo
// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())
// Show available databases
$> show dbs
If you like to instantiate a database on first run, check option b.
b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.
As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your yaml file:
mongo:
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth
flag accordingly.
c. You can also use docker secrets.
MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
variables:
mongo:
image: mongo
environment:
- MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
- MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
secrets:
- db_root_username
- db_root_password
docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
to MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
.
You can use MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your .sh
or .js
scripts in docker-entrypoint-initdb.d
folder while initializing database instance.
When a container is started for the first time it will execute files with extensions .sh
and .js
that are found in /docker-entrypoint-initdb.d
. Files will be executed in alphabetical order. .js
files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE
variable, if it is present, or test otherwise. You may also switch databases within the .js
script.
This last method is not in the reference docs, so it may not survive an update.