How to Install MongoDB on RHEL/CentOS 8: A Comprehensive 2021 Guide

Hello friend! Installing the latest MongoDB version on RHEL or CentOS 8 is a straight-forward process thanks to the official MongoDB repositories. However, some additional steps help optimize, secure and validate your MongoDB installation. This comprehensive, up-to-date guide covers all considerations for a production-grade MongoDB deployment.

A Brief History of MongoDB

MongoDB is an open source, document database designed for ease of development and scaling. Instead of storing data in rows and columns as relational databases do, MongoDB stores JSON-like documents with flexible schemas. This makes it easier for developers to store unstructured or polymorphic data.

Since its first release in 2009, MongoDB has become one of the most popular databases for modern applications. Over 35 million downloads have been logged by MongoDB. Popular users include eBay, Nielsen, advisor Wells Fargo, and thousands more organizations. Mobile apps, content management systems, and IoT applications rely on MongoDB for its intuitive data model.

So why consider MongoDB over traditional relational databases? A few key advantages:

  • Automatic horizontal scaling – Add nodes to handle more traffic without downtime
  • Flexible data model – Easily store data of any structure without complex schema migrations
  • Rich indexes support faster queries and analysis
  • Native aggregation framework to perform complex data analysis
  • Ease of use for developers while remaining highly scalable

Now let‘s get MongoDB installed the robust way!

Prerequisites

MongoDB can run on a wide range of systems, but here are some minimum recommendations:

Supported Operating Systems

MongoDB 4.2+ supports the following 64-bit OS versions:

  • RHEL/CentOS 8+
  • Fedora 30+
  • Debian 10+
  • Ubuntu 16.04+
  • Amazon Linux 2
  • SUSE 15+

Note Ubuntu 12.04 and 14.04 reached end-of-life and are unsupported.

Hardware

For best performance, follow these hardware guidelines:

Purpose CPU Cores RAM Storage Type
Dev/Test 2 2 GB+ SAS, SATA SSD
Production 4+ 8+ GB SAS, NVMe SSD
  • Compute Unit Definitions:
    • 2 compute units = 1 core of an Intel Xeon E5-2670v2 processor
  • Allocate about 10-100GB free space for the data directory

User Roles

To install MongoDB, you should have sudo or root permissions. Typically a UNIX admin, DevOps or platform engineer role would handle the install process.

For application developers that just need access to MongoDB, you can request a database user to be created for you once MongoDB is deployed.

Now let‘s get MongoDB installed!

Step 1 – Add the MongoDB Repository

RHEL, CentOS, and Fedora use yum and dnf to install software packages from configured repositories.

To set up the MongoDB 4.2 repository:

  1. Create a /etc/yum.repos.d/mongodb-org-4.2.repo file with this configuration:
