The docker hub mongo
image will run any scripts in /docker-entrypoint-initdb.d/
when there is nothing populated in the /data/db
directory.
Database Initialisation
The mongo
container image provides the /docker-entrypoint-initdb.d/
path to deploy custom .js
or .sh
setup scripts that will be run once on database initialisation. .js
scripts will be run against test
by default or MONGO_INITDB_DATABASE
if defined in the environment.
COPY mysetup.sh /docker-entrypoint-initdb.d/
or
COPY mysetup.js /docker-entrypoint-initdb.d/
A simple initialisation mongo shell javascript file that demonstrates setting up the container
collection with data, logging and how to exit with an error (for result checking).
let error = true
let res = [
db.container.drop(),
db.container.createIndex({ myfield: 1 }, { unique: true }),
db.container.createIndex({ thatfield: 1 }),
db.container.createIndex({ thatfield: 1 }),
db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]
printjson(res)
if (error) {
print('Error, exiting')
quit(1)
}
Admin User Setup
The environment variables to control "root" user setup are
MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD
Example
docker run -d \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongod
or Dockerfile
FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password
You don't need to use --auth
on the command line as the docker entrypoint.sh
script adds this in when it detects the environment variables exist.