We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Learn how to – Install MongoDB 5.0 on CentOS 8/7 & RHEL 8/7

Learn how to – Install MongoDB 5.0 on CentOS 8/7 & RHEL 8/7.

In this guide we will perform an installation of MongoDB 5.0 on CentOS 8/7 & RHEL 8/7. MongoDB is a general-purpose, object-oriented, simple, and dynamic NoSQL database server used in developing modern dynamic apps. This implies that data objects are stored as separate documents in a collection unlike in traditional relational databases where rows and columns are used. MongoDB is written in C++ for massive scalability and flexibility which offers easy querying and indexing for developers.

MongoDB offers both Community and Enterprise editions. The Community Edition is free for download while the Enterprise Edition is part of the Mongo Enterprise Advanced subscription. The Enterprise version has more features such as LDAP, Kerberos support, on-disk encryption, and auditing. Also, it includes comprehensive support for MongoDB development.

MongoDB is available for Windows, macOS, and Linux Operating Systems and is supported by both 32 and 64-bit architectures. MongoDB 5.0 is the latest release version released on July 13, 2021. It has the following new features:

  1. Live Resharding
  2. Native time-series features for efficiently storing sequences of measurements over a period of time
  3. Multi cloud-security tools
  4. The Versioned API future-proofs your applications.
  5. Serverless database on MongoDB Atlas
  6. Seamless data redistribution

Install MongoDB 5.0 on CentOS 8/7 & RHEL 8/7 Linux systems

In this guide, we will walk through the installation of MongoDB 5.0 on CentOS 8/7 & RHEL 8/7 using the below steps.

Step 1: Configure MongoDB YUM repository on CentOS 8/7 & RHEL 8/7

We need to create a /etc/yum.repos.d/mongodb-org-5.0.repo file to enable us install MongoDB 5.0 using the yum command.

