Reputation: 192
What is the best solution to create a user and database in MongoDB using docker-compose?
mongo:
restart: always
image: mongo:latest
container_name: "mongodb"
environment:
- MONGODB_USERNAME=test
- MONGODB_PASSWORD=test123
- MONGODB_DATABASE=test1
volumes:
- ./data/db:/var/micro-data/mongodb/data/db
- ./setup:/setup
ports:
- 27017:27017
command: mongod --smallfiles --logpath=/dev/null # --quiet
MONGODB env doesn't work for me.
Upvotes: 0
Views: 828
Reputation: 37048
With https://hub.docker.com/_/mongo/ you need to start the db with auth disabled, wait for mongo to spin up, create a user, restart the container with auth enabled.
https://hub.docker.com/r/bitnami/mongodb/ has a handy script added:
You can create a user with restricted access to a database while starting the container for the first time. To do this, provide the MONGODB_USERNAME, MONGO_PASSWORD and MONGODB_DATABASE environment variables.
$ docker run --name mongodb \
-e MONGODB_USERNAME=my_user -e MONGODB_PASSWORD=password123 \
-e MONGODB_DATABASE=my_database bitnami/mongodb:latest
It seems like you have bitnami environment variables set up, but use the original image image: mongo:latest
where they are not being used.
So either use image: bitnami/mongodb:latest
, or add the user manually.
Update:
Starting from v3.0 you can benefit from Localhost exception so you don't need to restart the container. Instead you can start it with authentication enabled, wait some time for the server to start listening, create users from within the container, e.g.
docker exec mongo4 mongo test1 \
--eval 'db.createUser({user: "test", pwd: "test123", roles: [ "readWrite", "dbAdmin" ]});'
Upvotes: 3