title: Create database and user in mongoDB official docker image
body: <p>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 <code>docker-compose.yml</code>:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Imagine we have an <code>.env</code> file like this:</p>
  
  <pre><code>MONGO_ROOT_USER=my_fancy_username
  MONGO_ROOT_PASSWORD=my_fancy_password
  MY_DATABASE_NAME=my_fancy_database
  </code></pre>
  
  <p>What I would expect (reading <a href="https://hub.docker.com/_/mongo/" rel="nofollow noreferrer">the doc</a>) is that a database matching <code>MY_DATABASE_NAME</code> value is created and an user matching <code>MONGO_ROOT_USER</code> is created too and I could authenticate with the pair (<code>MONGO_ROOT_USER</code>,<code>MONGO_ROOT_PASSWORD</code>).</p>
  
  <p>Ok, I launch my container with <code>docker-compose up</code> and enter on it with <code>docker exec -it &lt;container-id&gt; bash</code>. I put <code>mongo</code> on the console and when I try to authenticate it crashes:</p>
  
  <pre><code>&gt; use my_fancy_database
  switched to db my_fancy_database
  &gt; db.auth('my_fancy_username','my_fancy_password')
  Error: Authentication failed.
  0 
  </code></pre>
  
  <p>On the log, the error I find is the following</p>
  
  <pre><code>[...] authentication failed for my_fancy_username on my_fancy_database from client [...] ; UserNotFound: Could not find user my_fancy_username@my_fancy_database
  </code></pre>
  
  <p>The <code>docker-compose.yml</code> configuration (as it was posted on official documentation) is not working. What I'm doing wrong?</p>
  
  <p>Thanks in advance.</p>