0

I'm trying to get docker-compose to connect to mongodb using Authentication. In the past I've used a URI string containing the username and password, however, when I run docker up it returns MongoError: Authentication failed. Using terminal I can get into the docker container and manually access mongo using the credentials in the uri string, which means the database is running. I'm new to docker. Can someone explain why my URI string doesn't work and how I should fix it.

version: "3.8"
services:
  product-service:
    build:
      context: "."
      dockerfile: "./product-service/Dockerfile"
    container_name: product-service
    depends_on:
      - product-service-db
    ports:
      - "7300:7300"
    volumes:
      - ./product-service:/opt/app
    links:
      - product-service-db
    environment:
      - DB_URI=mongodb://root:example@product-service-db:27017/Products

  product-service-db:
    image: mongo:4.4.2
    restart: always
    ports:
      - "7399:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
bp123
  • 3,217
  • 8
  • 35
  • 74

1 Answers1

4

The solution that works and I'm not sure why, is to add ?authSource=admin to the URI string.

DB_URI=mongodb://root:example@product-service-db:27017/Products?authSource=admin

If anyone is able to give a good explanation as to why this solution works, please feel free to update the answer.

bp123
  • 3,217
  • 8
  • 35
  • 74
  • 1
    Adding `?authSource=admin` works because by default mongo defaults to the `test` database. Most users are created on the `admin` database. This is similar to the java equivalent answer here: https://stackoverflow.com/a/55138982/6281755 – Robert Seaman Dec 09 '20 at 15:09
  • If you're using pymongo `MongoClient` just specify `authSource='the_database',` when you call the class – forgetso Apr 11 '21 at 19:01