CentOSRHEL Based

How To Install MongoDB on CentOS Stream 10

Install MongoDB on CentOS Stream 10

MongoDB stands out as a leading NoSQL database, celebrated for its scalability and flexibility in handling modern application data. Its document-oriented approach aligns perfectly with the agile development methodologies prevalent today. For those leveraging CentOS Stream 10, installing MongoDB opens up a world of possibilities for managing and processing data efficiently. This guide provides a detailed, step-by-step walkthrough, ensuring a smooth installation experience. Let’s dive in!

Introduction

In today’s data-driven landscape, the choice of database can significantly impact application performance and scalability. MongoDB, with its flexible schema and robust feature set, has become a favorite among developers. It is particularly suitable for applications that require high availability and the ability to handle large volumes of unstructured or semi-structured data. CentOS Stream 10, known for its stability and enterprise-grade features, provides an excellent platform for deploying MongoDB. This article guides you through each stage of the installation, ensuring a successful setup. We will cover everything from initial system preparation to advanced security configurations.

  • Brief overview of MongoDB as a NoSQL database
  • Why MongoDB is popular for modern applications
  • Specific benefits for CentOS Stream 10 users
  • Article objectives and target audience

This guide aims to provide clear, concise instructions, making the installation process straightforward, even for those new to MongoDB or CentOS Stream 10. By the end of this tutorial, you will have a fully functional MongoDB installation, ready for development and deployment. Whether you’re setting up a development environment or configuring a production server, this guide has you covered. Ready to get started? Great, let’s proceed to the prerequisites.

Prerequisites

Before you begin the MongoDB installation on CentOS Stream 10, it’s essential to ensure your system meets certain prerequisites. Failing to meet these requirements can lead to installation issues or suboptimal performance. Let’s review what you need.

  • System requirements
  • Root or sudo privileges
  • Minimum hardware specifications
  • Required command-line knowledge
  • System update status

First and foremost, ensure you have a CentOS Stream 10 system up and running. You’ll also need an account with either root privileges or sudo access to execute administrative commands. Basic familiarity with the command line is necessary to follow the installation steps. Lastly, it’s crucial to have an active internet connection to download the required packages. Got all these? Wonderful, let’s head on.

Checking System Requirements

To ensure a smooth MongoDB installation, your CentOS Stream 10 system should meet the following minimum requirements:

  • Operating System: CentOS Stream 10
  • RAM: At least 2 GB (4 GB recommended for production)
  • Storage: 10 GB of free disk space (SSD recommended for better performance)
  • Processor: 64-bit architecture

Meeting these specifications will provide a solid foundation for running MongoDB. While MongoDB can technically run on systems with lower resources, performance may be significantly impacted, especially under heavy loads. For production environments, it’s always best to exceed these minimums. Next, let’s make sure you have the necessary privileges.

Verifying User Privileges

You need either root access or sudo privileges to install software and configure system services on CentOS Stream 10. Here’s how to check your current privileges:

whoami

If the output is root, you have root access. If you’re using a regular user account, you can check if you have sudo privileges by running:

sudo -l

If you see a list of commands you can run with sudo, you’re all set. If not, you’ll need to contact your system administrator to grant you sudo access. Having the right privileges is key to a hassle-free install. Now, let’s consider the importance of keeping your system up-to-date.

Ensuring System is Up-to-Date

Before installing any new software, it’s a good practice to update your system’s package list. This ensures you have the latest versions of all packages and dependencies. To update your system, run:

sudo dnf update

This command updates all installed packages to their latest versions. It may take some time, depending on how recently the system was last updated. Keeping your system current minimizes potential conflicts and vulnerabilities. All prerequisites checked? Great, let’s move to system preparation!

System Preparation

Preparing your CentOS Stream 10 system is a critical step before installing MongoDB. This involves updating system packages and installing any necessary dependencies. A well-prepared system ensures that the MongoDB installation process goes smoothly. Let’s explore these steps in detail.

  • Updating package repositories
  • Installing necessary dependencies
  • Verifying system compatibility

Updating System Packages

Updating your system packages is a fundamental step in ensuring compatibility and security. The dnf update command updates all installed packages to their latest versions. This not only ensures you have the newest features and bug fixes but also resolves potential dependency conflicts. Execute the following command:

sudo dnf update

This process might take some time, depending on your internet connection and the number of updates available. It’s advisable to perform this step during off-peak hours if you’re on a network with limited bandwidth. After the update, it’s time to consider specific dependencies MongoDB might need. Don’t worry, we will cover that in the next section.