[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
  1. Optionally, specify another major version instead of 4.2. See available repo configurations.

This yum repository definition will now let you install MongoDB directly using your package manager.

Step 2 – Install MongoDB Packages

The MongoDB server, client tools, key utilities are split into separate packages. To install the latest MongoDB 4.2 release:

sudo yum install -y mongodb-org
  • This will install the mongodb-org meta-package along with these components:
    • mongodb-org-server – The mongod database server daemon
    • mongodb-org-shell – The mongo interactive JavaScript shell
    • mongodb-org-mongos – The query router
    • mongodb-org-tools – Import/export tools, data analytics

Verify you have MongoDB 4.2+ with:

mongo --version 

On a freshly installed system, this uses about 248MB of disk space in /var/lib/mongo/.

Now we need to configure MongoDB for optimal performance.

Step 3 – Configure MongoDB

MongoDB provides sensible configuration defaults, but lacks access control and storage optimizations for production use cases.

The main configuration file is /etc/mongod.conf which uses the YAML format. You manage additional config files through the /etc/mongod.conf.d/ directory.

Considerations by Deployment Type

For standalone servers, make these updates:

  • Set access control
  • Change default data and journal directories
  • Tune WiredTiger storage engine settings
  • Set log paths

With a replica set topology consider also:

  • Define replica set members
  • ConfigureOplog sizing
  • Set election timeout

And for sharded clusters:

  • Break out shard servers
  • Configure config servers
  • Set chunk size

See the deployment topologies overview in MongoDB‘s docs for more details.

Now let‘s look at some specific configuration areas.

Storage

Update the default tiny data file path:

storage:
   dbPath: /opt/mongodb/data
   journal:
     enabled: true
  • Use a volume with ample disk space fordatabases
  • Set journaling to prevent data loss issues

Consider a separate disk volume for journal files.

Performance Tuning and Resourcing

WiredTiger Settings

Tune the WiredTiger storage engine settings:

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2
  • Allocate 50-75% of RAM for cache – the rest is left for computing

Index Configurations

storage: 
  indexConfig:
     prefixCompression: true

Enable prefix compression on indexes over large string fields.

Memory and CPU

Monitor host load and tune accordingly:

processManagement:
   fork: true  
   linuxSchedulerPolicy: fifo
   numa:
      maxInterleave: 0
      nodeMemoryMB: 1024  
      policy: preferLocal
  • Reduce NUMA interference
  • Use real-time fifo scheduler
  • Set max memory

Diagnostics and Telemetry

Capture orchestration and host telemetry:

diagnosticData:
  orchestration: enabled  
  hostInfo: enabled

Security and Access Control

Require authentication and create the first admin user:

security:
  authorization: enabled 

# create user admin for db admin
db.createUser({
  user: "admin",
  pwd: "passw0rd",
  roles: ["root"]
})

Then define additional application databases, users and roles.

See the role-based access control guidance for more details.

Network Exposure and Interfaces

Bind MongoDB to localhost and port 27017:

net:
  bindIp: 127.0.0.1,[::1]  
  port: 27017

IP whitelist connects from app servers:

net:
  bindIP: 0.0.0.0  
  port: 27017
  ipv6: true
security:    
  authorization: enabled
  whitelistedIPS: 
    - 192.168.103.100
    - "172.16.0.0/16" 

This prevents external MongoDB access.

Step 4 – Start MongoDB and Validate

Use systemctl to start MongoDB and check its status:

sudo systemctl start mongod
sudo systemctl status mongod

The process should show active and running.

Next validate that MongoDB is ready and responding to requests:

mongo 

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

Exit back to the system shell with exit.

Hooray 🎉 – MongoDB is now installed and running!

Now let‘s look at validating the deployment further.

Step 5 – Validate the Installation

To further test the MongoDB installation:

  1. Check logs for any issues

    sudo tail -f /var/log/mongodb/mongod.log
  2. Enable security and create an admin user

  3. Connect via Compass or your own client

    • Perform test inserts, finds, deletes
  4. Import sample dataset if available with mongorestore

  5. Review MongoDB settings in Compass

Share access credentials safely with your application development teams allowing them to start using the new database.

Step 6 – Secure MongoDB

While optional for early development uses, running MongoDB without security risks data loss or theft.

Here are quick steps to lock down MongoDB:

  1. Require authentication to enforce username and password login
  2. Create TLS/SSL certificates to encrypt traffic
  3. Setup role-based access control granting least privileges
  4. Enable auditing to track data access and changes
  5. Integrate an LDAP server for user management
  6. Set up VPC peering or VPN for server access
  7. Restrict network exposure beyond localhost

See MongoDB‘s security checklist for more hardening tips.

Now let‘s cover upgrades and compatibility…

Upgrading MongoDB Version

MongoDB aims to provide simple upgrades between versions, but several considerations apply:

  • Review compatibility changes before upgrading
  • Test upgrades in staging environments first
  • Plan for some downtime performing the upgrade
  • Follow the step-by-step major version upgrade procedure

Here is the standard upgrade process:

  1. Notify users of planned upgrade with downtime window
  2. Take a final backup of databases with mongodump
  3. Shutdown existing MongoDB process
  4. Install newer MongoDB version (steps above)
  5. Start new MongoDB version process
  6. Restore databases from backup using mongorestore
  7. Notify users to reconnect their applications
  8. Test thoroughly!

Be aware of any compatibility-breaking changes between versions as early MongoDB had relaxer datatypes and schema validation for example.

I hope this gives you a comprehensive, step-by-step guide to installing MongoDB on RHEL or Centos! Let me know if any part needs more explanation.

Sincerely,
[Your Name]