0

Hi I am using below docker file to create a mongodb instance ,

version: '3.1'
services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: XXXXXXXXXXX
    ports:
      - 27017:27017

Now how can I run some write + run init script to do following task ,

  • create a database name "data"
  • Create collections inside this database
  • Create 2 users for this database.
Naggappan Ramukannan
  • 2,564
  • 9
  • 36
  • 59

1 Answers1

1

The official docker mongo image supports db creation/initialization:

https://hub.docker.com/_/mongo/ Scroll down to 'MONGO_INITDB_DATABASE'

MONGO_INITDB_DATABASE
This variable allows you to specify the name of a database to be used 
for creation scripts in /docker-entrypoint-initdb.d/*.js (see 
Initializing a fresh instance below). MongoDB is fundamentally designed 
for "create on first use", so if you do not insert data with your 
JavaScript files, then no database is created.

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.
d g
  • 1,594
  • 13
  • 13
  • hi dg, can you give me some example js files, or link? I dont' get when i search. some example like create user, create collections etc – Naggappan Ramukannan May 14 '18 at 12:35
  • I enabled MONGO_INITDB_DATABASE: colltest and then mounted local folder as volume in /docker-entrypoint-init.d. And when I do there is a file called init.js db.createCollection("clouddata"). But still it is not executing when I do docker-compose up. it is just as a file inside container – Naggappan Ramukannan May 14 '18 at 13:14
  • 1
    I have never done this, but heres a post which shows how to get the *js to the container and an example js file (scroll down to 'Other Custom Initialisation') https://stackoverflow.com/questions/42912755/how-to-create-a-db-for-mongodb-container-on-start-up - Hope this helps! – d g May 14 '18 at 13:25