Installing Necessary Dependencies

MongoDB relies on certain dependencies to function correctly. While the dnf install command typically handles these dependencies automatically, it’s wise to ensure they are present beforehand. Common dependencies include libraries for SSL, compression, and system utilities. To install these, use the following command:

sudo dnf install -y openssl snappy

This command installs OpenSSL for secure communication and Snappy for data compression. The -y flag automatically confirms the installation, preventing the need for manual confirmation. Ensuring these dependencies are in place reduces the likelihood of encountering errors during the MongoDB installation. Dependency check? Great, let’s proceed.

Verifying System Compatibility

Before proceeding, verify that your system is fully compatible with MongoDB. This involves checking the kernel version, architecture, and other system-level configurations. Use the following commands to gather this information:

uname -a

This command displays detailed information about your kernel, including the architecture (x86_64 for 64-bit systems). MongoDB requires a 64-bit system, so ensure that the output confirms this. Next, check the CentOS Stream 10 version:

cat /etc/centos-release

This command displays the CentOS Stream version, ensuring you’re indeed running CentOS Stream 10. Verifying these details ensures that the installation aligns with MongoDB’s requirements. All good? Let’s move on to configuring the MongoDB repository!

MongoDB Repository Configuration

Configuring the MongoDB repository is a pivotal step in the installation process. It involves adding a repository file that tells the system where to find the MongoDB packages. This ensures that the dnf install command can locate and install MongoDB correctly. Let’s walk through this process.

  • Creating repository file
  • Detailed steps for adding MongoDB repository
  • Repository file location and permissions
  • Version selection considerations
  • GPG key verification process

Creating Repository File

To install MongoDB using the dnf package manager, you need to create a repository file. This file contains the necessary information for dnf to locate and download the MongoDB packages. The repository file should be named mongodb-org.repo and placed in the /etc/yum.repos.d/ directory.

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

This command opens the vi editor to create or edit the mongodb-org.repo file. If you prefer a more user-friendly editor, you can use nano instead:

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

Using either editor, you will now add the repository configuration. The repository file contains details such as the repository name, base URL, and GPG key information. Let’s look at the specifics.

Adding MongoDB Repository Details

Once you have opened the mongodb-org.repo file, you need to add the following configuration details. These details tell dnf where to find the MongoDB packages and how to verify their authenticity:

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

Here’s a breakdown of each line:

  • [mongodb-org-7.0]: Defines the repository ID.
  • name=MongoDB Repository: Specifies the name of the repository.
  • baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/: Sets the base URL where the packages are located.
  • gpgcheck=1: Enables GPG key checking for package verification.
  • enabled=1: Enables the repository.
  • gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc: Specifies the URL for the GPG key.

Make sure to adjust the version number (e.g., 7.0) to the specific MongoDB version you intend to install. After adding these lines, save and close the file. Now, let’s discuss the repository file location and its permissions.

Repository File Location and Permissions

The repository file must be located in the /etc/yum.repos.d/ directory. This directory is the standard location for dnf repository files. The file should have read permissions for all users, but write permissions should be restricted to the root user. To set the correct permissions, use the following commands:

sudo chmod 644 /etc/yum.repos.d/mongodb-org.repo
sudo chown root:root /etc/yum.repos.d/mongodb-org.repo

These commands ensure that the file has the correct permissions and ownership. Incorrect permissions can prevent dnf from accessing the repository, leading to installation failures. Next, let’s talk about version selection.

Version Selection Considerations

MongoDB offers multiple versions, each with its own features, improvements, and support lifecycle. Selecting the right version is crucial for ensuring compatibility and long-term support. As of the latest information, MongoDB 7.0 is the newest stable version. When configuring the repository, specify the desired version in the baseurl and gpgkey lines:

baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc

Choosing a version depends on your specific needs and compatibility requirements. Always refer to the official MongoDB documentation for the latest recommendations. After setting the version, it’s important to verify the GPG key.

GPG Key Verification Process

The GPG key is used to verify the integrity and authenticity of the MongoDB packages. When you install MongoDB, dnf uses the GPG key to ensure that the packages come from a trusted source and haven’t been tampered with. The GPG key URL is specified in the gpgkey line of the repository file:

gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc

dnf automatically imports this key when you install MongoDB for the first time. If you encounter GPG key errors, you can manually import the key using the following command:

sudo rpm --import https://www.mongodb.org/static/pgp/server-7.0.asc

