1

First of all this is my first time asking a question on stackoverflow and English is not my native language. Sorry in advence if there are any mistakes. I'm creating a rest-api with language go and using docker image of mongodb as my database. My docker-compose.yaml file is like this:

version: '3'
services:
  db:
    image: mongo
    container_name: mongo
    restart: always
    ports:
      - '27017:27017'
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
    volumes:
      - ./data/db:/data/db
  api:
    build : .
    container_name: restapi
    restart: always
    ports:
      - '8080:8080'
    environment:
      MONGO_URI: mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@localhost:27017/?authSource=admin
    depends_on:
      - db

I set my variables as an .env file. When I run docker compose up -d --build command it creates 2 containers which named mongo and restapi respectively. But when i try to access my database using command docker exec -it mongo mongosh and use admin and then show collections it gives me this error:

"MongoServerError: not authorized on admin to execute command { > listCollections: 1, filter: {}, cursor: {}, nameOnly: true, > authorizedCollections: false, lsid: { id: > UUID("d02d6b74-0f09-4cee-8c08-b2842b1dc6b2") }, $db: "admin", > $readPreference: { mode: "primaryPreferred" } }"

After that i tried use admin and db.auth('myusername','mypassword') Even though my username and password are correct it's just says: MongoServerError: Authentication failed.

I really tried nearly everything and now i'm stuck. Every help will be appreciated

0 Answers0