Docker Community Forums

Share and learn in the Docker community.

Create new database in mongodb with docker-compose


(D3us) #1

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


(Joffrey F) #2

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.