This command imports the GPG key, resolving any key-related issues. With the repository configured and the GPG key verified, you’re now ready to install MongoDB. Let’s proceed to the installation process!

Installation Process

Now that your CentOS Stream 10 system is prepared and the MongoDB repository is configured, you can proceed with the installation. This involves using the dnf install command to download and install the MongoDB packages. Let’s dive into the specifics.

  • Package installation
  • Package verification
  • Handling dependencies
  • Troubleshooting common installation errors

Package Installation

To install MongoDB, use the dnf install command. This command downloads the MongoDB packages from the configured repository and installs them on your system. Execute the following command:

sudo dnf install -y mongodb-org

The -y flag automatically confirms the installation, bypassing the need for manual confirmation. This command installs the core MongoDB packages, including the server (mongod), the command-line shell (mongo), and related utilities. During the installation, dnf resolves any dependencies, ensuring that all required libraries and components are installed. Installation in progress? Perfect, let’s verify the package.

Package Verification

After the installation completes, verify that the packages have been installed correctly. You can do this by checking the installed version of MongoDB. Use the following command:

mongo --version

This command displays the version of the MongoDB shell, confirming that MongoDB has been successfully installed. Additionally, you can check the installed packages using dnf:

sudo dnf list installed | grep mongodb-org

This command lists all installed packages and filters the output to show only the MongoDB packages. Seeing the installed version and packages confirms a successful installation. If there were any missing packages, we will handle them next!

Handling Dependencies

During the installation, dnf automatically handles most dependencies. However, if you encounter any dependency-related issues, you can resolve them using the dnf command. For example, if a specific library is missing, you can install it directly:

sudo dnf install -y <missing-package>

Replace <missing-package> with the name of the missing package. Additionally, you can use the dnf check command to identify and resolve dependency issues:

sudo dnf check

This command checks for broken dependencies and suggests solutions. Addressing dependency issues ensures that MongoDB functions correctly. Let’s discuss common errors.

Troubleshooting Common Installation Errors

Despite following the installation steps carefully, you might encounter errors. Here are some common issues and their solutions:

  • GPG Key Errors: If you encounter GPG key errors, manually import the GPG key using the rpm --import command.
  • Repository Not Found: If dnf cannot find the MongoDB repository, double-check the repository file configuration and ensure it’s placed in the correct directory.
  • Package Conflicts: If you encounter package conflicts, try running sudo dnf update to update all packages before installing MongoDB.

Consulting the MongoDB documentation and community forums can also provide valuable insights into resolving specific errors. Successfully troubleshooting installation errors ensures a smooth MongoDB setup. With all errors resolved, let’s configure the service!

Service Configuration

After installing MongoDB, the next step is to configure the MongoDB service. This involves starting the service, enabling it to start on boot, and configuring service parameters. Proper service configuration ensures that MongoDB runs reliably and efficiently. Let’s explore the configuration process.

  • Starting MongoDB service
  • Enabling automatic startup
  • Configuring service parameters
  • Setting up security basics

Starting MongoDB Service

To start the MongoDB service, use the systemctl start command. This command initiates the mongod process, which is the core MongoDB server. Execute the following command:

sudo systemctl start mongod

This command starts the MongoDB service. To verify that the service is running, use the systemctl status command.

Enabling Automatic Startup

To ensure that MongoDB starts automatically when the system boots, enable the service using the systemctl enable command. This command creates symbolic links in the system’s startup directories, ensuring that the service is started during boot. Execute the following command:

sudo systemctl enable mongod

This command enables the MongoDB service to start on boot. To confirm that the service is enabled, use the systemctl is-enabled command.

Configuring Service Parameters

MongoDB’s behavior can be customized by configuring various service parameters. These parameters control aspects such as the data directory, log file location, and network settings. The main configuration file is located at /etc/mongod.conf. To edit this file, use a text editor:

sudo nano /etc/mongod.conf

Within this file, you can modify various settings. For example, to change the data directory, modify the dbPath parameter:

storage:
dbPath: /var/lib/mongodb

After making changes, save the file and restart the MongoDB service for the changes to take effect:

sudo systemctl restart mongod

Configuring service parameters allows you to fine-tune MongoDB to meet your specific requirements. Always consult the official MongoDB documentation for details on available parameters and their effects. Securing your MongoDB instance is always a great step to perform right away.

Setting up Security Basics

By default, MongoDB does not have authentication enabled. For production environments, it’s crucial to set up user authentication to prevent unauthorized access. To enable authentication, modify the /etc/mongod.conf file:

