如何通过 Docker 在 MongoDB 上启用身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34559557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enable authentication on MongoDB through Docker?
提问by user706838
I want to spin-up a docker for mongodb:latest
but allow only certain user(s) to access certain db(s) (i.e. enable --auth
). No one else should access mongodb whatsoever! How should I do this as part of the docker initiation?
我想启动一个 dockermongodb:latest
但只允许某些用户访问某些 db(s)(即启用--auth
)。任何人都不应访问 mongodb!作为 docker 启动的一部分,我应该如何执行此操作?
BTW, data directory
sits on the host by utilising the following command during initiation: -v /my/own/datadir:/data/db
.
顺便说一句,data directory
在启动过程中使用以下命令位于主机上:-v /my/own/datadir:/data/db
.
回答by jbochniak
If you take a look at:
如果你看一下:
- https://github.com/docker-library/mongo/blob/master/4.2/Dockerfile
- https://github.com/docker-library/mongo/blob/master/4.2/docker-entrypoint.sh#L303-L313
- https://github.com/docker-library/mongo/blob/master/4.2/Dockerfile
- https://github.com/docker-library/mongo/blob/master/4.2/docker-entrypoint.sh#L303-L313
you will notice that there are two variables used in the docker-entrypoint.sh
:
您会注意到在 中使用了两个变量docker-entrypoint.sh
:
- MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD
- MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD
You can use them to setup root user. For example you can use following docker-compose.yml
file:
您可以使用它们来设置 root 用户。例如,您可以使用以下docker-compose.yml
文件:
mongo-container:
image: mongo:3.4.2
environment:
# provide your credentials here
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
ports:
- "27017:27017"
volumes:
# if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
# no --auth is needed here as presence of username and password add this option automatically
command: mongod
Now when starting the container by docker-compose up
you should notice following entries:
现在,当您启动容器时,docker-compose up
您应该注意到以下条目:
...
I CONTROL [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose
to entrypoint):
要在 root 之外添加自定义用户,请使用入口点可执行脚本(放置在 $PWD/mongo-entrypoint 目录下,因为它安装docker-compose
到入口点):
#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."
Entrypoint script will be executed and additional users will be created.
将执行入口点脚本并创建其他用户。
回答by SnnSnn
a. You can use environment variables via terminal:
一种。您可以通过终端使用环境变量:
$ docker run -d --name container_name \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo
If you like to test if everything works:
如果你想测试一切是否正常:
// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash
// Enter into mongo shell
$ mongo
// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())
// Show available databases
$> show dbs
If you like to instantiate a database on first run, check option b.
如果您想在第一次运行时实例化数据库,请选中选项 b。
b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.
湾 您可以在 docker 堆栈部署文件或 3.4 到 4.1 版本的撰写文件中使用环境变量。
As it is explained on the quick reference section of the official mongo imageset MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your yaml file:
正如官方 mongo 图像集的快速参考部分MONGO_INITDB_ROOT_USERNAME
和MONGO_INITDB_ROOT_PASSWORD
您的 yaml 文件中所解释的:
mongo:
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
docker-entrypoint.shfile in mongo image checks for the existence of these two variables and sets --auth
flag accordingly.
mongo 映像中的docker-entrypoint.sh文件检查这两个变量是否存在并相应地设置--auth
标志。
c. You can also use docker secrets.
C。您还可以使用 docker 机密。
MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
variables:
MONGO_INITDB_ROOT_USERNAME
并MONGO_INITDB_ROOT_PASSWORD
通过从docker-entrypoint.sh间接设置MONGO_INITDB_ROOT_USERNAME_FILE
和MONGO_INITDB_ROOT_PASSWORD_FILE
变量:
mongo:
image: mongo
environment:
- MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
- MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
secrets:
- db_root_username
- db_root_password
docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
to MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
.
docker-entrypoint.sh 将MONGO_INITDB_ROOT_USERNAME_FILE
and转换MONGO_INITDB_ROOT_PASSWORD_FILE
为MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
。
You can use MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your .sh
or .js
scripts in docker-entrypoint-initdb.d
folder while initializing database instance.
您可以在初始化数据库实例时在您的或文件夹中的脚本中使用MONGO_INITDB_ROOT_USERNAME
和。MONGO_INITDB_ROOT_PASSWORD
.sh
.js
docker-entrypoint-initdb.d
When a container is started for the first time it will execute files with extensions .sh
and .js
that are found in /docker-entrypoint-initdb.d
. Files will be executed in alphabetical order. .js
files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE
variable, if it is present, or test otherwise. You may also switch databases within the .js
script.
当容器启动首次它将与扩展执行文件.sh
和.js
那个被发现在/docker-entrypoint-initdb.d
。文件将按字母顺序执行。.js
文件将由 mongo 使用MONGO_INITDB_DATABASE
变量指定的数据库执行(如果存在),否则进行测试。您还可以在.js
脚本中切换数据库。
This last method is not in the reference docs, so it may not survive an update.
最后一种方法不在参考文档中,因此它可能无法在更新后继续存在。
回答by Sankaran Srinivasan
Better solutions for furthering:
https://blog.madisonhub.org/setting-up-a-mongodb-server-with-auth-on-docker/https://docs.mongodb.com/v2.6/tutorial/add-user-administrator/
更好的解决方案:
https: //blog.madisonhub.org/setting-up-a-mongodb-server-with-auth-on-docker/ https://docs.mongodb.com/v2.6/tutorial/add -用户管理员/
Here's what I did for the same problem, and it worked.
这是我为同样的问题所做的,它奏效了。
Run the mongo docker instance on your server
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo
Open bash on the running docker instance.
docker ps
CONTAINER IDIMAGE COMMAND CREATED STATUS PORTS NAMES
b07599e429fb mongo "docker-entrypoint..." 35 minutes ago Up 35 minutes 0.0.0.0:27017->27017/tcp musing_stallman
docker exec -it b07599e429fb bash root@b07599e429fb:/#
Enter the mongo shell by typing mongo.
root@b07599e429fb:/# mongo
For this example, I will set up a user named ian and give that user read & write access to the cool_db database.
> use cool_db > db.createUser({ user: 'ian', pwd: 'secretPassword', roles: [{ role: 'readWrite', db:'cool_db'}] })
Reference: https://ianlondon.github.io/blog/mongodb-auth/(First point only)
Exit from mongod shell and bash.
Stop the docker instance using the below command.
docker stop mongo
Now run the mongo docker with auth enabled.
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo mongod --auth
Reference: How to enable authentication on MongoDB through Docker?(Usman Ismail's answer to this question)
I was able to connect to the instance running on a Google Cloud server from my local windows laptop using the below command.
mongo <ip>:27017/cool_db -u ian -p secretPassword
Reference: how can I connect to a remote mongo server from Mac OS terminal
在您的服务器上运行 mongo docker 实例
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo
在正在运行的 docker 实例上打开 bash。
docker ps
容器 IDIMAGE 命令创建状态端口名称
b07599e429fb mongo "docker-entrypoint..." 35 分钟前向上 35 分钟 0.0.0.0:27017->27017/tcp musing_stallman
docker exec -it b07599e429fb bash root@b07599e429fb:/#
通过键入 mongo 进入 mongo shell。
root@b07599e429fb:/# mongo
在本例中,我将设置一个名为 ian 的用户并授予该用户对 cool_db 数据库的读写访问权限。
> use cool_db > db.createUser({ user: 'ian', pwd: 'secretPassword', roles: [{ role: 'readWrite', db:'cool_db'}] })
参考:https: //ianlondon.github.io/blog/mongodb-auth/(仅限第一点)
退出 mongod shell 和 bash。
使用以下命令停止 docker 实例。
docker stop mongo
现在在启用身份验证的情况下运行 mongo docker。
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo mongod --auth
参考:如何通过 Docker 在 MongoDB 上启用身份验证?(Usman Ismail 对这个问题的回答)
我能够使用以下命令从本地 Windows 笔记本电脑连接到在 Google Cloud 服务器上运行的实例。
mongo <ip>:27017/cool_db -u ian -p secretPassword
回答by Usman Ismail
The Dockerfile for the official mongo image is here. The default command is mongod but you can override to add the --auth switch assuming user's are already configured.
官方 mongo 镜像的 Dockerfile 在这里。默认命令是 mongod 但您可以覆盖添加 --auth 开关假设用户已经配置。
docker run -d .... mongodb:latest mongod --auth
If the user has to be created then you need to volume mount a startup script into /entrypoint.sh
to replace the default startup script and then have that script create users and start mongo with the auth switch.
如果必须创建用户,那么您需要将启动脚本批量装入/entrypoint.sh
以替换默认启动脚本,然后让该脚本创建用户并使用 auth 开关启动 mongo。
docker run -d .... -v $PWD/my_custom_script.sh:/entrypoint.sh mongodb:latest
回答by Shapeshifter
Just dropping a .js file into the entry point init folder works for this
只需将 .js 文件放入入口点 init 文件夹即可解决此问题
e.g. entrypoint.js
例如入口点.js
var db = connect("mongodb://localhost/admin");
db.createUser(
{
user: "yourAdminUserName",
pwd: "yourAdminPassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
docker-compose.yml:
docker-compose.yml:
db:
image: mongo:3.2
volumes:
- /my/own/datadir:/data/db
- ../mongo-entrypoint:/docker-entrypoint-initdb.d
Doing the rest by hand or more of the same works.
手工完成其余的工作或更多相同的工作。
If you want to you can also drop a .sh file into the init folder to clean up the files so they are not laying around: zz-cleanup.sh.
如果您愿意,您还可以将 .sh 文件放入 init 文件夹以清理文件,以免它们四处乱放:zz-cleanup.sh。
回答by Che-Hao Kang
I want to comment but don't have enough reputation.
我想发表评论,但没有足够的声誉。
The user-adding executable script shown above has to be modified with --authenticationDatabase adminand NEWDATABASENAME.
必须使用--authenticationDatabase admin和NEWDATABASENAME修改上面显示的用户添加可执行脚本 。
mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"
回答by Frederik
@jbochniak: Thanks, although at first read I thought I've already discovered all of this, it turned out that your example (esp. the version of the Mongo Docker image) helped me out!
@jbochniak:谢谢,虽然在第一次阅读时我以为我已经发现了所有这些,但事实证明您的示例(尤其是 Mongo Docker 映像的版本)帮助了我!
That version (v3.4.2) and the v3.4 (currently corresponding to v3.4.3) still support 'MONGO_INITDB_ROOT' specified through those variables, as of v3.5 (at least tags '3' and 'latest') DON'T work as describedin your answer and in the docs.
该版本 (v3.4.2) 和 v3.4(当前对应于 v3.4.3)仍然支持通过这些变量指定的“MONGO_INITDB_ROOT”,从 v3.5 开始(至少标签“3”和“最新”)不要按照您的回答和文档中的描述工作。
I quickly had a look at the code on GitHub, but saw similar usage of these variables and couldn't find the bug immediately, should do so before filing this as a bug...
我很快查看了 GitHub 上的代码,但看到这些变量的类似用法并且无法立即找到错误,应该在将其作为错误提交之前这样做......
回答by Mark Simon
use this images to fix:
使用此图像修复:
With docker-compose.yml
使用 docker-compose.yml
services:
db:
image: aashreys/mongo-auth:latest
environment:
- AUTH=yes
- MONGODB_ADMIN_USER=admin
- MONGODB_ADMIN_PASS=admin123
- MONGODB_APPLICATION_DATABASE=sample
- MONGODB_APPLICATION_USER=aashrey
- MONGODB_APPLICATION_PASS=admin123
ports:
- "27017:27017"
// more configuration
回答by Ehsan sarshar
you can use env variables to setup username and password for mongo
您可以使用 env 变量为 mongo 设置用户名和密码
MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD
using simple docker command
使用简单的 docker 命令
docker run -e MONGO_INITDB_ROOT_USERNAME=my-user MONGO_INITDB_ROOT_PASSWORD=my-password mongo
using docker-compose
使用 docker-compose
version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: my-user
MONGO_INITDB_ROOT_PASSWORD: my-password
and the last option is to manually access the container and set the user and password inside the mongo docker container
最后一个选项是手动访问容器并在 mongo docker 容器中设置用户和密码
docker exec -it mongo-container bash
now you can use mongo shell command to configure everything that you want
现在你可以使用 mongo shell 命令来配置你想要的一切
回答by Chau Giang
I have hard time when trying to
我在尝试时很难
- Create other db than admin
- Add new users and enable authentication to the db above
- 创建除管理员以外的其他数据库
- 添加新用户并启用对上面数据库的身份验证
So I made 2020answer here
所以我在这里做了2020 年的回答
My directory looks like this
我的目录看起来像这样
├── docker-compose.yml
└── mongo-entrypoint
└── entrypoint.js
My docker-compose.yml
looks like this
我的docker-compose.yml
看起来像这样
version: '3.4'
services:
mongo-container:
# If you need to connect to your db from outside this container
network_mode: host
image: mongo:4.2
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=pass
ports:
- "27017:27017"
volumes:
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
command: mongod
Please change admin
and pass
with your need.
请更改admin
,并pass
与您的需要。
Inside mongo-entrypoint
, I have entrypoint.js
file with this content:
在里面mongo-entrypoint
,我有entrypoint.js
这个内容的文件:
var db = connect("mongodb://admin:pass@localhost:27017/admin");
db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db
db.createUser(
{
user: "user",
pwd: "pass",
roles: [ { role: "readWrite", db: "new_db"} ],
passwordDigestor: "server",
}
)
Here again you need to change admin:pass
to your root mongo credentials in your docker-compose.yml
that you stated before. In additional you need to change new_db
, user
, pass
to your new database name and credentials that you need.
在这里,您需要再次更改admin:pass
您docker-compose.yml
之前声明的根 mongo 凭据。在另外你需要改变new_db
,user
,pass
到新的数据库名称和凭据,你所需要的。
Now you can:
现在你可以:
docker-compose up -d
And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo
command:
然后从localhost连接到这个db,请注意我已经有了mongo cli,你可以安装它或者你可以执行到上面的容器来使用mongo
命令:
mongo new_db -u user -p pass
Or you can connect from other computer
或者您可以从其他计算机连接
mongo host:27017/new_db -u user -p pass
My git repository: https://github.com/sexydevops/docker-compose-mongo
我的 git 仓库:https: //github.com/sexydevops/docker-compose-mongo
Hope it can help someone, I lost my afternoon for this ;)
希望它可以帮助某人,我为此失去了下午;)