title: How to initialize a new user and database for mongodb on docker-compose
body: <p>So, currently I have a <code>docker-compose.yml</code> file that has the following:</p>
  
  <pre><code>version: "2"
  services:
   pastime:
     build:
       context: ./pastime
       dockerfile: ./Dockerfile
     volumes:
       - ./pastime:/usr/src/app
       - /usr/src/app/node_modules
     ports:
       - "3000:3000"
     depends_on:
       - mongo
     environment:
       - PORT=3000
       - DATABASE_USER=pastime
       - DATABASE_URL=mongo:27017
       - DATABASE_PASS=pastime123
       - DATABASE_NAME=pastime
     command: npm run start:dev
   mongo:
     image: mongo:latest
     restart: always
     ports:
       - "27017:27017"
     environment:
       - MONGO_INITDB_DATABASE=pastime
       - MONGO_INITDB_ROOT_USERNAME=root
       - MONGO_INITDB_ROOT_PASSWORD=root_password
     volumes:
       - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
  </code></pre>
  
  <p>And also my <code>init-mongo.js</code> file has:</p>
  
  <pre><code>db.createUser({
    user: 'pastime',
    pwd: 'pastime123',
    roles: [
      {
        role: 'readWrite',
        db: 'pastime'
      }
    ]
  })
  </code></pre>
  
  <p>I am not sure why, but the output I get everytime when I do a <code>docker-compose logs -f mongo</code> comes up to:
  <code>SASL SCRAM-SHA-1 authentication failed for pastime on admin from client 172.19.0.3:55568 ; UserNotFound: Could not find user "pastime"...</code></p>
  
  <p>I suspect that the init script is not running as I don't see kinds of logs about it in my mongo container.</p>
  
  <p>Have followed a few examples, mainly following thru with this one:
  <a href="https://stackoverflow.com/questions/42912755/how-to-create-a-db-for-mongodb-container-on-start-up">How to create a DB for MongoDB container on start up?</a></p>