Search code examples
mongodbspring-bootdockerdocker-composedockerfile

Authentication failed while connecting to docker-compose mongodb via springboot application


docker-compose.yml

version: '4'
services:
  mongodb:
    image: mongo:7.0.5
    container_name: mongodb
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: product-service
    volumes:
      - ./data:/data/db

application.properties

spring.application.name=product-service
spring.data.mongodb.uri=mongodb://root:password@localhost:27017/product-service?authSource=admin

While I debug my code I get the expected result but just couldn't connect to docker mongodb. When I tried to execute the application I get

com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}

Solution

  • To resolve the authentication issue, you need to set up a MongoDB initialization script to create a user with the necessary roles.

    the file looks like this :

    db.createUser(
            {
                user: "root",
                pwd: "password",
                roles: [
                    {
                        role: "readWrite",
                        db: "product-service"
                    }
                ]
            }
    );
    

    then you need to Modify your docker-compose.yml file to mount the script into the MongoDB container. You should take a look here : How to create a DB for MongoDB container on start up?