sudo tee /etc/yum.repos.d/mongodb-org-5.0.repo<<EOF
[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
EOF

Alternatively, one can download and install the .rpm file directly from the MongoDB repository. On the page, downloads are organized by the RedHat / CentOS version. Download the package for your distribution and architecture.

Step 2: Install MongoDB 5.0 Packages on CentOS 8/7 & RHEL 8/7

The latest version can now be downloaded since the repositories have been added successfully. Install the latest version of MongoDB on CentOS 8/7 & RHEL 8/7 using the below command:

sudo yum install mongodb-org

Dependency Tree:

Dependencies Resolved

======================================================================================================================================================================================================
 Package                                                       Arch                                Version                                         Repository                                    Size
======================================================================================================================================================================================================
Installing:
 mongodb-org                                                   x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                              6.1 k
Installing for dependencies:
 cyrus-sasl                                                    x86_64                              2.1.26-24.el7_9                                 updates                                       88 k
 cyrus-sasl-gssapi                                             x86_64                              2.1.26-24.el7_9                                 updates                                       41 k
 cyrus-sasl-plain                                              x86_64                              2.1.26-24.el7_9                                 updates                                       39 k
 mongodb-database-tools                                        x86_64                              100.5.2-1                                       mongodb-org-5.0                               47 M
 mongodb-mongosh                                               x86_64                              1.5.0-1.el8                                     mongodb-org-5.0                               41 M
 mongodb-org-database                                          x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                              6.2 k
 mongodb-org-database-tools-extra                              x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                               11 k
 mongodb-org-mongos                                            x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                               20 M
 mongodb-org-server                                            x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                               28 M
 mongodb-org-shell                                             x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                               15 M
 mongodb-org-tools                                             x86_64                              5.0.9-1.el7                                     mongodb-org-5.0                              6.1 k
Updating for dependencies:
 cyrus-sasl-lib                                                x86_64                              2.1.26-24.el7_9                                 updates                                      156 k

Transaction Summary
======================================================================================================================================================================================================
Install  1 Package  (+11 Dependent packages)
Upgrade             (  1 Dependent package)

Total download size: 151 M
Is this ok [y/d/N]: y

Allow GPG key importation.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                  64 MB/s | 151 MB  00:00:02
Retrieving key from https://www.mongodb.org/static/pgp/server-5.0.asc
Importing GPG key 0xE2C63C11:
 Userid     : "MongoDB 5.0 Release Signing Key <packaging@mongodb.com>"
 Fingerprint: f567 9a22 2c64 7c87 527c 2f8c b00a 0bd1 e2c6 3c11
 From       : https://www.mongodb.org/static/pgp/server-5.0.asc
Is this ok [y/N]: y
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-9.2009.1.el7.centos.x86_64 (installed)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Is this ok [y/N]: y

Alternatively, you can install a specific version of MongoDB let’s say version 5.0.x by appending the version number to the package name and specify each component individually as below.

sudo yum install -y mongodb-org-<version> mongodb-org-database-<version> mongodb-org-server-<version> mongodb-org-shell-<version> mongodb-org-mongos-<version> mongodb-org-tools-<version>

Check the installed MongoDB version.

$ mongod --version
db version v5.0.9
Build Info: {
    "version": "5.0.9",
    "gitVersion": "6f7dae919422dcd7f4892c10ff20cdc721ad00e6",
    "openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "rhel70",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

Configure MongoDB on CentOS 8/7 & RHEL 8/7

With MongoDB successfully installed, we now need to make a few configurations.

1. Start and Enable Service.

First, we need to start and enable the mongod service as below:

sudo systemctl start mongod
sudo systemctl enable mongod

Check the status of the service:

$ systemctl status mongod
mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2021-08-25 06:36:08 EDT; 9s ago
     Docs: https://docs.mongodb.org/manual
  Process: 8883 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 8881 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 8879 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 8877 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
 Main PID: 8886 (mongod)
   CGroup: /system.slice/mongod.service
           └─8886 /usr/bin/mongod -f /etc/mongod.conf

Aug 25 06:36:04 rhellab systemd[1]: Stopped MongoDB Database Server.
Aug 25 06:36:04 rhellab systemd[1]: Starting MongoDB Database Server...
Aug 25 06:36:04 rhellab mongod[8883]: about to fork child process, waiting until server is ready for connections.
Aug 25 06:36:04 rhellab mongod[8883]: forked process: 8886
Aug 25 06:36:08 rhellab systemd[1]: Started MongoDB Database Server.

2. Secure MongoDB instance

After installation, the MongoDB database has no password and one can easily access it.

sudo vi /etc/mongod.conf

In the conf file, find and uncomment #Security line and add the below content appropriately. Remember the syntax is very important in this file.

security:
  authorization: enabled

Restart the service for changes to apply.

sudo systemctl restart mongod

Using MongoDB 5.0 on CentOS 8/7 & RHEL 8/7.

MongoDB listens on port 27017 by default. You can access the MongoDB shell from the localhost using the code:

$ mongo

Sample Output:

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("3aab3c08-01c9-4896-acf6-44d6466a58a3") }
MongoDB server version: v5.0.9
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
> 

While in the shell, there are a number of activities you can do such as:

1. Create a User and Add Role in MongoDB

Here we will create a user and give them admin roles. We will create and use the db “admin

use admin
db.createUser(
{
user: "mongouser",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)

Set the password for the user.

Now exit the shell using.

> exit
bye

Then login to the created user now.

mongo -u mongouser -p --authenticationDatabase admin

Enter the set password above and proceed.

2. List databases in MongDB

To list existing databases use the command:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

3. Create a database in MongoDB.

A new database in MongoDB is created by simply switching to a non-existing database and specify the name of the database. Let’s create a database named mongotestdb.

use admin

Sample Output:

> use admin
switched to db admin
> 

4. Create a collection in MongoDB

With the database created, we can now add data to it. Below, we are creating a table for the user details.

db.userdetails.insertOne(
   {F_Name: "fist name",
    L_NAME: "last name",
    ID_NO: "12345",
     AGE: "49",
     TEL: "+254654671"
   }
)

Show the created table/collection

show collections

Sample Output:

> show collections
system.users
system.version
userdetails
> 

5. Create a User with read and write privileges.

To create a user with read and write privileges in MongoDB use the syntax in the below commands:

use testdatabase
db.createUser(
   {
     user: 'testuser',
     pwd: 'P@ssWord',
     roles: [ { role: 'readWrite', db: 'testdatabase' } ]
   }
 );

Change MongoDB default Path on CentOS 8/7 & RHEL 8/7.

MongoDB stores its data in the default path in /var/lib/mongo. You can set MongoDB to store data in a custom path as shown below.

First, stop the service:

sudo systemctl stop mongod.service

Then create a new custom path to use to store MongoDB data.

sudo mkdir -p /data/mongo

Set the owner of the directory to mongod as below.

sudo chown -R mongod:mongod /data/mongo

Then modify /etc/mongod.conf to accommodate the new directories.

sudo vi /etc/mongod.conf

Edit the paths in the file as below.

path: /data/log/mongodb/mongod.log   #where to write logging data.
dbPath: /data/mongo    #Where and how to store data.
pidFilePath: /data/mongodb/mongod.pid  # location of pidfile

Configure SELinux and its enforcing mode since the path has been changed. Without configuring SELinux, it will not allow MongoDB to access /sys/fs/cgroup.

First, install checkpolicy.

sudo yum install checkpolicy
####OR###
sudo yum install policycoreutils-python

Create a new check policy with the information as below.

cat > mongodb_cgroup_memory.te <<EOF
module mongodb_cgroup_memory 1.0;

require {
    type cgroup_t;
    type mongod_t;
    class dir search;
    class file { getattr open read };
}

#============= mongod_t ==============
allow mongod_t cgroup_t:dir search;
allow mongod_t cgroup_t:file { getattr open read };
EOF

Then compile and load the policy created above.

checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
sudo semodule -i mongodb_cgroup_memory.pp

Now a new check policy has been compiled, load the 3 directories as below:

1. Log File Directory

Run the commands below to update files and directory contexts:

sudo semanage fcontext -a -t mongod_log_t '/data/log/mongodb/mongod.*'
sudo chcon -Rv -u system_u -t mongod_log_t '/data/log/mongodb/mongod.log'
sudo restorecon -R -v '/data/log/mongodb/mongod.log'

2. Data Directory

For data directory apply as below:

sudo semanage fcontext -a -t mongod_var_lib_t '/data/mongo.*'
sudo chcon -Rv -u system_u -t mongod_var_lib_t '/data/mongo'
sudo restorecon -R -v '/data/mongo'

3. PID Directory

Same applies to updating pod directories.

semanage fcontext -a -t mongod_var_run_t '/data/mongodb/mongod.*'
chcon -Rv -u system_u -t mongod_var_run_t '/data/mongodb/mongod.pid'
restorecon -R -v '/data/mongodb/mongod.pid'

Update the firewall and Iptables

For Firewalld use:

sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload

For those using Iptables:

sudo iptables -A INPUT -p tcp --dport 27017 -j ACCEPT
sudo iptables-save | grep 27017

Reload and start Mongod daemon as below.

sudo systemctl daemon-reload
sudo systemctl start mongod.service

In case MongoDB fails to reload and start it using:

sudo systemctl daemon-reload
sudo systemctl start mongod

Next reading:

That is it! We have concluded this guide on how to install MongoDB 5.0 on CentOS 8/7 & RHEL 8/7 Linux machine. we have also seen how to create users with roles, add databases to MongoDB e.t.c. I hope you found this guide helpful.

See more guides:

MongoDB Udemy Video courses

Cart

Your Cart is Empty

Back To Shop