Enable mongodb authentication with docker

(λx.x)eranga
Effectz.AI
Published in
2 min readJul 11, 2018

By default mongodb comes with empty authentication(no users and roles by default). We need to manually create users and roles. Following are the steps to enable authentication on mongodb. In here I’m running mongodb with docker. I have written another post about dockerizeng mongodb in here. Please refer it for find more information about running mongodb on docker.

1. Run mongodb without auth

First we need to run mongodb without enabling auth. Following is the docker-compose configuration to run mongodb with auth. Use dokcer-compose up -d to up mongodb.

mongodb:
image: erangaeb/senzmongodb:0.1
container_name: mongodb
volumes:
['/private/var/services/mongodb:/data/db']
ports:
- 27017:27017

2. Connect to mongodb without auth

Since mongodb auth not enabled yet we can simply connect to mongodb like below.

mongo

3. Create root user

Create admin user with usernameroot and password root in admin database.

use admin
db.createUser(
{
user: "root",
pwd: "root",
roles:["root"]
}
);

4. Create other user

I have a db name senz, so I’m gonna create separate user with read write access for the senz db.

use senz
db.createUser(
{
user: "senz",
pwd: "senz",
roles:[
{
role: "readWrite",
db: "senz"
}
]
}
);

5. Run mongodb with auth

Enable auth in mongodb with --auth flag. Following is the docker-compose config to run mongodb with auth. Use dokcer-compose up -d to up mongodb.

mongodb:
image: erangaeb/senzmongodb:0.1
command: [--auth]
container_name: mongodb
volumes:
['/private/var/services/mongodb:/data/db']
ports:
- 27017:27017

6. Connect to mongodb with auth

Following commands enables to connect mongodb with specifying username, password and authentication database.

mongo -u root -p root --authenticationDatabase admin
mongo -u senz -p senz --authenticationDatabase senz

--

--