skip to Main Content

I can’t connect to mongoDB started in a container when database path is specified. I use mongoDB Compass to test connection – it returns Authentication failed.

The container with mongo is started via docker compose up and here are compose.yaml contents:

services:
  mongo:
    image: mongo
    container_name: "mongo"
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: mongoadmin
      MONGO_INITDB_ROOT_PASSWORD: a12345
    volumes:
      - './db-data/mongodb:/data/db'
    ports:
      - 27017:27017

After starting the container I connect with connection string:

mongodb://mongoadmin:a12345@localhost:27017

then I create db named sampledb. When I modify connection string to point to it directly connection fails:

mongodb://mongoadmin:a12345@localhost:27017/sampledb

(without /sampledb it connects).

Any ideas what am I doing wrong?

3

Answers


  1. Try adding the authSource to the connection string. E.g.,

    mongodb://mongoadmin:a12345@localhost:27017/sampledb?authSource=admin
    
    Login or Signup to reply.
  2. Please use below connection string

    • "mongodb://user:pwd@hostname/myDB?authSource=admin" — authentication database is admin and current database would be myDB
    • "mongodb://user:pwd@hostname?authSource=admin" — authentication database is admin and current database would be the test
    Login or Signup to reply.
  3. It looks like the issue might be related to how the database path is specified in your docker-compose.yaml file. When you mount a volume to the container at ./db-data/mongodb:/data/db, it tells Docker to use the ./db-data/mongodb directory on your host machine as the data directory for the MongoDB container.

    However, when you specify the database name in your connection string (mongodb://mongoadmin:a12345@localhost:27017/sampledb), MongoDB Compass tries to connect to a database named sampledb directly in the MongoDB instance, which may not exist because the data directory is mounted from the host machine.

    To resolve this, you can either create the sampledb database manually after connecting to MongoDB without specifying the database name in the connection string or modify your docker-compose.yaml file to use a different path for the data directory (e.g., /data/db) without the database name in the path. Here’s an updated version of your docker-compose.yaml file:

    services:
    mongo:
    image: mongo
    container_name: "mongo"
    restart: always
    environment:
    MONGO_INITDB_ROOT_USERNAME: mongoadmin
    MONGO_INITDB_ROOT_PASSWORD: a12345
    volumes:
    – ‘./db-data:/data/db’
    ports:
    – 27017:27017

    With this configuration, MongoDB Compass should be able to connect to the MongoDB instance at mongodb://mongoadmin:a12345@localhost:27017/sampledb after you manually create the sampledb database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search