MongoDB Docker Authentication Issue: 'Command insert requires authentication

I’m encountering an authentication issue while trying to use MongoDB via a Docker image. Here are the relevant sections from my configuration files:

application.yml:

springs:
  data:
    mongodb:
      username: cihatsaman
      password: cihatsaman
      host: localhost
      port: 27017
      database: cihatiscoding
      authentication-database: admin

docker-compose.yml:

services:
  mongodb:
    image: mongo
    container_name: mongo_db
    ports:
      - 27017:27017
    volumes:
      - mongo:/data
    environment:
      - MONGO_INITDB_ROOT_USERNAME=cihatsaman
      - MONGO_INITDB_ROOT_PASSWORD=cihatsaman

  mongo_express:
    image: mongo-express
    container_name: mongo_express
    restart: always
    ports:
      - 8081:8081
    environment:
      - ME_CONFIG_MONGODB_ADMIN_USERNAME=cihatsaman
      - ME_CONFIG_MONGODB_ADMIN_PASSWORD=cihatsaman
      - ME_CONFIG_MONGODB_SERVER=mongodb

volumes:
  mongo: {}

The issue arises with the following error message:

Caused by: com.mongodb.MongoCommandException: Command failed with error 13 (Unauthorized): ‘Command insert requires authentication’ on server localhost:27017. The full response is {“ok”: 0.0, “errmsg”: “Command insert requires authentication”, “code”: 13, “codeName”: “Unauthorized”}

I’ve followed the usual steps for setting up authentication in both my application.yml and docker-compose.yml files. Can anyone help me identify the root cause of this authentication error and suggest a solution? Thanks!

Is mongoexpress throwing the error or your application with application.yml? How do you run that application? In a container?

Whenever I run the app, after running the docker-compose.yml file, I encounter that error.

Again:

How do you run that application? In a container?

I am a newbie for Docker. But I will try to explain as much as I can.

I use Docker Compose to start MongoDB and Mongo-Express containers as defined in my docker-compose.yml file. This sets up my database environment in a containerized setup. For the Spring Boot application, which connects to MongoDB, I run it directly on my host machine. I ensure that the application’s configuration matches the MongoDB service’s credentials and port as defined in the Docker setup and the application.yml .

hello,
got the same issue for the same usecase.
any hint ?

I have made two steps that resolved my issue:
1- I have created a user to my database with readwrite access:
example: db.createUser({
user: “admin”,
pwd: “password”,
roles: [
{
role: ‘readWrite’,
db: ‘product-service’
},
],
});

2- added the following property to my springboot application.properties :
spring.data.mongodb.authentication-database=admin

reference: java - Error authentication to MongoDB - Exception authenticating MongoCredential - Stack Overflow