How to create user in mongodb with docker-compose

EDIT: tutumcloud repository is deprecated and no longer maintained, see other answers

I suggest that you use environment variables to set mongo user, database and password. tutum (owned by Docker) published a very good image

https://github.com/tutumcloud/mongodb

docker run -d -p 27017:27017 -p 28017:28017 -e MONGODB_USER="user" -e MONGODB_DATABASE="mydatabase" -e MONGODB_PASS="mypass" tutum/mongodb

You may convert these variables into docker-compose environments variables. You don't have to hard code it.

environment:
    MONGODB_USER: "${db_user_env}"
    MONGODB_DATABASE: "${dbname_env}"
    MONGODB_PASS: "${db_pass}"

This configuration will read from your session's environment variables.


After reading the the official mongo docker page, I've found that you can create an admin user one single time, even if the auth option is being used. This is not well documented, but it simply works (hope it is not a feature). Therefore, you can keep using the auth option all the time.

I created a github repository with scripts wrapping up the commands to be used. The most important command lines to run are:

docker exec db_mongodb mongo admin /setup/create-admin.js
docker exec db_mongodb mongo admin /setup/create-user.js -u admin -p admin --authenticationDatabase admin

The first line will create the admin user (and mongo will not complain even with auth option). The second line will create your "normal" user, using the admin rights from the first one.


The official mongo image now supports following environment variables that can be used in docker-compose as below:

environment:
      - MONGO_INITDB_ROOT_USERNAME=user
      - MONGO_INITDB_ROOT_PASSWORD=password
      - MONGO_INITDB_DATABASE=test

more explanation at: https://stackoverflow.com/a/42917632/1069610


This is how I do it, my requirement was to bring up a few containers along with mongodb, the other containers expect a user to be present when they come up, this worked for me. The good part is, the mongoClientTemp exits after the command is executed so the container doesn't stick around.

version: '2'
services:
  mongo:
   image: mongo:latest
   container_name: mongo
   ports:
    - "27017:27017"
   volumes:
    - /app/hdp/mongo/data:/data/db

  mongoClientTemp:
   image: mongo:latest
   container_name: mongoClientTemp
   links:
    - mongo:mongo
   command: mongo --host mongo --eval  "db.getSiblingDB('dashboard').createUser({user:'db', pwd:'dbpass', roles:[{role:'readWrite',db:'dashboard'}]});"
   depends_on:
    - mongo

  another-container:
   image: another-image:v01
   container_name: another-container
   ports:
    - "8080:8080"
   volumes:
    - ./logs:/app/logs
   environment:
    - MONGODB_HOST=mongo
    - MONGODB_PORT=27017
   links:
    - mongo:mongo
   depends_on:
    - mongoClientTemp