skip to Main Content

I am trying to secure a mongoDB docker container and am stumped by the authentication.
So far, in my docker compose file, I am setting root environment variables, but I am unable to connect to the mongoDB from outside of the container. Without setting auth, I have no such issues.

services:
  mongodb:
    image: mongo:latest
    restart: always
    ports:
      - "27017:27017"
    command: ["--auth"]
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=root

I’ve tried to connect to mongodb://root:root@localhost:27017 using MongoDB Compass tool, but I keep getting authentication errors.

I am assuming that the root user is already created since I am getting authentication errors. I have tried using a script to create a user, but still I could not connect.

2

Answers


  1. Chosen as BEST ANSWER

    The solution I went with was limiting the published ports to the local host. This works fine for my application despite not being able to use set environment variables to get a root user.

    services: 
      mongodb:
        image: mongo:latest
        restart: always
        ports:
          - "127.0.0.1:27017:27017"
    

  2. Try without command: ["--auth"]

    Environment variables that you have provided should already turn this option on. Let me know, if that works.

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