How to install and setup MongoDB 4 on CentOS 7.6

#helpful #centos #development #tutorial #text #written #mongodb

In this tutorial I will explain how you can install and setup a Mongo Database with some options of how to connect to it.

Make sure you are on CentOS or similar, for this tutorial I was using CentOS 7.6 and a user with sudo privileges connected over SSH.

First of all we need to add the MongoDB repository to yum to install it. Start by creating this file.

# sudo vi /etc/yum.repos.d/mongodb-org-4.0.repo

Then inside paste the following: (if you are new to vi just hit the i key to enter edit mode)

[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

Then save and quit vi. (hit the esc key and type :wq and hit enter)

Next up we'll start the installation. And then start mongo and make sure it start automatically if you server is restarted.

# sudo yum install mongodb-org
# sudo systemctl start mongod
# sudo systemctl enable mongod

Done! Mongo installed and you can now start using it.
Now you can try to enter the mongo shell.

# mongo

In the shell you will most likely be greeted with three warnings. One is for unrestricted access, one for Transparent Huge Pages and one for something with defrag. The first warning is obvious while the two others are a bit obscure, but disabling Transparent Huge Pages and defrag Mongo should perform better. But if you don't care, leave it like this and enjoy Mongo! :)

If you however want to remove the warnings, continue.

Disable Transparent Huge pages and defrag

Lets start with adding a new script file.

# sudo vi /etc/init.d/disable-transparent-hugepages

Insert the following:

#!/bin/bash
### BEGIN INIT INFO
# Provides:          disable-transparent-hugepages
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    mongod mongodb-mms-automation-agent
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Disable Linux transparent huge pages
# Description:       Disable Linux transparent huge pages, to improve
#                    database performance.
### END INIT INFO

case $1 in
  start)
    if [ -d /sys/kernel/mm/transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/transparent_hugepage
    elif [ -d /sys/kernel/mm/redhat_transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/redhat_transparent_hugepage
    else
      return 0
    fi

    echo 'never' > ${thp_path}/enabled
    echo 'never' > ${thp_path}/defrag

    re='^[0-1]+$'
    if [[ $(cat ${thp_path}/khugepaged/defrag) =~ $re ]]
    then
      # RHEL 7
      echo 0  > ${thp_path}/khugepaged/defrag
    else
      # RHEL 6
      echo 'no' > ${thp_path}/khugepaged/defrag
    fi

    unset re
    unset thp_path
    ;;
esac

Save and quit.
Next we need to make this script executable Make it executable and add it as a start script.

# sudo chmod 755 /etc/init.d/disable-transparent-hugepages
# sudo chkconfig --add disable-transparent-hugepages

CentOS 7.6 comes with an app called Tuned which automatically tunes the performance of your system. What we need to do is to make sure Tuned doesn't re-enable Transparent Huge Pages. Just do the following

# sudo mkdir /etc/tuned/no-thp
# sudo tuned-adm profile no-thp

At this point I needed to restart my server for the changes to take effect.

Once restarted check that it worked.

# cat /sys/kernel/mm/transparent_hugepage/enabled
# cat /sys/kernel/mm/transparent_hugepage/defrag

These two lines should output three words where the word never is selected.

Add authentication to Mongo

Enter the mongo shell and switch to the admin database.

# mongo
use admin

Here we'll create an admin user for mongo, change the username and password to what you want and paste it in the mongo shell.

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

Then type exit to leave the shell.
Next we'll change the Mongo config.

# sudo vi /etc/mongod.conf

And close to the bottom there you should see security:, add authorization enabled there so it looks like this.

security:
  authorization: "enabled"

Save and exit. And restart Mongo.

# sudo systemctl restart mongod

Then try to login to the mongo shell using your new admin account.

# mongo -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

Create a database with a user

As the admin user inside the mongo shell type use and the name of the database you want to create.

use testdb

Inside of testdb we will then create a test user.

db.createUser({user:"testuser",pwd:"testpwd",roles:[{role:"readWrite",db:"test"},{role:"read",db:"reporting"}]})

Then exit the shell and try to enter it again with your new user.

# mongo -u "testuser" -p "testpwd" --authenticationDatabase "testdb"

Connect to your MongoDB

Depending on how you want to use and mange your database there are some more things you can to set it up.

If you want to connect to the db from an app running locally on your server you just need to connect to localhost and port 27017. This is the most secure way. And you can connect to your database to manually edit the content using Compass.

To connect to your db with compass you have to use your ssh connection. Download compass and connect like this.

Hostname: localhost
Port: 27017
Authentication: Username & Password
Username: testuser
Password: testpwd
Authentication database: testdb
SSH Tunnel: Either password or certificate depending on your setup

If you instead want to connect to the db from outside your server you can open up the mongodb port in your firewall, allow mongo to listen to connections from ip's other than localhost, and enable the mongo port in SELinux. Much less secure than only letting localhost connect to it. For this, do the following:

# sudo semanage port -a -t mongod_port_t -p tcp 27017
# sudo firewall-cmd --zone=public --permanent --add-port=27017/tcp
# sudo firewall-cmd --reload
# sudo firewall-cmd --list-all

This will enable the port in SELinux if it isn't already and open up the port for traffic in the firewall. The last command will show you that the part you just added is listed as an open port.
Next we have to tell mongo to allow connections from any ip address.

# sudo vi /etc/mongod.conf

Make the net section look similar to this. Making sure the bindIp setting is set to 0.0.0.0.

net:
  port: 27017
  bindIp: 0.0.0.0 

Save and exit. And restart Mongo.

# sudo systemctl restart mongod

And there we go. If you use compass, you should not be able to connect to mongo without ssh. In the hostname field, just type your domain name or ip of server and connect.