security:
authorization: enabled

Save the file and restart the MongoDB service. Next, connect to the MongoDB shell as the root user:

mongo -u root -p

Create an admin user:

use admin
 db.createUser(
  {
  user: "admin",
  pwd: "password",
  roles: [ { role: "root", db: "admin" } ]
  }
 )

Replace "password" with a strong password. Now, you can authenticate using the admin user. Enabling authentication and creating administrative users are fundamental security practices. With security set up, let’s proceed to verification and testing!

Verification and Testing

After installing and configuring MongoDB, it’s essential to verify that the installation is working correctly. This involves checking the service status, accessing the MongoDB shell, and performing basic functionality tests. Let’s go through these steps.

  • Checking service status
  • MongoDB shell access
  • Basic functionality testing
  • Version verification

Checking Service Status

To check the status of the MongoDB service, use the systemctl status command. This command provides detailed information about the service, including whether it’s active (running) and any recent log messages. Execute the following command:

sudo systemctl status mongod

If the service is running correctly, you should see output similar to this:

● mongod.service - MongoDB Database Server
  Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
  Active: active (running) since Mon 2025-01-07 14:30:00 UTC; 10min ago
  ...
 

The Active: active (running) line confirms that the MongoDB service is up and running. If the service is not running, check the log files for any error messages and troubleshoot accordingly. Let’s access the mongo shell now.

MongoDB Shell Access

The MongoDB shell (mongo) is a command-line interface for interacting with MongoDB. To access the shell, simply run the mongo command:

mongo

This command connects you to the default MongoDB instance. If authentication is enabled, you may need to specify the username and password:

mongo -u <username> -p <password> --authenticationDatabase admin

Replace <username> and <password> with your credentials. Once connected, you can execute MongoDB commands to manage databases, collections, and documents. Now, let’s move on to functionality testing.

Basic Functionality Testing

After accessing the MongoDB shell, perform basic functionality tests to ensure that MongoDB is working as expected. Try creating a database, adding a collection, and inserting a document. Here are some example commands:

use testdb
 db.createCollection("mycollection")
 db.mycollection.insertOne({ name: "example", value: 123 })
 db.mycollection.find()

These commands create a database named testdb, create a collection named mycollection, insert a document into the collection, and then find and display the document. Successful execution of these commands confirms that MongoDB is functioning correctly. Lastly, let’s check the version.

Version Verification

Verifying the MongoDB version is another way to confirm a successful installation. Use the mongo --version command to display the version of the MongoDB shell:

mongo --version

This command shows the version number, confirming that MongoDB is installed and accessible. Additionally, you can check the MongoDB server version from within the shell:

db.version()

This command returns the server version. Successfully verifying the version, service status, shell access, and basic functionality ensures that MongoDB is properly installed and ready for use. Security is always an important step for any installation and MongoDB is no exception.

Security Configuration

Securing your MongoDB installation is paramount, especially in production environments. This involves setting up user authentication, configuring network access, and implementing firewall rules. A secure MongoDB instance protects your data from unauthorized access and potential threats. Let’s explore these security measures.

  • User authentication setup
  • Network access configuration
  • Firewall rules
  • SELinux considerations

User Authentication Setup

Enabling user authentication is the first line of defense against unauthorized access. By default, MongoDB does not require authentication, meaning anyone can access your data. To enable authentication, modify the /etc/mongod.conf file:

security:
  authorization: enabled

Save the file and restart the MongoDB service:

sudo systemctl restart mongod

After enabling authentication, create administrative users with appropriate roles. Connect to the MongoDB shell as the root user and create an admin user:

use admin
 db.createUser(
  {
  user: "admin",
  pwd: "strong_password",
  roles: [ { role: "root", db: "admin" } ]
  }
 )

Replace "strong_password" with a strong, unique password. Now, you can authenticate using the admin user when connecting to the MongoDB shell. Restricting network access is just as important for security.

Network Access Configuration

By default, MongoDB listens on all network interfaces. To restrict network access, configure the bindIp parameter in the /etc/mongod.conf file. Specify the IP addresses that are allowed to connect to MongoDB:

net:
  bindIp: 127.0.0.1,192.168.1.10

This configuration allows connections only from the local machine (127.0.0.1) and the specified IP address (192.168.1.100). Save the file and restart the MongoDB service for the changes to take effect. Limiting network access reduces the attack surface and prevents unauthorized connections. A firewall is also a great way to prevent unwanted traffic from accessing your server.

