How to Install MongoDB on RHEL 7

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like BSON documents rather than traditional rows and columns. Its schema-less design makes it an excellent choice for applications that need to handle varied or rapidly evolving data structures, such as content management systems, real-time analytics platforms, user profile stores, and IoT data pipelines. MongoDB is not included in the RHEL 7 base or EPEL repositories, so installation requires configuring MongoDB’s official yum repository. This guide covers adding the MongoDB repository, installing the packages, starting and securing the mongod service, using the mongo shell for basic operations, enabling authentication, and addressing SELinux requirements on RHEL 7.

Prerequisites

  • A RHEL 7 server with root or sudo access
  • At least 2 GB of RAM (4 GB or more recommended for production)
  • Internet access to reach the MongoDB yum repository
  • RHEL 7 subscription with base repos enabled (for glibc, openssl, etc.)
  • firewalld installed and running

Verify available disk space before proceeding, as MongoDB can consume significant storage:

df -h /var
# MongoDB data defaults to /var/lib/mongo

Step 1: Create the MongoDB Yum Repository File

MongoDB provides an official yum repository for Red Hat-based Linux distributions. Create the repository configuration file manually:

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

Add the following content for MongoDB 4.4 (the last version supporting RHEL 7):

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

Save and close the file. Verify the repository is recognized by yum:

sudo yum repolist | grep mongodb

You should see the mongodb-org-4.4 repository listed as enabled.

Step 2: Install MongoDB

Install the mongodb-org meta-package, which pulls in all required MongoDB components:

sudo yum install -y mongodb-org

This installs the following packages:

  • mongodb-org-server — the mongod daemon
  • mongodb-org-mongos — the MongoDB shard router
  • mongodb-org-shell — the mongo JavaScript shell
  • mongodb-org-tools — utilities such as mongodump, mongorestore, mongostat

Confirm the installed version:

mongod --version
# db version v4.4.x

Step 3: Start and Enable the mongod Service

Start the MongoDB daemon using systemctl and enable it to start automatically at boot:

sudo systemctl start mongod
sudo systemctl enable mongod

Check the service status:

sudo systemctl status mongod

Expected output:

● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; ...)
   Active: active (running) since Sun 2024-03-15 12:00:00 UTC; 5s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 14567 (mongod)

MongoDB logs are written to /var/log/mongodb/mongod.log. Check this file if the service fails to start:

sudo tail -50 /var/log/mongodb/mongod.log

Step 4: Connect with the mongo Shell

Connect to the local MongoDB instance using the mongo shell. With authentication disabled (the default after installation), you can connect without credentials:

mongo

Inside the mongo shell, explore some basic commands:

// Show the MongoDB server version
db.version()

// List all databases
show dbs

// Switch to (or create) a database named 'appdb'
use appdb

// Insert a document into a collection
db.products.insertOne({
    name: "RHEL 7 Server",
    category: "Operating System",
    price: 349.00,
    tags: ["linux", "enterprise", "rhel"],
    createdAt: new Date()
})

// Query the collection
db.products.find().pretty()

// Insert multiple documents at once
db.products.insertMany([
    { name: "RHEL 7 Workstation", price: 179.00, category: "Operating System" },
    { name: "RHEL 7 Developer", price: 0.00, category: "Free Tier" }
])

// Count documents
db.products.countDocuments()

// Find documents matching a filter
db.products.find({ category: "Operating System" }).pretty()

// Create an index for faster queries
db.products.createIndex({ name: 1 })

// Show all collections in the current database
show collections

Step 5: Create an Administrative User

Before enabling authentication, create an administrative user in the admin database. Without this step, enabling authentication will lock you out entirely:

use admin

db.createUser({
    user: "mongoadmin",
    pwd: "Adm1n#Secure2024",
    roles: [
        { role: "userAdminAnyDatabase", db: "admin" },
        { role: "readWriteAnyDatabase", db: "admin" },
        { role: "dbAdminAnyDatabase", db: "admin" }
    ]
})

// Create a less privileged application user
use appdb

db.createUser({
    user: "appuser",
    pwd: "App#User2024!",
    roles: [
        { role: "readWrite", db: "appdb" }
    ]
})

exit

Step 6: Enable Authentication in mongod.conf

Edit the MongoDB configuration file to enable access control:

sudo vi /etc/mongod.conf

Locate the security section and enable authorization:

# mongod.conf

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# security
security:
  authorization: enabled

Restart MongoDB to apply the security change:

sudo systemctl restart mongod

Test authentication by connecting with the admin user:

mongo -u mongoadmin -p 'Adm1n#Secure2024' --authenticationDatabase admin

Test the application user connection:

mongo -u appuser -p 'App#User2024!' --authenticationDatabase appdb appdb

Step 7: Configure MongoDB for Remote Access

To accept connections from remote hosts, change the bindIp setting in /etc/mongod.conf:

net:
  port: 27017
  bindIp: 0.0.0.0

Or bind to a specific network interface IP:

net:
  port: 27017
  bindIp: 127.0.0.1,192.168.1.10

Restart MongoDB after editing:

sudo systemctl restart mongod

Open the firewall for port 27017:

sudo firewall-cmd --permanent --add-port=27017/tcp
sudo firewall-cmd --reload
sudo firewall-cmd --list-ports

Restrict remote access to specific trusted hosts using a rich rule:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.0/24" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload

Step 8: SELinux Considerations

SELinux on RHEL 7 requires specific policies for MongoDB. By default, MongoDB’s file paths are labelled correctly, but certain operations may be blocked by SELinux in enforcing mode. Check for AVC denials:

sudo ausearch -m avc -ts recent | grep mongod

The most common SELinux issue with MongoDB on RHEL 7 is the mongod service being prevented from creating files in its data directory or binding to its socket. Set the correct file context for MongoDB’s default paths:

# Check existing labels
ls -dZ /var/lib/mongo
ls -dZ /var/log/mongodb

# These should show mongod_var_lib_t and mongod_log_t respectively

If you change the data directory to a custom path, apply the correct SELinux label:

sudo semanage fcontext -a -t mongod_var_lib_t "/data/mongodb(/.*)?"
sudo restorecon -Rv /data/mongodb
sudo chown -R mongod:mongod /data/mongodb

MongoDB 4.4 ships with an SELinux policy module for RHEL 7 that can be installed to resolve most policy issues:

cd /usr/share/doc/mongodb-org-server-4.4.*/
sudo semodule -i mongod.te 2>/dev/null || echo "Policy module not found, using default policies"

If SELinux is blocking mongod from functioning correctly and you need a temporary workaround while building the correct policy, you can set SELinux to permissive mode for the mongod context only (do not disable SELinux globally):

sudo semanage permissive -a mongod_t

MongoDB 4.4 is now installed and secured on your RHEL 7 server. You configured the official MongoDB yum repository, installed all required components, started the mongod service, explored basic operations in the mongo shell, created administrative and application users, enabled authentication in /etc/mongod.conf, and addressed both firewall and SELinux requirements. For production deployments, consider enabling replica sets for high availability, configuring TLS/SSL for encrypted connections, and tuning the WiredTiger storage engine cache size to match your available RAM.