Docker compose authentication doesn't register

this is the docker compose file

  mongodb:
    image: mongo:5.0
    container_name: mongo
    environment:
      MONGO_INITDB_DATABASE: test
    ports:
      - 27018:27017
    volumes:
      - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo-js:ro
      - './volumes/mongo:/data/db'

and this is the init script

db.createUser({
  user: 'admin',
  password: 'admin',
  roles: [
    {
      role: 'readWrite',
      db: 'admin',
    },
  ],
});

I tried opening the container with auth but it failed mesrably.it works without auth… coupld someone point out where did I go wrong with this ?

Hi @Ahmed_Elbarqy and welcome to the community!!

In order to enable authentication using the docker-compose.yaml, you would need to perform the following procedure:

  1. Add MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD as parameters to the yaml file:
command: [--auth]
environment:
      - MONGO_INITDB_ROOT_USERNAME=userAdmin
      - MONGO_INITDB_ROOT_PASSWORD=userPassword
  1. Run the docker compose.yaml file using:

docker-compose up -d

  1. Execute the docker-compose.yaml file

docker-compose exec mongodb /bin/sh

  1. Once you are logged in to the MongoDB using mongosh:

mongosh -u userAdmin -p userPassword --authenticationDatabase admin

Once you are logged in using the shell, you can create the user on the required database using the required roles and authentication.

For more information, there are further documentations available regarding the configuration in Docker Hub

If you are still facing issue, please provide the complete step by step process to reproduce the issue with the received error response.

Please note that the official MongoDB image is maintained by docker and not MongoDB.

Thanks
Aasawari