MongoDB init script won't work when a volume is mounted

Viewed 145

I'm trying to set up a cluster with my NodeJs app and Mongo DB. For this I need to create a DB and a user for this DB on init. And also it would be cool if the data was persisted, so I need to mount a volume.

I am using Windows 10.

When I mount a volume, the init script won't work. It only works when I am not mounting any data volume. I've read that the init scripts are executed only when the data/db volume is empty. Is there a problem?

My docker-compose.yml:

version: '3.7'
services:
  mailer_mongo_db:
  container_name: mailer-db
  image: mongo:4
  env_file: ./.env
  environment:
    - MONGO_INITDB_ROOT_USERNAME=$MONGO_ROOT_USERNAME
    - MONGO_INITDB_ROOT_PASSWORD=$MONGO_ROOT_PASSWORD
    - MONGO_INITDB_DATABASE=admin
    - MAILER_USERNAME=$MONGO_USERNAME
    - MAILER_PWD=$MONGO_PASSWORD
    - MAILER_DATABASE=$MONGO_DBNAME
  ports:
    - 27017:27017
  restart: always
  volumes:
    #- db-data:/data/db
    #- /Users/andrz/Documents/Volumes/mailer-mongo-volume:/data/db
    - ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro
  networks: 
    - mailer
api:
  container_name: mailer-api
  build: ./
  restart: always
  volumes:
    - ./:/usr/src/api/
  depends_on:
    - mailer_mongo_db
  ports:
    - 3000:3000
    - 465:465
  env_file: ./.env
  command: 'npm start'
  networks: 
    - mailer

networks:
  mailer:
    driver: bridge

volumes:
  db-data:

The mongo-init.sh:

mongo --eval "db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD'); db = db.getSiblingDB('$MAILER_DATABASE'); db.createUser({ user: '$MAILER_USERNAME', pwd: '$MAILER_PWD', roles: [{ role: 'readWrite', db: '$MAILER_DATABASE' }] });"

As you can see there are two ways of mounting the data volume. Each works fine but the init script won't execute.

Is there something I am missing?

0 Answers
Related