How to create user in mongodb with docker-compose
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
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.