Create database and user in mongoDB official docker image

Viewed 1783

I want to have a MongoDB service running in a Docker in order to serve a Flask app. What I've tried is create a container using docker-compose.yml:

my_mongo_service:
  image: mongo
  environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD}
      - MONGO_INITDB_DATABASE=${MY_DATABASE_NAME}
  ports:
    - "27017:27017"
  volumes:
    - "/data/db:/data/db"
  command: mongod

Imagine we have an .env file like this:

MONGO_ROOT_USER=my_fancy_username
MONGO_ROOT_PASSWORD=my_fancy_password
MY_DATABASE_NAME=my_fancy_database

What I would expect (reading the doc) is that a database matching MY_DATABASE_NAME value is created and an user matching MONGO_ROOT_USER is created too and I could authenticate with the pair (MONGO_ROOT_USER,MONGO_ROOT_PASSWORD).

Ok, I launch my container with docker-compose up and enter on it with docker exec -it <container-id> bash. I put mongo on the console and when I try to authenticate it crashes:

> use my_fancy_database
switched to db my_fancy_database
> db.auth('my_fancy_username','my_fancy_password')
Error: Authentication failed.
0 

On the log, the error I find is the following

[...] authentication failed for my_fancy_username on my_fancy_database from client [...] ; UserNotFound: Could not find user my_fancy_username@my_fancy_database

The docker-compose.yml configuration (as it was posted on official documentation) is not working. What I'm doing wrong?

Thanks in advance.

1 Answers

I don't get it. Are you using environmental variables, which are not in the environment? It sure looks so.

If you do echo $MY_DATABASE_NAME in your terminal and see empty output, then here is the answer to your question. You either first have to define the variable with export (or source for a file) or redefine your docker-compose.yml.

For that, it's best to use env_file directive:

my_mongo_service:
  image: mongo
  env_file:
      - .env
  ports:
    - "27017:27017"
  volumes:
    - "/data/db:/data/db"

And set your .env as this:

MONGO_INITDB_ROOT_USERNAME=my_fancy_username
MONGO_INITDB_ROOT_PASSWORD=my_fancy_password
MONGO_INITDB_DATABASE=my_fancy_database

Side note: using command: mongod is not necessary, the base image is already using it.

Related