How to Install MongoDB on CentOS 8 - CentLinux

Latest

Tuesday, 14 April 2020

How to Install MongoDB on CentOS 8

Install MongoDB on CentOS Server

MongoDB is an open-source document-oriented NoSQL database management system. In this article, you will learn how to install MongoDB on CentOS 8 server.

 

This Article Provides:

 

What is MongoDB? :

MongoDB is an open-source, cross-platform, document oriented database management system. MongoDB is a NoSQL (Not Only SQL) database software. MongoDB uses JSON (JavaScript Object Notation) like documents with schema. MongoDB is developed by MongoDB Inc and distributed under SSPL (Server Side Public License).

Although, we are installing MongoDB 4.2 on CentOS 8, but the same procedure will work for CentOS 7, RHEL 7, RHEL 8 and similar distros.

 

Environment Specification:

We are using a minimal installed CentOS 8 virtual machine with following specifications.

  • CPU - 3.4 Ghz (2 cores)
  • Memory - 2 GB
  • Storage - 20 GB
  • Operating System - CentOS 8.0
  • Hostname – mongodb-01.centlinux.com
  • IP Address - 192.168.116.206 /24

 

Install MongoDB Yum Repository in CentOS 8:

We can download our required installation package from MongoDB download page.

01-install-mongodb-on-centos-server-download

Here, you can choose your desired MongoDB release and the target operating system and the website will provide you a download link to the respective installation package. You can then download that RPM package and install it on CentOS 8 server by using dnf command.

But, there is a better way to install MongoDB on CentOS 8 server i.e. by installing MongoDB official yum repository in CentOS 8 and then install the MongoDB by using the dnf command, and we are using the same approach in this installation guide.

Connect with mongodb-01.centlinux.com as root user by using a ssh client.

Create a repo file in /etc/yum.repo.d directory to install MongoDB yum repository in CentOS 8 server.

[root@mongodb-01 ~]# vi /etc/yum.repos.d/mongodb-org-4.2.repo

And add following configurations in this file.

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

Build cache for MongoDB yum repository.

[root@mongodb-01 ~]# yum makecache
CentOS-8 - AppStream                            6.0 kB/s | 4.3 kB     00:00
CentOS-8 - Base                                 5.7 kB/s | 3.8 kB     00:00
CentOS-8 - Extras                               2.9 kB/s | 1.5 kB     00:00
MongoDB Repository                              4.7 kB/s | 6.6 kB     00:01
Metadata cache created.

We have installed the MongoDB yum repository in CentOS 8 server.

 

Set Resource Limits for MongoDB in CentOS 8:

We need to set the resource limits in our CentOS 8 server as required by the MongoDB software.

For this purpotse, create a resource limit configuration file for MongoDB as follows.

[root@mongodb-01 ~]# vi /etc/security/limits.d/mongod.conf

And add the following resource limits therein.

mongod soft nproc 64000
mongod hard nproc 64000
mongod soft nofile 64000
mongod hard nofile 64000

 

Installing MongoDB Database on CentOS 8:

Now, we can install MongoDB on CentOS 8 server from the newly added yum repository.

We are installing latest stable release of MongoDB server by using following dnf command.

[root@mongodb-01 ~]# dnf install -y mongodb-org
Last metadata expiration check: 0:08:43 ago on Mon 13 Apr 2020 12:02:47 PM PKT.
Dependencies resolved.
================================================================================
 Package           Arch   Version                               Repo       Size
================================================================================
Installing:
 mongodb-org       x86_64 4.2.5-1.el8                           mongodb-org-4.2
                                                                           10 k
Installing dependencies:
 python2           x86_64 2.7.16-12.module_el8.1.0+219+cf9e6ac9 AppStream 109 k
 python2-libs      x86_64 2.7.16-12.module_el8.1.0+219+cf9e6ac9 AppStream 6.0 M
 python2-pip-wheel noarch 9.0.3-14.module_el8.1.0+219+cf9e6ac9  AppStream 1.2 M
 python2-setuptools-wheel
                   noarch 39.0.1-11.module_el8.1.0+219+cf9e6ac9 AppStream 289 k
 mongodb-org-mongos
                   x86_64 4.2.5-1.el8                           mongodb-org-4.2
                                                                           15 M
 mongodb-org-server
                   x86_64 4.2.5-1.el8                           mongodb-org-4.2
                                                                           25 M
 mongodb-org-shell x86_64 4.2.5-1.el8                           mongodb-org-4.2
                                                                           17 M
 mongodb-org-tools x86_64 4.2.5-1.el8                           mongodb-org-4.2
                                                                           62 M
Installing weak dependencies:
 python2-pip       noarch 9.0.3-14.module_el8.1.0+219+cf9e6ac9  AppStream 2.0 M
 python2-setuptools
                   noarch 39.0.1-11.module_el8.1.0+219+cf9e6ac9 AppStream 643 k
Enabling module streams:
 python27                 2.7

Transaction Summary
================================================================================
Install  11 Packages

Total download size: 129 M
Installed size: 321 M
Downloading Packages:
(1/11): python2-2.7.16-12.module_el8.1.0+219+cf 254 kB/s | 109 kB     00:00
(2/11): python2-pip-wheel-9.0.3-14.module_el8.1 296 kB/s | 1.2 MB     00:04
(3/11): python2-setuptools-39.0.1-11.module_el8 310 kB/s | 643 kB     00:02
(4/11): python2-pip-9.0.3-14.module_el8.1.0+219 284 kB/s | 2.0 MB     00:07
(5/11): python2-setuptools-wheel-39.0.1-11.modu 393 kB/s | 289 kB     00:00
(6/11): mongodb-org-4.2.5-1.el8.x86_64.rpm      5.5 kB/s |  10 kB     00:01
(7/11): python2-libs-2.7.16-12.module_el8.1.0+2 349 kB/s | 6.0 MB     00:17
(8/11): mongodb-org-mongos-4.2.5-1.el8.x86_64.r 262 kB/s |  15 MB     00:56
(9/11): mongodb-org-shell-4.2.5-1.el8.x86_64.rp 240 kB/s |  17 MB     01:11
(10/11): mongodb-org-server-4.2.5-1.el8.x86_64. 265 kB/s |  25 MB     01:38
(11/11): mongodb-org-tools-4.2.5-1.el8.x86_64.r 561 kB/s |  62 MB     01:53
--------------------------------------------------------------------------------
Total                                           742 kB/s | 129 MB     02:57
warning: /var/cache/dnf/mongodb-org-4.2-fddc3ec541fac48b/packages/mongodb-org-4.2.5-1.el8.x86_64.rpm: Header V3 RSA/SHA1 Signature, key ID 058f8b6b: NOKEY
MongoDB Repository                              1.5 kB/s | 1.7 kB     00:01
Importing GPG key 0x058F8B6B:
 Userid     : "MongoDB 4.2 Release Signing Key <packaging@mongodb.com>"
 Fingerprint: E162 F504 A20C DF15 827F 718D 4B7C 549A 058F 8B6B
 From       : https://www.mongodb.org/static/pgp/server-4.2.asc
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1
  Installing       : mongodb-org-tools-4.2.5-1.el8.x86_64                  1/11
  Installing       : mongodb-org-shell-4.2.5-1.el8.x86_64                  2/11
  Installing       : mongodb-org-mongos-4.2.5-1.el8.x86_64                 3/11
  Installing       : python2-setuptools-wheel-39.0.1-11.module_el8.1.0+    4/11
  Installing       : python2-pip-wheel-9.0.3-14.module_el8.1.0+219+cf9e    5/11
  Installing       : python2-libs-2.7.16-12.module_el8.1.0+219+cf9e6ac9    6/11
  Installing       : python2-pip-9.0.3-14.module_el8.1.0+219+cf9e6ac9.n    7/11
  Installing       : python2-setuptools-39.0.1-11.module_el8.1.0+219+cf    8/11
  Installing       : python2-2.7.16-12.module_el8.1.0+219+cf9e6ac9.x86_    9/11
  Running scriptlet: python2-2.7.16-12.module_el8.1.0+219+cf9e6ac9.x86_    9/11
  Running scriptlet: mongodb-org-server-4.2.5-1.el8.x86_64                10/11
  Installing       : mongodb-org-server-4.2.5-1.el8.x86_64                10/11
  Running scriptlet: mongodb-org-server-4.2.5-1.el8.x86_64                10/11
Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service â /usr/lib/systemd/system/mongod.service.

  Installing       : mongodb-org-4.2.5-1.el8.x86_64                       11/11
  Running scriptlet: mongodb-org-4.2.5-1.el8.x86_64                       11/11
  Verifying        : python2-2.7.16-12.module_el8.1.0+219+cf9e6ac9.x86_    1/11
  Verifying        : python2-libs-2.7.16-12.module_el8.1.0+219+cf9e6ac9    2/11
  Verifying        : python2-pip-9.0.3-14.module_el8.1.0+219+cf9e6ac9.n    3/11
  Verifying        : python2-pip-wheel-9.0.3-14.module_el8.1.0+219+cf9e    4/11
  Verifying        : python2-setuptools-39.0.1-11.module_el8.1.0+219+cf    5/11
  Verifying        : python2-setuptools-wheel-39.0.1-11.module_el8.1.0+    6/11
  Verifying        : mongodb-org-4.2.5-1.el8.x86_64                        7/11
  Verifying        : mongodb-org-mongos-4.2.5-1.el8.x86_64                 8/11
  Verifying        : mongodb-org-server-4.2.5-1.el8.x86_64                 9/11
  Verifying        : mongodb-org-shell-4.2.5-1.el8.x86_64                 10/11
  Verifying        : mongodb-org-tools-4.2.5-1.el8.x86_64                 11/11

Installed:
  mongodb-org-4.2.5-1.el8.x86_64
  python2-pip-9.0.3-14.module_el8.1.0+219+cf9e6ac9.noarch
  python2-setuptools-39.0.1-11.module_el8.1.0+219+cf9e6ac9.noarch
  python2-2.7.16-12.module_el8.1.0+219+cf9e6ac9.x86_64
  python2-libs-2.7.16-12.module_el8.1.0+219+cf9e6ac9.x86_64
  python2-pip-wheel-9.0.3-14.module_el8.1.0+219+cf9e6ac9.noarch
  python2-setuptools-wheel-39.0.1-11.module_el8.1.0+219+cf9e6ac9.noarch
  mongodb-org-mongos-4.2.5-1.el8.x86_64
  mongodb-org-server-4.2.5-1.el8.x86_64
  mongodb-org-shell-4.2.5-1.el8.x86_64
  mongodb-org-tools-4.2.5-1.el8.x86_64

Complete!

Enable and start MongoDB database service.

[root@mongodb-01 ~]# systemctl enable --now mongod.service

After successful start, check the status for MongoDB for any possible errors.

[root@mongodb-01 ~]# systemctl status mongod.service
â mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor pres>
   Active: active (running) since Mon 2020-04-13 12:38:08 PKT; 13s ago
     Docs: https://docs.mongodb.org/manual
  Process: 2034 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCE>
  Process: 2031 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited,>
  Process: 2029 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (cod>
  Process: 2028 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, s>
 Main PID: 2036 (mongod)
   Memory: 76.8M
   CGroup: /system.slice/mongod.service
           ââ2036 /usr/bin/mongod -f /etc/mongod.conf

Apr 13 12:38:05 mongodb-01.centlinux.com systemd[1]: Starting MongoDB Database >
Apr 13 12:38:06 mongodb-01.centlinux.com mongod[2034]: about to fork child proc>
Apr 13 12:38:06 mongodb-01.centlinux.com mongod[2034]: forked process: 2036
Apr 13 12:38:08 mongodb-01.centlinux.com mongod[2034]: child process started su>
Apr 13 12:38:08 mongodb-01.centlinux.com systemd[1]: Started MongoDB Database S>

 

Create SELinux Policy for MongoDB on CentOS 8:

According to MongoDB documentation, if you have configured SELinux in enforcing mode then you have to create a SELinux policy for MongoDB.

Check current SELinux mode.

[root@mongodb-01 ~]# getenforce
Enforcing

We need checkpolicy command to verfiy the custom SELinux policies, therefore we are installing checkpolicy package by using dnf command.

[root@mongodb-01 ~]# dnf install -y checkpolicy
CentOS-8 - AppStream                            4.0 kB/s | 4.3 kB     00:01
CentOS-8 - Base                                 3.0 kB/s | 3.8 kB     00:01
CentOS-8 - Extras                               2.7 kB/s | 1.5 kB     00:00
MongoDB Repository                              1.6 kB/s | 2.5 kB     00:01
Dependencies resolved.
================================================================================
 Package              Architecture    Version             Repository       Size
================================================================================
Installing:
 checkpolicy          x86_64          2.9-1.el8           BaseOS          348 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 348 k
Installed size: 1.7 M
Downloading Packages:
checkpolicy-2.9-1.el8.x86_64.rpm                7.5 kB/s | 348 kB     00:46
--------------------------------------------------------------------------------
Total                                           7.5 kB/s | 348 kB     00:46
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1
  Installing       : checkpolicy-2.9-1.el8.x86_64                           1/1
  Running scriptlet: checkpolicy-2.9-1.el8.x86_64                           1/1
  Verifying        : checkpolicy-2.9-1.el8.x86_64                           1/1

Installed:
  checkpolicy-2.9-1.el8.x86_64

Complete!

Create a custom SELinux policy file.

[root@mongodb-01 ~]# vi mongodb_cgroup_memory.te

And add followingdirectives therein.

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 };

Compiled and apply this SELinux policy.

[root@mongodb-01 ~]# checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
[root@mongodb-01 ~]# semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
[root@mongodb-01 ~]# semodule -i mongodb_cgroup_memory.pp

 

Create an Admin User in MongoDB:

By default, Access Control is not enabled in MongoDB server, therefore, anyone can access MongoDB server and perform administrative actions.

Therefore, it is very important that, we create an Admin user and enable Access Control in our MongoDB server.

Connect with MongoDB shell as follows.

[root@mongodb-01 ~]# mongo
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("195cc9ab-b18a-4edc-9fb0-1266e4d961af") }
MongoDB server version: 4.2.5
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings:
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-04-13T12:38:08.220+0500 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-04-13T12:38:08.220+0500 I  CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

Connect with admin database.

> use admin;
switched to db admin

Create an admin user as follows.

> db.createUser(
...   {
...     user: "admin",
...     pwd: "123",
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}

List down all the users in MongoDB database.

> show users
{
        "_id" : "admin.admin",
        "userId" : UUID("cefd30bd-2e83-4959-a47a-087a423806a0"),
        "user" : "admin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

MongoDB admin user has been created successfully.

Exit from MongoDB shell.

> exit
bye

 

Enable Access Control in MongoDB Server:

Initially, Access Control is disabled in MongoDB server. Therefore, any user that has operating system level access to CentOS 8 server can connect to MongoDB instance and perform administrative actions on the databases. That is why we were able to create an admin user without any authentication in the previous step.

To enable Access Control for MongoDB server, we need to edit the systemd unit file for mongod.service.

[root@mongodb-01 ~]# vi /usr/lib/systemd/system/mongod.service

Find following line in this file.

Environment="OPTIONS=-f /etc/mongod.conf"

And replace it with following line.

Environment="OPTIONS=--auth -f /etc/mongod.conf"

We have edited a systemd unit file explicitly by using a text editor. Therefore, we need to execute the following command to inform systemd about this change.

[root@mongodb-01 ~]# systemctl daemon-reload

Restart MongoDB service to apply the changes.

[root@mongodb-01 ~]# systemctl restart mongod.service

For checking Access Control, connect with MongoDB shell and execute some administrative commands.

[root@mongodb-01 ~]# mongo
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("3526a97b-a0a1-47d2-91b1-0c15ef9f21e9") }
MongoDB server version: 4.2.5
> use admin
switched to db admin
> show users
2020-04-13T15:11:54.161+0500 E  QUERY    [js] uncaught exception: Error: command usersInfo requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1638:15
shellHelper.show@src/mongo/shell/utils.js:883:9
shellHelper@src/mongo/shell/utils.js:790:15
@(shellhelp2):1:1

This time the "show user" command raises the authentication error, it confirms that the Access Control has been enabled in our MongoDB server.

Now, connect as admin user.

> db.auth("admin",passwordPrompt())
Enter password:
1

Now, execute the same command, to check if it is working or not.

> show users
{
        "_id" : "admin.admin",
        "userId" : UUID("cefd30bd-2e83-4959-a47a-087a423806a0"),
        "user" : "admin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

The command “show users” has been successfully executed with a privileged user.

Access Control for MongoDB database has been enabled.

 

Configure MongoDB Service for Network Access:

This step is optional. If you are planning to access your MongoDB database across the network, then you have to perform following configurations.

By default the MongoDB service runs on the localhost interface. Therefore, to make it accessible from the network, we need to run MongoDB service on all interfaces.

Edit MongoDB configuration file by using vim editor

[root@mongodb-01 ~]# vi /etc/mongod.conf

Locate bindIp directive in this file and set it as.

bindIp: 0.0.0.0

Restart MongoDB service to apply changes.

[root@mongodb-01 ~]# systemctl restart mongod.service

We are also required to allow incoming traffic to MongoDB service in Linux firewall.

[root@mongodb-01 ~]# firewall-cmd --permanent --add-service=mongodb
success
[root@mongodb-01 ~]# firewall-cmd --reload
success

You can now access MongoDB database service from network.

 

MongoDB Data and Log Directories:

Following are the two directories, that are very important for MongoDB database administrators.

  • /var/lib/mongo - Data directory (default)
  • /var/log/mongodb - Log directory (default)

We can customize above directories by setting following parameters in /etc/mongodb.conf file.

  • storage.dbPath - to specify a new data directory path
  • systemLog.path - to specify a new log file path

 

Conclusion:

We have successfully installed MongoDB on CentOS 8 server and enabled Access Control. MongoDB: The Definitive Guide: Powerful and Scalable Data Storage by O'Reilly Media is a very good book on the MongoDB administration and we are highly recommend this for the MongoDB database administrators.

No comments:

Post a Comment