Mongo Auth

MongoDB + Authentication on Docker

3 years ago · 2 min read

Let’s dig around the security of MongoDB that is installed on top of Docker.

To get started using MongoDB using Docker you should pull its docker image and create a new container

$ docker run -it --name my-mongo -p 27017:27017 mongo

This would create a MongoDB container that is accessible from the host OS on port 27017

Tip: Never, ever expose the default port which is 27017 as it’s known and there’s a ton of hackers and bots scanning for these known ports.

Any other random port would be a great choice and a good starting point towards a better security

Till now we can access our MongoDB without password as authentication is disabled by default

1) In order to enable authentication we got to map our data to a volume that would hold authentication and user info until we finish our installation and also persist our data to prevent its loss.

$ docker run -it --name my-mongo -p {YourSecureRandomPortNumber}:27017 -v mongodata:/data/db mongo

2) Enter your MongoDB shell to add your admin user

  • Enter container bash

$ docker exec -ti my-mongo bash

  • Create your admin user

Note: you would be able to login without username/password until you enable authentication

$ mongo


> use admin


> db.createUser(

{

user: "myUserAdmin",

pwd: passwordPrompt(), // or cleartext password

roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]

}

)

3) Now we have added our admin user, let’s enable authentication

  • Terminate your container, don’t worry data is persisted in the volume

$ docker rm -f my-mongo

  • Launch a new container with — auth option supplied

$ docker run -d -p {YourSecureRandomPortNumber}:27017 \

-v mongodata:/data/db --name my-mongo mongo mongod --auth

Now you are all done, and you can connect securely to your database with proper connection string.

  • Using DB Compass:

mongodb://YourUsername:YourPassword@host:port

  • Using Mongoose:

You may encounter problem authentication so you would have to do it as follows:

const mongoose = require('mongoose');


await mongoose.connect('mongodb://host:port/databaseName',{

useNewUrlParser: true,useUnifiedTopology: true,

"auth": { "authSource": "admin" },

"user": "YourUsername",

"pass": "YourPassword"

});

Any edits and comments are welcome, this was a real case and I thought it may be useful to share it so it may help someone.

Suggestions and feedback are welcome with ❤️ at [email protected]