Balasubramani M

@balasubramanim

How to install and secure MongoDB in Amazon EC2 in minutes?

In this post, we will be installing MongoDB in Amazon EC2 instance and secure it using authentication mechanism.

One comes to knows the importance of security only when he knows the importance of its job.

It is said to be that over 30% of MongoDB databases and its connections are not secured.

So don’t you want to secure it? Of course, everyone loves to secure whatever they host. Let’s start implementing it.

The steps in the MongoDB site are not enough for a noob to complete the steps successfully. This happened to me personally. After going through almost hundreds of post, I finally decided to document it perfectly because I know Sharing is Caring. If you find any difficulties in this post, feel free to comment. I will try to reply as soon as possible.

I assume you are already aware of Amazon Web services and little knowledge on EC2. If you are not don’t worry. I have created a tutorial about AWS(Amazon Web Services) and EC2 instance setup in the following post. Request you to go through the same.

Let’s install the MongoDB.

Once you are ready with the terminal, let’s start installing MongoDB in it. Since we are going to set up this installation in minutes, I would request you to go through below link in the references section for the below-mentioned command for its detailed usages if you need.

Step 1: Import the public key used by the package management system.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

Step 2: Create a list file for MongoDB. (for Ubuntu 16.04)

echo “deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

Step 3: Reload local package database.

sudo apt-get update

Step 4: Install the MongoDB packages.

sudo apt-get install -y mongodb-org

This will install the latest stable version of MongoDB.

That’s it, We have installed MongoDB latest stable version in our Amazon EC2 instance.

In the following process, We will first create an admin, who generally has root access to your database and then admin will create a user who can be created with specific roles and access to specific databases. Finally, we will be using usercredentials to connect to our database and start working on it.

Let’s start the MongoDB

Step 1: Start MongoDB. Issue the following command to start mongod.

sudo service mongod start

Step 2: Verify that MongoDB has started successfully by typing the following command,

cat /var/log/mongodb/mongod.log

and ensure you find the below line at the last.

[initandlisten] waiting for connections on port 27017

That’s it. You are successfully running MongoDB instance in your remote instance right now.

Note: Issue the following command to stop mongod (Don’t execute till needed)

sudo service mongod stop

Note: Issue the following command to restart mongod(Don’t execute till needed)

sudo service mongod restart

It’s time to secure your MongoDB.

Enabling access control on a MongoDB deployment enforces authentication, requiring users to identify themselves. When accessing a MongoDB deployment that has access control enabled, users can only perform actions as determined by their roles.

The following procedure first adds a user administrator to a MongoDB instance running without access control and then enables access control.

Access Control? — Yes, when you run the MongoDB with AccessControl, you are saying, Start secure MongoDB instance.

admin — This user can administrate user and roles such as: create users, grant or revoke roles from users, and create or modify customs roles.

Procedure

Step 1: Create a directory to store data and set permission to it.

//Creating a path to store DB data.
sudo mkdir -p /data/db
//Giving yourself permission to write in that folder.

sudo chown $USER /data/db

If you have any difficulties in setting up this folder and permission, you may refer to this StackOverflow link.

Step 2: Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

Step 3: Let the MongoDB instance run on this terminal instance. Now let’s work on another remote terminal instance (Say Terminal 2) so that we will be switching to and fro after creating a user and to restart Mongo instance.

Open a new terminal and connect to your EC2 instance. Now we will be working on Mongo Shell which is used to run commands or queries in your created database.

Now we are going to create Mongo Shell by issuing the below command.

mongo --port 27017

Now your terminal will look like a below image, which is ready to run commands in it.

Mongo Shell

Step 4: Create the user administrator (admin)

In the admin database, add a user with the userAdminAnyDatabase role. This database acts as admin DB where we creating it only for authentication purpose.

Issue the following command to switch to admin DB even though you haven’t created it. It will be created automatically when you issue the command.

use admin

After switching to admin DB, let’s create an admin by issuing the following command.

db.createUser({user: "admin", pwd: "adminUser123", roles: [{role: "userAdminAnyDatabase", db: "admin"}]})

Which is prettified as, (Above prettified command, do not run twice)

db.createUser(
{
user: “admin”,
pwd: “adminUser123”,
roles: [ { role: “userAdminAnyDatabase”, db: “admin” } ]
}
)

Now you have created an user called admin with userAdminAnyDatabase role.

Disconnect the mongo shell by pressing Ctrl+C.

Step 5: Switch back to an old mongod instance (Terminal 1) where it is running. Let’s restart the MongoDB instance with access control to gain admin access to our databases. Remember, you are starting your Mongo instance with access control now.

Re-start the mongod instance with the --auth command line option.

mongod --auth --port 27017 --dbpath /data/db

Step 6: Switch back to Terminal 2 (mongo shell instance).

Connect and authenticate as the user administrator by issuing the below command.

mongo --port 27017 -u "admin" -p "adminUser123" --authenticationDatabase "admin"

Step 7: Create additional users (user) as needed for your deployment.

Once authenticated as the user administrator, use db.createUser() to create additional users. You can assign any built-in roles or user-defined roles to the users. The following operation adds a user myTester to the test database who has a readWrite role in the test database

Issue the following command to create a database called test and use it.

use test

Now let’s create a user in this database, assigning specific roles to her/him.

db.createUser({user: "user", pwd: "user123", roles: [{role: "readWrite", db: "test"}]})

Which is prettified as, (Above prettified command, do not run twice)

db.createUser(
{
user: "user",
pwd: "user123",
roles: [ { role: "readWrite", db: "test" } ]
}
)

Now you have successfully created a user with specific roles and access to database.

Step 8: Connect and authenticate as a user now.

Now, connect to the instance with the user role by issuing the following command in the same Mongo Shell.

mongo --port 27017 -u "user" -p "user123" --authenticationDatabase "test"

You are now securely authenticated as a user to the database called test. If you want to perform some query operations, you can issue the below command and test now.

db.foo.insert( { x: 1, y: 1 } )

Which creates a collection called foo and insert a aforementioned JSON in it.

Connect via Mongo URI connection string.

Below given the connection string needed to connect to this instance securely from your Node.js server, using mongoose module.

mongodb://user:user123@localhost:27017/test

Yes. You have installed and configured your MongoDB securely in your remote server. Let’s take a break for a while.

In the next tutorial, let us use Docker and create an image and automate all this process so that just a Docker image is required to install and secure MongoDB in any instance in a single command.

Thank you.

More by Balasubramani M

Topics of interest

More Related Stories