简体   繁体   English

docker-compose在mognodb中创建用户

[英]docker-compose create user in mognodb

What is the best solution to create a user and database in MongoDB using docker-compose? 使用docker-compose在MongoDB中创建用户和数据库的最佳解决方案是什么?

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. MONGODB env对我不起作用。

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/_/mongo/时,您需要在禁用身份验证的情况下启动数据库,等待mongo启动,创建用户,并在启用身份验证的情况下重启容器。

https://hub.docker.com/r/bitnami/mongodb/ has a handy script added: https://hub.docker.com/r/bitnami/mongodb/添加了一个方便的脚本:

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. 为此,请提供MONGODB_USERNAME,MONGO_PASSWORD和MONGODB_DATABASE环境变量。

$ 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. 似乎您已设置了bitnami环境变量,但在未使用它们的地方使用了原始图像image: mongo:latest So either use image: bitnami/mongodb:latest , or add the user manually. 因此,要么使用image: bitnami/mongodb:latest ,要么手动添加用户。

Update: 更新:

Starting from v3.0 you can benefit from Localhost exception so you don't need to restart the container. 从v3.0开始,您可以从Localhost异常中受益,因此无需重新启动容器。 Instead you can start it with authentication enabled, wait some time for the server to start listening, create users from within the container, eg 相反,您可以在启用身份验证的情况下启动它,等待服务器开始监听,从容器内创建用户,例如

docker exec mongo4 mongo test1 \
    --eval 'db.createUser({user: "test", pwd: "test123", roles: [ "readWrite", "dbAdmin" ]});'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM