0

I'm following this example of creating a Spring Boot app that connects with a Mongo DB. However, when I run my application I get:

Exception in monitor thread while connecting to server localhost:8081

With the following properties:

spring.data.mongodb.uri=mongodb://root:example@localhost:8081/test

And the following MongoClient:

MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync|spring-boot", "version": "4.8.0"}, "os": {"type": "Linux", "name": "Linux", "architecture": "amd64", "version": "5.15.0-56-generic"}, "platform": "Java/Eclipse Adoptium/17.0.5+8"} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=MongoCredential{mechanism=null, userName='root', source='test', password=<hidden>, mechanismProperties=<hidden>}, streamFactoryFactory=null, commandListeners=[], codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, CollectionCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.Jep395RecordCodecProvider@1b9d9a2b]}, clusterSettings={hosts=[localhost:8081], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName='null', serverSelector='null', clusterListeners='[]', serverSelectionTimeout='30000 ms', localThreshold='30000 ms'}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, sendBufferSize=0}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, sendBufferSize=0}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=[], maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners='[]', serverMonitorListeners='[]'}, sslSettings=SslSettings{enabled=false, invalidHostNameAllowed=false, context=null}, applicationName='null', compressorList=[], uuidRepresentation=JAVA_LEGACY, serverApi=null, autoEncryptionSettings=null, contextProvider=null}

The application is running fine but can't reach the db. I tried several other settings, such as replacing localhost with 127.0.0.1 and declaring settings in separate values such that:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=8081
spring.data.mongodb.database=test
spring.data.mongodb.username=root
spring.data.mongodb.password=example

But nothing seems to work. The Mongo DB dashboard is shown at localhost:8081 so I know that the DB is actually running fine.

This is what I used start a local Mongo DB instance in a Docker container:

# Use root/example as user/password credentials
version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_DATABASE: test
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/
DSteman
  • 1,388
  • 2
  • 12
  • 25
  • Maybe this one? https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb/63755470#63755470 – Wernfried Domscheit Dec 23 '22 at 15:55
  • Thanks for the suggestion but in that question an authentication error is raised. In my case, the whole db can't be found it seems... I tried appending `?authSource=admin` to the URI but no luck. – DSteman Dec 23 '22 at 16:21
  • @DSteman, use `mongosh admin -u root -p example`, `use test`, `db.createUser({user: "root", pwd: "example", roles: ["dbOwner"]})`, details step describe in my answer. I am test Ok. – life888888 Dec 26 '22 at 03:32

2 Answers2

1

Are you using -p 8081:27071 while running your mongo docker container? I guess your config - 8081:8081 should be updated to '- 8081:27071'.

Aakash
  • 2,029
  • 14
  • 22
  • 1
    Actually I made a mistake thinking I had to expose Mongo Express, which is just the admin portal. You are right for suggesting to expose port 27071 on the mongo container. @life888888 explained this quite thoroughly. – DSteman Dec 26 '22 at 11:17
1

Download example code

git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest

goto gs-accessing-mongodb-data-rest/complete

create dir resources under `src/main/

create application.properties

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

MongoDB docker compose

docker-compose.yml

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_DATABASE: test
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

Start MonogoDB

docker compose up

Use mongosh

mongosh admin -u root -p example

In mongosh

use test

db.createUser({user: "root", pwd: "example", roles: ["dbOwner"]})

exit

Run Spring Boot

go to gs-accessing-mongodb-data-rest/complete

mvn clean spring-boot:run

Test

curl -i -X POST -H "Content-Type:application/json" -d "{  \"firstName\" : \"Frodo\",  \"lastName\" : \"Baggins\" }" http://localhost:8080/people

Result

HTTP/1.1 201 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Location: http://localhost:8080/people/63a7cb0249786806453df30d
Content-Type: application/hal+json
Transfer-Encoding: chunked
Date: Sun, 25 Dec 2022 04:01:06 GMT

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/63a7cb0249786806453df30d"
    },
    "person" : {
      "href" : "http://localhost:8080/people/63a7cb0249786806453df30d"
    }
  }
life888888
  • 835
  • 2
  • 2
  • 8
  • Thanks for this elaborate answer. I made a mistake by exposing the port of the mongo express container and not the mongo container... – DSteman Dec 26 '22 at 11:18