<p>I am trying to do the following tutorial:
<a href="https://itnext.io/docker-mongodb-authentication-kubernetes-node-js-75ff995151b6" rel="noreferrer">https://itnext.io/docker-mongodb-authentication-kubernetes-node-js-75ff995151b6</a></p>
<p>However, in there, they use raw values for the mongo init.js file that is placed within docker-entrypoint-initdb.d folder.</p>
<p>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.</p>
<p>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.</p>
<p>Thank you in advance and regards.</p>

<p>you can make use of a shell script to retrieve env variables and create the user.</p>
<p><strong>initdb.d/init-mongo.sh</strong></p>
<pre><code>set -e

mongo &lt;&lt;EOF
use $MONGO_INITDB_DATABASE

db.createUser({
  user: '$MONGO_INITDB_USER',
  pwd: '$MONGO_INITDB_PWD',
  roles: [{
    role: 'readWrite',
    db: '$MONGO_INITDB_DATABASE'
  }]
})
EOF
</code></pre>
<p><strong>docker-compose.yml</strong></p>
<pre><code>version: &quot;3.7&quot;

services:
  mongodb:
    container_name: &quot;mongodb&quot;
    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: [ &quot;-f&quot;, &quot;/etc/mongod.conf&quot; ]
</code></pre>
<p>Now you can connect to <code>development</code> database using <code>mongodb</code> as user and password credentials.</p>