Firewall Rules

A firewall provides an additional layer of security by controlling network traffic to and from your CentOS Stream 10 system. Use firewalld to configure firewall rules for MongoDB. To allow connections to MongoDB’s default port (27017), use the following commands:

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

These commands add a rule to the public zone, allowing TCP traffic on port 27017. The --permanent flag makes the rule persistent across reboots, and --reload applies the changes. Configuring firewall rules ensures that only authorized traffic can reach your MongoDB instance. Let’s consider SELinux as another layer of security!

SELinux Considerations

SELinux (Security-Enhanced Linux) provides mandatory access control, enhancing the security of your CentOS Stream 10 system. MongoDB includes SELinux policies that restrict the actions that the mongod process can perform. To ensure that SELinux doesn’t interfere with MongoDB, use the following commands:

sudo setsebool -P authlogin_nsswitch_use_ldap 1
sudo setsebool -P daemons_enable_cluster_mode 1

These commands enable specific SELinux booleans required for MongoDB. Additionally, ensure that the MongoDB data directory has the correct SELinux context:

sudo chcon -t mongod_db_t /var/lib/mongodb

This command sets the SELinux context for the /var/lib/mongodb directory. Configuring SELinux ensures that MongoDB operates within a secure environment. With security configured, let’s move on to performance optimization!

Performance Optimization

Optimizing MongoDB’s performance ensures that it operates efficiently and meets the demands of your applications. This involves tuning memory allocation, configuring the storage engine, and adjusting system limits. Let’s explore these optimization techniques.

  • Memory allocation
  • Storage engine configuration
  • System limits adjustment
  • Performance monitoring basics

Memory Allocation

MongoDB’s performance is heavily influenced by memory allocation. The WiredTiger storage engine, which is the default, uses an internal cache to store data and indexes. Allocating sufficient memory to this cache can significantly improve read and write performance. Configure the cacheSizeGB parameter in the /etc/mongod.conf file:

storage:
  wiredTiger:
  engineConfig:
  cacheSizeGB: 4

Set this value to an appropriate percentage of your system’s RAM. A common recommendation is to allocate 50-75% of available RAM to the WiredTiger cache. Monitoring memory usage and adjusting the cacheSizeGB parameter can optimize performance. The storage engine is another important area to consider.

Storage Engine Configuration

MongoDB supports multiple storage engines, each with its own strengths and weaknesses. The default WiredTiger storage engine provides a good balance of performance and features. However, you can configure various WiredTiger options to further optimize performance. For example, you can configure the journal compressor:

storage:
  wiredTiger:
  engineConfig:
  journalCompressor: snappy

Snappy provides fast compression and decompression, reducing disk I/O. Other options include configuring the block compressor and enabling or disabling the journal. Always consult the MongoDB documentation for the latest recommendations on storage engine configuration. Aside from the database, it’s crucial to check your system limits.

System Limits Adjustment

CentOS Stream 10 imposes various system limits that can impact MongoDB’s performance. These limits include the maximum number of open files, the maximum number of processes, and the maximum number of threads. To adjust these limits, edit the /etc/security/limits.conf file:

* soft nofile 64000
 * hard nofile 64000
 * soft nproc 64000
 * hard nproc 64000

These settings increase the maximum number of open files and processes for all users. Additionally, adjust the kernel parameters in the /etc/sysctl.conf file:

vm.max_map_count=262144
kernel.pid_max=65535

Apply these changes by running:

sudo sysctl -p

Adjusting system limits ensures that MongoDB has sufficient resources to operate efficiently. Monitoring performance helps to ensure you are maximizing resources.

Performance Monitoring Basics

Monitoring MongoDB’s performance is crucial for identifying bottlenecks and optimizing resource utilization. MongoDB provides various tools for monitoring performance, including the mongostat and mongotop utilities. mongostat provides real-time statistics on MongoDB operations:

mongostat

mongotop provides real-time statistics on read and write activity:

mongotop

Additionally, you can use the MongoDB Cloud Manager or third-party monitoring tools to track performance metrics such as CPU usage, memory usage, and disk I/O. Regularly monitoring performance allows you to identify and address potential issues before they impact your applications. Now that you know about optimizing performance, let’s talk about troubleshooting.

Congratulations! You have successfully installed MongoDB. Thanks for using this tutorial for installing MongoDB NoSQL database on your CentOS Stream 10 system. For additional help or useful information, we recommend you check the official MongoDB website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button