Skip to content

No documentation on accessing ENV variables from docker-entrypoint_initdb.d #257

Closed

Description

@dlipovac012

As the name said, i couldn't find a way of accessing env variables from docker.
What i need is to access some var that is defined in docker-compose file over here:

let res = [
'use admin',
db.createUser({
user: 'apUser', // it should be this: ENV_APP_SERVER_USERNAME
pwd: '12345',
roles: [
{
role: 'readWrite',
db: 'dummydb'
}
]
})
];

printjson(res);

This is the content of javascript file that gets copied into docker-entrypoint-inidb.d

Activity

  1. bchrobot commented on Mar 23, 2018

    @bchrobot
  2. BorntraegerMarc commented on Mar 23, 2018

    @BorntraegerMarc

    Thanks for the link @bchrobot

    But what is the purpose of defining users in docker-entrypoint_initdb.d if you can't even access the password through env variables?
    How else would one securely set passwords?

  3. tianon commented on Mar 23, 2018

    @tianon
    Member
  4. BorntraegerMarc commented on Mar 23, 2018

    @BorntraegerMarc

    ah so with a shell script it is possible. Thanks for the info @tianon Nice! So to convert the JS into a .sh script I would have written:

    use admin
    db.createUser({
      user:  $ENV_APP_SERVER_USERNAME,
      pwd: $ENV_APP_SERVER_PW,
      roles: [{
        role: 'readWrite',
        db: 'dummydb'
      }]
    })
    

    Is that correct? Without the whole printjson thing...

  5. bchrobot commented on Mar 23, 2018

    @bchrobot

    Shell scripts are also executed (/docker-entrypoint-initdb.d/*.sh) so you could access ENV variables there.

    From this SO post it seems like something along the following lines would work:

    /docker-entrypoint-initdb.d/create_secure_user.sh:

    # Executed during Mongo container startup, concatenates scripts to pass ENV var
    
    mongo --eval "var secureUsername = '$ENV_APP_SERVER_USERNAME'" create_user-js

    /docker-entrypoint-initdb.d/create_user-js:

    // Skipped during Mongo container startup due to lack of .js extension.
    // Instead, is executed by above shell script.
    
    let res = [
      'use admin',
      db.createUser({
        user: secureUsername,
        pwd: '12345',
        roles: [
          {
            role: 'readWrite',
            db: 'dummydb'
          }
        ]
      })
    ];
    
    printjson(res);
  6. bchrobot commented on Mar 23, 2018

    @bchrobot

    @tianon if the above seems like a reasonable approach I will add it as an example for ENV usage in the 'Initializing a fresh instance' section in my docker-docs PR

  7. yosifkit commented on Mar 23, 2018

    @yosifkit
    Member

    I am quite sure you can just put it in one file and just use bash to insert the variables directly into the js. I don't see this as a necessary addition to the docs.

    #!/bin/bash
    set -e
    
    mongo <<EOF
    use admin
    db.createUser({
      user:  '$ENV_APP_SERVER_USERNAME',
      pwd: '$ENV_APP_SERVER_PW',
      roles: [{
        role: 'readWrite',
        db: 'dummydb'
      }]
    })
    EOF
  8. dlipovac012 commented on Mar 26, 2018

    @dlipovac012
    Author

    Thanks @yosifkit This script works perfectly fine.

  9. BorntraegerMarc commented on Mar 26, 2018

    @BorntraegerMarc

    Thanks @yosifkit
    But may I ask why you don't want to put this in the docs? The fact that we had to open an issue to get this information is proof for me that the info is not easily accessable.

  10. x-yuri commented on Nov 28, 2018

    @x-yuri

    No need for shebang, it's sourced.

  11. weibeld commented on Apr 2, 2019

    @weibeld

    No need for shebang, it's sourced.

    Thanks @x-yuri to point to this location in the code, that's great information.

    For short commands, you could also use a pipe instead of a heredoc to send the commands to mongo's stdin:

    echo "db.createUser({...})" | mongo admin
  12. javierguzman commented on Oct 30, 2020

    @javierguzman

    edit: sorry I found the stupid error; I had a typo I did not notice and was importing badly my environment variable, sorry for the trouble! I am going to run it now through the entire CI/CD flow and see if it works.
    Sorry @yosifkit I am trying your code snippet, however, it does not work. Has this changed?

    I have an initDatabase.sh file with the following content:

    #!/bin/bash
    set -e
    
    mongo <<EOF
    use admin
    db.createUser({
      user: '$MONGO_ADMIN_USER',
      pwd:  '$MONGO_ADMIN_PASSWORD',
      roles: [{
        role: 'readWrite',
        db: 'dummydb'
      }]
    })
    EOF
    

    I have in my shell the environment variables defined, but if I run the script it does not go ok, the error is:

    Error: couldn't add user: User passwords must not be empty

    What am I missing?

    Thank you very much in advance and regards.

  13. x-yuri commented on Oct 30, 2020

    @x-yuri

    FWIW, here's my answer on Stack Overflow. Although I'd avoid using Docker Swarm (buggy) and secrets (environment variables are easier to use). Also from a cursory glance at docker-entrypoint.sh, it looks like without MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD authentication is disabled, so no point in creating a user. On the other hand if you do specify the variables, you've got to authenticate first (before creating a user), as I did in my example. Whether it makes sense to create a non-root user if the database is accessed just by one application... I'm not sure.

  14. javierguzman commented on Nov 1, 2020

    @javierguzman

    Thanks @x-yuri Indeed at the end I just placed those variables (INITDB_ROOT_blabla) because as you pointed out, without them, auth is not enabled and I was having issues connecting because of that.

  15. orgads commented on Apr 21, 2021

    @orgads
    Contributor

    A function named _getEnv was added here. Usage:

    _getEnv("MONGO_INITDB_ROOT_USERNAME")
  16. garex commented on Jul 30, 2021

    @garex

    A function named _getEnv was added here. Usage:

    _getEnv("MONGO_INITDB_ROOT_USERNAME")

    But only since 4.7.0 !

  17. ogostus commented on Mar 23, 2023

    @ogostus

    To access env variables from docker-entrypoint-initdb.d

    Add env variables to mongo's container either via env_file or environment attributes

      mongo:
        volumes:
          # Add the db-init.js file to the Mongo DB container
          - .PATH_TO_FILE/db-init.js:/docker-entrypoint-initdb.d/db-init.js:ro
        ports:
          - ${MONGO_PORT}:27017
        environment:
          - MONGO_INITDB_DATABASE=
          - MONGO_INITDB_ROOT_USERNAME
          - MONGO_INITDB_ROOT_PASSWORD-
          - MONGO_USER
          - MONGO_PASSWORD
    

    db-init.js content would be:

    db.createUser({
      user: process.env.MONGO_USER,
      pwd: process.env.MONGO_PASSWORD,
      roles: [{ role: "readWrite", db: "dummydb" }],
    });
    
  18. x-yuri commented on Mar 23, 2023

    @x-yuri

    Some time ago, I updated my answer. _getEnv() is undocumented and available for a limited range of versions (around >=4.4, <5 probably). Starting with 6.x you can use process.env. Before that with the help of jq you can achieve pretty much the same result. At least I don't see any issues with it.

  19. bacloud22 commented on Mar 19, 2025

    @bacloud22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions