Reputation: 2534
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.
Upvotes: 6
Views: 3270
Reputation: 4363
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)
Upvotes: 4