6

This is my 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_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.

2
  • Did you try to enable access control? Commented Mar 31, 2020 at 7:51
  • try with spring.data.mongodb.database=admin Commented Mar 31, 2020 at 8:49

1 Answer 1

4

You need to add the following line in your application.properties :

spring.data.mongodb.authentication-database=admin

From docker-hub mongodb readme :

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.

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.

In MongoDB, when authentication is enabled you allways authenticate against a particular database (by default admin), then connect and use another one. That's why there are two different properties : authentication-database (to authenticate against) and database (the one to use)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.