title: How to create user in mongodb with docker-compose
body: <p>I'm trying to create some kind of script that will create a docker with mongodb and automatically create a user.</p>
  
  <p>I can usually manage my docker images with docker-compose but this time, I don't know how to do it.</p>
  
  <p>Basically, here is what I have to do:</p>
  
  <ol>
  <li>clean/destroy container (<code>docker-compose down</code>)</li>
  <li>create a docker container with mongodb and start it (without <code>--auth parameter</code>) </li>
  <li>execute a java script containing <code>db.createUser()</code></li>
  <li>stop the container</li>
  <li>restart the same container with <code>--auth</code> parameter to allow login with the user created in the javascript</li>
  </ol>
  
  <p><strong>I can't find how to do that properly with docker-compose because when it starts, I have to give it the command --auth. If I do that, I cannot execute my javascript to add my user. MongoDB allows users creation without being logged in if there is no user and if --auth parameter is not provided.</strong></p>
  
  <p>I want to do that automatically, I do not want to manually do some commands. The goal is to have a script that can be executed before each integration tests to start from a clean database.</p>
  
  <p>Here is my project: </p>
  
  <p>integration-test/src/test/resources/scripts/docker-compose.yml</p>
  
  <pre><code>mongodb:
      container_name: mongo
      image: mongo
    ports:
      - "27017:27017"
    volumes:
      - .:/setup
    command: --auth
  </code></pre>
  
  <p>integration-test/src/test/resources/scripts/docker-init.sh</p>
  
  <pre><code>docker-compose down
  docker-compose up -d
  sleep 1
  docker exec mongo bash -c "mongo myDatabase /setup/mongodb-setup.js"
  </code></pre>
  
  <p>integration-test/src/test/resources/scripts/mongodb-setup.js</p>
  
  <pre><code>db.createUser(
  {
      user: "myUser",
      pwd: "myPassword",
      roles: [
        { role: "readWrite", db: "myDatabase" }
      ]
  })
  </code></pre>
  
  <p>Finding a way to start again a container with a new parameter (in this case <code>--auth</code>) would help but I can't find how to do that (docker start does not take parameters).</p>
  
  <p>Any idea how I should do what I would like ? </p>
  
  <p>If not, I can still delete everything from my database with some Java code or something else but I would like a complete mongodb docker setup created with a script.</p>