Search code examples
mongodbdocker-composemongodb-compass

I can not connect to mongodb container with mongodb compass


Here is my docker-compose file

version: "3.8"
services:

  mongodb:
    image: mongo
    restart: always
    container_name: mongodb_container_gold_jar
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_DATABASE: root
      MONGO_INITDB_ROOT_USERNAME: haolamongodb
      MONGO_INITDB_ROOT_PASSWORD: haolamongodb1210
    volumes:
      # named volumes
      - mongodb_gold_jar:/data/db
      - mongoconfig_gold_jar:/data/configdb

And here is my connection string: mongodb://haolamongodb:haolamongodb1210@127.0.0.1:27017/root.

I also try to use localhost instead of 127.0.0.1 but it still does not work

the error message: enter image description here

I have searched a lot but still got stuck on this, so pls help me figure it out. Thanks


Solution

  • I finally figured it out. My connection string is missing the authenticationDatabase.

    I tried to connect with mongosh and succeeded.

    docker run -it --rm --network server_default mongo \ 
    mongosh --host mongodb_container_gold_jar \
     -u haolamongodb -p haolamongodb1210 --authenticationDatabase admin \
     root
    

    so the connection string should be mongodb://haolamongodb:haolamongodb1210@127.0.0.1:27017/root?authSource=admin