简体   繁体   English

带有 docker-compose 的 Mongodb - 创建用户

[英]Mongodb with docker-compose - create user

This is my docker-compose.yaml:这是我的 docker-compose.yaml:

version: "2.0"
services:
  mongo_container:
    image: mongo:latest
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
      MONGO_INITDB_DATABASE: testdb
    ports:
      - "27017:27017"
    volumes:
      - ./mongodata:/data/db

And this in my spring configuration:这在我的弹簧配置中:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=root
spring.data.mongodb.password=example
spring.data.mongodb.database=testdb

But everytime when I try to connect my app to Mongo I get following error in Docker console:但是每次当我尝试将我的应用程序连接到 Mongo 时,我都会在 Docker 控制台中收到以下错误:

mongo_container_1  | 2020-03-31T07:37:24.803+0000 I  ACCESS   [conn2] SASL SCRAM-SHA-1 authentication failed for root on testdb from client 172.29.0.1:36628 ; UserNotFound: Could not find user "root" for db "testdb"

What am I doing wrong?我究竟做错了什么? I tried to remove all containers with docker system prune and run it again but it still gives the same error.我尝试使用docker system prune删除所有容器并再次运行它,但它仍然给出相同的错误。

You need to add the following line in your application.properties :您需要在 application.properties 中添加以下行:

spring.data.mongodb.authentication-database=admin

From docker-hub mongodb readme :来自 docker-hub mongodb 自述文件

MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD MONGO_INITDB_ROOT_USERNAME、MONGO_INITDB_ROOT_PASSWORD

These variables, used in conjunction, create a new user and set that user's password.这些变量结合使用,创建一个新用户并设置该用户的密码。 This user is created in the admin authentication database and given the role of root, which is a "superuser" role.该用户是在 admin 身份验证数据库中创建的,并被赋予 root 角色,这是一个“超级用户”角色。

And for database :对于数据库:

MONGO_INITDB_DATABASE This variable allows you to specify the name of a database to be used for creation scripts in /docker-entrypoint-initdb.d/*.js ... MongoDB is fundamentally designed for "create on first use", so if you do not insert data with your JavaScript files, then no database is created. MONGO_INITDB_DATABASE 此变量允许您在 /docker-entrypoint-initdb.d/*.js 中指定要用于创建脚本的数据库的名称... MongoDB 基本上是为“首次使用时创建”而设计的,因此如果您这样做不使用 JavaScript 文件插入数据,则不会创建数据库。

In MongoDB, when authentication is enabled you allways authenticate against a particular database (by default admin), then connect and use another one.在 MongoDB 中,启用身份验证后,您始终针对特定数据库(默认为管理员)进行身份验证,然后连接并使用另一个数据库。 That's why there are two different properties : authentication-database (to authenticate against) and database (the one to use)这就是为什么有两个不同的属性:authentication-database(进行身份验证)和 database(要使用的属性)

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

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