简体   繁体   中英

Create a MongoDB database through docker-compose

docker-compose.yml

mongo:
        image: mongo:3.4.13-jessie
        restart: always
        ports:
            - "27019:27017"
        volumes:
            - ./db1.js:/docker-entrypoint-initdb.d/db1.js:ro
            - ./db2.js:/docker-entrypoint-initdb.d/db2.js:ro

db1.js

use testdba;
db.getCollection("users").insert({
   "name": "A"
})

db2.js

use testdbb;
db.getCollection("users").insert({
   "name": "B"
})

the files are copied in the mongo container but not executed my understanding is that files(*.js) inside docker-entrypoint-initdb.d/ gets executed, but with above setup it doesn't

does anyone know what am I missing?

also in some of the post I found

environment:
      MONGO_INITDB_ROOT_USERNAME: test
      MONGO_INITDB_ROOT_PASSWORD: test
      MONGO_INITDB_DATABASE: admin

do I need to add root user before the .js fils can be executed ?

MongoDB finds your files and tries to execute them but it fails. You can see that in the logs: docker-compose logs -f and look for the line where it tries to run your first js file.

To fix it use this syntax in your js files:

db.testdba.getCollection("users").insert({
   "name": "A"
});

After you edit both your files start your service with docker-compose up -d . Check again the logs and you will see that the files are executed successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM