Share on Social Media

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. #centlinux #linux #nosql

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 Linux 8.0
  • Hostname –
  • IP Address – /24

Read Also: How to install MongoDB on Rocky Linux 9

Install MongoDB Yum Repository:

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

MongoDB Download Page

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 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.

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

And add following configurations in this file.

name=MongoDB Repository

Build cache for MongoDB yum repository.

# 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:

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.

# 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

Install MongoDB 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.

# dnf install -y mongodb-org

Enable and start MongoDB database service.

# systemctl enable --now mongod.service

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

# 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
  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 systemd[1]: Starting MongoDB Database >
Apr 13 12:38:06 mongod[2034]: about to fork child proc>
Apr 13 12:38:06 mongod[2034]: forked process: 2036
Apr 13 12:38:08 mongod[2034]: child process started su>
Apr 13 12:38:08 systemd[1]: Started MongoDB Database S>

Create SELinux Policy for MongoDB:

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.

# getenforce

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

# dnf install -y checkpolicy

Create a custom SELinux policy file.

# 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.

# checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
# semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
# 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.

# mongo
MongoDB shell version v4.2.5
connecting to: 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
Questions? Try the support group
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" : [

MongoDB admin user has been created successfully.

Exit from MongoDB shell.

> exit

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.

# 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.

# systemctl daemon-reload

Restart MongoDB service to apply the changes.

# systemctl restart mongod.service

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

# mongo
MongoDB shell version v4.2.5
connecting to: 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 :

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:

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" : [

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

Access Control for MongoDB database has been enabled.

Configure MongoDB Service:

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

# vi /etc/mongod.conf

Locate bindIp directive in this file and set it as.


Restart MongoDB service to apply changes.

# systemctl restart mongod.service

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

# firewall-cmd --permanent --add-service=mongodb
# firewall-cmd --reload

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 – Install MongoDB on CentOS 8:

In this article, we have demonstrated, how to install MongoDB on CentOS 8 server and enabled Access Control. MongoDB: The Definitive Guide: Powerful and Scalable Data Storage (PAID LINK) by O’Reilly Media is a very good book on the MongoDB administration and we are highly recommend this for the MongoDB database administrators.

Leave a Reply

Your email address will not be published. Required fields are marked *