Create multiple database using Bitnami/MongoDB docker-entrypoint-initdb.d

⚠️ This is merely to ease away pain for testing and local development. Please avoid using this for production.

3. Create a directory

with following files. Each step shows what's in those files.

├── docker-compose.yml
├── Dockerfile.Mongo.Local
├── db_init
 │   └── create_databases.sh

2. Create your local version of bitnami/mongodb image

# File name: Dockerfile.Mongo.Local
FROM bitnami/mongodb:4.0

USER root
RUN chmod 755 libmongodb.sh

3. Your docker compose yaml

version: "3"
services:
  mongo-db:
    # image: 'bitnami/mongodb:latest'
    build:
      context: .
      dockerfile: Dockerfile.Mongo.Local
    ports:
      - "27017:27017"
    volumes:
      - ./db_init:/docker-entrypoint-initdb.d
    environment:
      MONGODB_ROOT_PASSWORD: admin

4. Prepare bash script

for creating multiple databases

# create_databases.sh
/libmongodb.sh

mongodb_execute 'root' "$MONGODB_ROOT_PASSWORD" "" "127.0.0.1" <<EOF
  use schooldb
  db.getSiblingDB('schooldb').createCollection('students')
  use accountdb
  db.getSiblingDB('accountdb').createCollection('customer')
EOF

5. Start your docker

$ docker-compose up 
...
...
mongo-db_1       | MongoDB shell version v4.0.13
mongo-db_1       | connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
mongo-db_1       | Implicit session: session { "id" : UUID("a7dc5873-e649-42dd-9b50-621521b57479") }
mongo-db_1       | MongoDB server version: 4.0.13
mongo-db_1       | switched to db schooldb
mongo-db_1       | { "ok" : 1 }
mongo-db_1       | switched to db accountdb
mongo-db_1       | { "ok" : 1 }
mongo-db_1       | bye

....