Search code examples
mongodbdocker

MongoDB Authentication Failed in Docker using MongoDB Compass


I struggled here for many hours but was still stuck. I am trying to set up a MongoDB Docker container to use as a local database and use MongoDB Compass to connect. Here is my docker-compose file

  mongodb:
    container_name: ms_mongo_db
    image: mongo
    ports:
      - 27017:27017
    volumes:
      - mongo:/data
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=password

When my container runs successfully, I try to connect with this URL: mongodb://root:password@localhost:27017/?authSource=admin but MongoDbCompass keeps saying authentication failed, although my username and password are correct. I have read many problems others but still don't fix my issue. Can anyone know what the problem is? Thank you for reading my problem. Silly me if there is any mistake


Solution

  • By default, none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup.

    MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD
    

    So, you need to login in with the user and password stored in the volume or deploy without using the volume.

      mongodb:
        container_name: ms_mongo_db
        image: mongo
        ports:
          - 27017:27017
        environment:
          - MONGO_INITDB_ROOT_USERNAME=root
          - MONGO_INITDB_ROOT_PASSWORD=password