Create new database in mongodb with docker-compose

Hello,

What is the best solution to add a new database to MongoDB in docker-compose?
Here is part of my docker-compose.yml:

mongo:
  restart: always
 image: mongo:latest
 container_name: "mongodb"
 environment:
  - MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
  - MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
  - MONGODB_USERNAME=test
  - MONGODB_PASSWORD=test123
  - MONGODB_DATABASE=test1
volumes:
  - ./data/db:/var/micro-data/mongodb/data/db
ports:
  - 27017:27017
command: mongod --smallfiles --logpath=/dev/null # --quiet

It seems that MongoDB envs don’t create user and database. I was thinking to run a command in the container with setup.js to create user and database. Maybe you know a better solution?

OS = ubuntu/xenial64

Here’s what the description of the mongo image spells out:

Initializing a fresh 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.

You may want to try setting MONGO_INITDB_DATABASE.

Hi,

I resolved this precise issue recently, see https://github.com/pnmcosta/saas-boilerplate/blob/docker-support/docker-compose.yml#L62

You will also need to set:

MONGO_INITDB_DATABASE=saas
MONGO_NON_ROOT_USERNAME=saas
MONGO_NON_ROOT_PASSWORD=secret

and keep

MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=supersecret

separate.

Please note if you’re running services that depend on it, the first boot (because it runs the init script) may error. For example, my saas-api service fails on the first load 1/3 times :smiley:

Cheers,
P.