Skip to content

Unable to use docker-entrypoint-initdb.d start scripts to setup a new user without exposing passwords #535

@ferrao

Description

@ferrao

I am trying to setup the mongo docker image in Docker Compose in such a way that:

  1. A user with the root role is created on the admin database.
  2. A user with readWrite role on another database is created.

I want username, password and database to come from environment variables. This is proving to be impossible with the current mongo:5.0.8 image.

This is the relevant part of my docker-compose.yaml:

        container_name: read-store
        image: mongo:5.0.8
        restart: always
        environment:
            - MONGO_INITDB_ROOT_USERNAME=${MONGO_USER}
            - MONGO_INITDB_ROOT_PASSWORD=${MONGO_PASS}
            - MONGO_INITDB_DATABASE=${READ_STORE_DB}
        ports:
            - 27017:27017
        command: --auth
        volumes:
            - mongo:/data/db
            - ../db/read-model/docker/:/docker-entrypoint-initdb.d/

The MONGO_USER, MONGO_PASS and READ_STORE_DB values are fetched from a .env file.

The root user is successfully created by the docker-entrypoint.sh script, so this part of the setup works just fine.

The problem comes when I try to setup my database user on docker-entrypoint-initdb.d. I have the choice of using either a .js or a .sh file in there to achieve this, as described in the Initializing a fresh instance section of the documentation.

Problem is that neither work for my intent and purposes, here is why:

  • .js file - can not pass environment variables here, so I end up exposing the auth credentials on this file, which I want under revision control
  • .sh file - file is executed by user mongodb, which causes 2 different problems:
  1. /home/mongodb home directory does not exist, which causes mongosh to fail. It runs fine as user root, or if I simply create the missing home directory.
  2. Environment variables are passed and accessible to root user, but not the mongodb user.

So basically I have my hands tied. If I run my script manually as root after the container is up, everything works, but no way to get it to run properly by the docker-entrypoint.sh script.

Maybe I am missing something here, if that is the case, lets properly document how to achieve this. I have seen countless threads regarding this issue and people struggling with this simple user creation, which could be solved with a simple example on the documentation page.

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