Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB with Docker Authentication

I have set up a docker with MongoDB Image. By default it has no password set up. I made a user and assigned it roles, which works perfectly well. But the issue is that the connection is still possible without authentication.

  1. Connect with Authentication > Right Username, Right Password -> CONNECTED

  2. Connect with Authentication > Right Username, Wrong Password -> CONNECTION FAILED

  3. Connection without Authentication > CONNECTED

I want the 3rd point to stop working.

like image 389
Aqib Bangash Avatar asked Feb 05 '23 02:02

Aqib Bangash


1 Answers

Steps:-

1) Run a docker instance without authentication


    $ docker run --name container-name -d -p 27017:27017 -v ~/mongodb:/data/db mongo

2) Create a main administrator user with admin roles


    $ mongo --port 27017
    $ use admin;
    $ db.createUser({user: "adminUserName",pwd: "adminPassword",roles: [{ role: "userAdminAnyDatabase", db: "admin" }})

This will create a user in the admin database with roles "userAdminAnyDatabase". This is like a superuser.

3) Create User for a particular database


    $ use 
    $ db.createUser({user: "dev-read-username",pwd: "dev-read-password",roles:["read"]})  
    -- User with "read" role

    $ db.createUser({user: "dev-write-username",pwd: "dev-write-password",roles:["readWrite"]}) 
    -- User with "readWrite" role

For list of roles available or how to create custom roles, please check https://docs.mongodb.com/manual/reference/built-in-roles/

4) Remove the docker container


    $ docker ps -a
    $ docker stop container_id
    $ docker rm container_id

5) Run the docker instance with authentication enabled


    $ docker run --name container-name -d -p 27017:27017 -v ~/mongodb:/data/db mongo --auth

I assume you might not have started the docker container with --auth enabled. Once you start with --auth enabled, then you will not be able to connect without credentials.

like image 120
Akshay Mehta Avatar answered Feb 08 '23 08:02

Akshay Mehta