Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass environment variables to mongo docker-entrypoint-initdb.d?

I am trying to do the following tutorial: https://itnext.io/docker-mongodb-authentication-kubernetes-node-js-75ff995151b6

However, in there, they use raw values for the mongo init.js file that is placed within docker-entrypoint-initdb.d folder.

I would like to use environment variables that come from my CI/CD system (Gitlab). Does anyone know how to pass environment variables to the init.js file? I have tried several things like for example use init.sh instead for the shell but without any success.

If I run manually the init shell version, I can have it working because I call mongo with --eval and pass the values, however, the docker-entrypoint-blabla is called automatically, so I do not have control of how this is called and I do not know what I could do for achieving what I want.

Thank you in advance and regards.

like image 641
Javier Guzmán Avatar asked Oct 30 '20 10:10

Javier Guzmán


1 Answers

you can make use of a shell script to retrieve env variables and create the user.

initdb.d/init-mongo.sh

set -e

mongo <<EOF
use $MONGO_INITDB_DATABASE

db.createUser({
  user: '$MONGO_INITDB_USER',
  pwd: '$MONGO_INITDB_PWD',
  roles: [{
    role: 'readWrite',
    db: '$MONGO_INITDB_DATABASE'
  }]
})
EOF

docker-compose.yml

version: "3.7"

services:
  mongodb:
    container_name: "mongodb"
    image: mongo:4.4
    hostname: mongodb
    restart: always
    volumes:
      - ./data/mongodb/mongod.conf:/etc/mongod.conf
      - ./data/mongodb/initdb.d/:/docker-entrypoint-initdb.d/
      - ./data/mongodb/data/db/:/data/db/
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=root
      - MONGO_INITDB_DATABASE=development
      - MONGO_INITDB_USER=mongodb
      - MONGO_INITDB_PWD=mongodb
    ports:
      - 27017:27017
    command: [ "-f", "/etc/mongod.conf" ]

Now you can connect to development database using mongodb as user and password credentials.

like image 138
Lazaro Fernandes Lima Suleiman Avatar answered Sep 18 '22 02:09

Lazaro Fernandes Lima Suleiman