如何通过 Docker 在 MongoDB 上启用身份验证? [英] How to enable authentication on MongoDB through Docker?

查看:82
本文介绍了如何通过 Docker 在 MongoDB 上启用身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 mongodb:latest 启动一个 docker,但只允许某些用户访问某些 db(s)(即启用 --auth).任何人都不应访问 mongodb!作为 docker 启动的一部分,我应该如何执行此操作?

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?

顺便说一句,data directory 在启动过程中使用以下命令位于主机上:-v/my/own/datadir:/data/db.

BTW, data directory sits on the host by utilising the following command during initiation: -v /my/own/datadir:/data/db.

推荐答案

如果你看看:

你会注意到docker-entrypoint.sh中使用了两个变量:

you will notice that there are two variables used in the docker-entrypoint.sh:

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

您可以使用它们来设置 root 用户.例如,您可以使用以下 docker-compose.yml 文件:

You can use them to setup root user. For example you can use following docker-compose.yml file:

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

现在当通过 docker-compose up 启动容器时,您应该注意到以下条目:

Now when starting the container by docker-compose up you should notice following entries:

...
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"
        }
    ]
}

要添加除 root 之外的自定义用户,请使用入口点可执行脚本(放置在 $PWD/mongo-entrypoint 目录下,因为它安装在 docker-compose 到入口点):

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):

#!/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.

这篇关于如何通过 Docker 在 MongoDB 上启用身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