How To Install MongoDB on Rocky Linux 10
MongoDB stands as one of the most popular NoSQL databases in modern application development, offering exceptional scalability and flexibility for handling diverse data types. Rocky Linux 10, being an enterprise-grade Linux distribution, provides an ideal foundation for MongoDB deployments in production environments. This comprehensive tutorial will walk you through multiple installation methods, security configuration, and optimization techniques to ensure your MongoDB setup performs optimally.
Whether you’re deploying MongoDB for development purposes or production workloads, understanding the proper installation and configuration process is crucial for database reliability and security. This guide covers everything from basic installation to advanced security hardening, ensuring you have a robust MongoDB environment on Rocky Linux 10.
Prerequisites and System Requirements
Before beginning the MongoDB installation process, ensure your Rocky Linux 10 system meets the necessary requirements for optimal performance and compatibility.
Hardware Requirements
MongoDB performs best with adequate system resources. Minimum requirements include 2GB of RAM, though 4GB or more is recommended for production environments. The system should have at least 2 CPU cores and sufficient disk space for your anticipated data storage needs. Plan for additional space beyond your data requirements for logs, backups, and temporary files.
Production environments should consider 8GB or more RAM and multiple CPU cores for handling concurrent connections effectively. Storage type significantly impacts performance – SSD storage is highly recommended over traditional hard drives for better I/O performance.
Software Prerequisites
Your Rocky Linux 10 system must be up-to-date with a functioning package manager. Root access or sudo privileges are essential for installing packages and configuring system services. Network connectivity is required for downloading MongoDB packages from official repositories.
Ensure the DNF package manager is available and functioning correctly. The system firewall should be configured to allow necessary network connections. SELinux policies may need adjustment depending on your security requirements and MongoDB configuration.
Version Compatibility
MongoDB 8.0 represents the latest stable version with full Rocky Linux 10 compatibility. The Community Edition provides robust functionality for most use cases, while Enterprise Edition offers additional features for large-scale deployments. Consider your specific requirements when selecting between versions, as newer versions may include performance improvements and security enhancements.
Understanding MongoDB Architecture
MongoDB operates through several key components that work together to provide database functionality. Understanding these components helps in proper configuration and troubleshooting.
MongoDB Components
The MongoDB daemon (mongod) serves as the primary database process, handling data storage, query processing, and client connections. This process runs continuously in the background and manages all database operations. The MongoDB shell (mongosh) provides an interactive JavaScript interface for database administration and querying.
Configuration files control various aspects of MongoDB behavior, including network settings, storage options, and security parameters. These files allow fine-tuning of performance characteristics and operational behavior.
Default Configuration
MongoDB uses port 27017 by default for client connections. The service binds to localhost (127.0.0.1) by default, restricting connections to local applications only. Data files are stored in /var/lib/mongo
, while log files are written to /var/log/mongodb
.
Understanding these default locations helps in maintenance tasks, backup procedures, and troubleshooting efforts. Custom configurations can modify these paths based on specific requirements or security policies.
Method 1: Installing MongoDB via Official Repository
The recommended approach for installing MongoDB on Rocky Linux 10 involves adding the official MongoDB repository to your system. This method ensures you receive the latest updates and security patches directly from MongoDB Inc.
Adding MongoDB Repository
Create a new repository configuration file to enable DNF access to MongoDB packages. This file tells the package manager where to find MongoDB software and how to verify its authenticity.
sudo nano /etc/yum.repos.d/mongodb-org-8.0.repo
Add the following repository configuration content to the file:
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc
This configuration specifies the repository location, enables GPG signature verification for security, and provides the public key for package verification. The $releasever
variable automatically uses your Rocky Linux version number.
Import the GPG key to verify package authenticity:
sudo rpm --import https://www.mongodb.org/static/pgp/server-8.0.asc
Verify the repository configuration by updating the package cache:
sudo dnf makecache
Installing MongoDB Packages
With the repository configured, install MongoDB using DNF. The mongodb-org
meta-package includes all necessary components for a complete MongoDB installation.
sudo dnf install mongodb-org -y
This command installs several packages: mongodb-org-server
(the mongod daemon), mongodb-org-shell
(the command-line interface), mongodb-org-mongos
(sharding router), mongodb-org-tools
(utility programs), and mongodb-org-database-tools-extra
(additional utilities).
Verify the installation by checking installed packages:
sudo dnf list installed | grep mongodb
The installation process creates necessary user accounts, directories, and configuration files automatically. Review the installation output for any warnings or errors that might require attention.
Starting and Enabling MongoDB Service
MongoDB operates as a systemd service on Rocky Linux 10. Start the service and configure it to launch automatically at system boot.
sudo systemctl start mongod
sudo systemctl enable mongod
Verify the service status to ensure MongoDB is running correctly:
sudo systemctl status mongod
A successful startup shows an “active (running)” status with recent log entries indicating proper initialization. If the service fails to start, check the MongoDB log files for error messages.
Test connectivity to confirm MongoDB is accepting connections:
sudo ss -tulpn | grep 27017
This command should show MongoDB listening on port 27017, confirming the service is operational and ready for client connections.
Method 2: Installing Specific MongoDB Versions
Different MongoDB versions may be required for specific applications or compatibility requirements. Understanding how to install particular versions provides flexibility in deployment scenarios.
MongoDB 6.0 Installation
For applications requiring MongoDB 6.0, create a version-specific repository configuration. This approach is useful when working with legacy applications or specific version requirements.
sudo nano /etc/yum.repos.d/mongodb-org-6.0.repo
Use the appropriate repository URL for version 6.0:
[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
Install the specific version using the same DNF command structure, ensuring compatibility with your application requirements.
MongoDB 5.0 Installation
Legacy applications might require MongoDB 5.0 for compatibility reasons. While this version is older, it remains stable and supported for existing deployments.
Follow similar repository configuration steps, adjusting the URL and GPG key path for version 5.0. Consider the implications of using older versions, including potential security vulnerabilities and missing features.
Version Selection Best Practices
Choose MongoDB versions based on application compatibility, security requirements, and long-term support considerations. Production environments should prioritize stability and security updates over newest features. Development environments can use latest versions to test new capabilities.
Document version selections and maintain upgrade paths for future migrations. Consider the MongoDB release lifecycle and support timeline when making version decisions.
Post-Installation Configuration
Proper configuration ensures optimal MongoDB performance and security. These steps customize MongoDB behavior for your specific environment and requirements.
Verifying Installation
Confirm MongoDB installation success by checking the version and service status. These verification steps help identify any installation issues before proceeding with configuration.
mongod --version
This command displays the installed MongoDB version, build information, and compilation details. Compare the output with your expected version to confirm correct installation.
Test database connectivity using the MongoDB shell:
mongosh
A successful connection displays the MongoDB shell prompt and database connection information. Exit the shell using the exit
command or Ctrl+C.
Basic Configuration Optimization
The MongoDB configuration file /etc/mongod.conf
controls various operational parameters. Edit this file to customize behavior for your specific use case.
sudo nano /etc/mongod.conf
Key configuration options include:
bindIp
: Controls which network interfaces MongoDB accepts connections onport
: Specifies the listening port (default 27017)dbPath
: Defines the data storage directorylogPath
: Sets the log file location
Memory usage optimization involves configuring the WiredTiger storage engine cache size. By default, MongoDB uses approximately 50% of available RAM for caching. Adjust this based on your system’s memory allocation requirements.
Network binding configuration determines connection accessibility. The default 127.0.0.1
setting restricts connections to local applications only. Modify this setting carefully, considering security implications.
System Optimization for MongoDB
Transparent Huge Pages (THP) can negatively impact MongoDB performance. Disable THP for optimal database performance:
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
Make this change permanent by adding the commands to system startup scripts.
File descriptor limits should be increased for high-connection workloads. Edit /etc/security/limits.conf
to raise limits for the MongoDB user account. This prevents connection failures due to system resource limitations.
MongoDB Security Configuration
Security hardening is critical for production MongoDB deployments. These configurations protect your database from unauthorized access and potential security threats.
Enabling Authentication
MongoDB installations default to no authentication requirements, which poses security risks. Enable authentication to control database access through user accounts and permissions.
Start the MongoDB shell and create an administrative user:
mongosh
Switch to the admin database and create the administrative account:
use admin
db.createUser({
user: "admin",
pwd: "your_secure_password",
roles: ["userAdminAnyDatabase", "readWriteAnyDatabase"]
})
Replace your_secure_password
with a strong password following security best practices. Use complex passwords with mixed case letters, numbers, and special characters.
Enable authentication by editing the MongoDB configuration file:
sudo nano /etc/mongod.conf
Add or modify the security section:
security:
authorization: enabled
Restart MongoDB to apply the authentication changes:
sudo systemctl restart mongod
Test authentication by connecting with credentials:
mongosh -u admin -p --authenticationDatabase admin
Network Security
Firewall configuration should allow MongoDB connections only from trusted sources. Configure firewalld to control network access:
sudo firewall-cmd --permanent --add-port=27017/tcp
sudo firewall-cmd --reload
For environments requiring external connections, modify the bindIp
configuration to include appropriate network interfaces. Exercise caution when binding to public interfaces.
SSL/TLS encryption protects data in transit between clients and the MongoDB server. Configure SSL certificates for encrypted connections, especially in production environments handling sensitive data.
Additional Security Measures
File permissions should restrict access to MongoDB data and configuration files. Ensure only the MongoDB user account can access database files:
sudo chmod 700 /var/lib/mongo
sudo chown -R mongod:mongod /var/lib/mongo
Implement regular security auditing to monitor database access and identify potential security issues. MongoDB Enterprise Edition provides enhanced auditing capabilities for comprehensive security monitoring.
Basic MongoDB Operations
Understanding fundamental MongoDB operations helps verify proper installation and provides a foundation for database administration tasks.
Connecting to MongoDB
The MongoDB shell (mongosh) provides an interactive interface for database operations. Connect to your MongoDB instance using various authentication methods.
Local connection without authentication:
mongosh
Authenticated connection using username and password:
mongosh -u admin -p --authenticationDatabase admin
Connection strings provide flexible connectivity options for different network configurations and authentication requirements.
Basic Database Operations
Create a database by switching to it and inserting data:
use testdb
db.users.insertOne({name: "Nadia Shel", email: "nads@example.com"})
View databases and collections:
show dbs
show collections
Basic queries demonstrate MongoDB’s document-oriented nature:
db.users.find()
db.users.find({name: "Nadia Shel"})
These operations confirm MongoDB functionality and provide familiarity with the database interface.
Backup and Restore Basics
MongoDB backup utilities include mongodump
and mongorestore
for data protection. Regular backups ensure data recovery capabilities in case of system failures or data corruption.
mongodump --db testdb --out /backup/mongodb/
Restore data using the corresponding restore utility:
mongorestore --db testdb /backup/mongodb/testdb/
Establish backup schedules and test restore procedures regularly to ensure data protection effectiveness.
Troubleshooting Common Issues
MongoDB installations may encounter various issues. Understanding common problems and their solutions helps maintain system reliability.
Installation Issues
Repository access problems often result from network connectivity issues or incorrect repository URLs. Verify internet connectivity and repository configuration accuracy. DNS resolution problems can prevent package downloads.
GPG key verification failures indicate security concerns or configuration errors. Re-import GPG keys and verify repository authenticity before proceeding with package installation.
Package dependency conflicts may occur with existing software installations. Use DNF’s dependency resolution features to identify and resolve conflicts systematically.
Service Issues
MongoDB service startup failures commonly result from configuration errors, permission problems, or resource constraints. Check log files in /var/log/mongodb/
for specific error messages.
Port binding problems indicate conflicts with other services or firewall restrictions. Verify port availability and firewall configurations. Change MongoDB’s default port if conflicts persist.
Permission-related errors affect data directory access and log file writing. Ensure proper ownership and permissions for MongoDB directories and files.
Performance Issues
Memory usage optimization requires understanding MongoDB’s caching behavior and system resource allocation. Monitor memory usage patterns and adjust cache sizes accordingly.
Disk I/O considerations impact database performance significantly. Use faster storage devices and optimize disk configurations for better performance.
Connection limit adjustments prevent connection exhaustion in high-traffic environments. Configure appropriate connection pool sizes and timeouts.
Maintenance and Best Practices
Regular maintenance ensures MongoDB continues operating efficiently and securely. These practices prevent common issues and optimize performance.
Regular Maintenance Tasks
Log rotation prevents log files from consuming excessive disk space. Configure logrotate or MongoDB’s built-in log rotation features:
sudo logrotate -f /etc/logrotate.d/mongod
Database optimization includes index maintenance and collection statistics updates. Regular optimization improves query performance and storage efficiency.
Index maintenance involves monitoring index usage and removing unused indexes to improve write performance and reduce storage requirements.
Monitoring and Logging
Built-in monitoring tools provide insights into MongoDB performance and resource usage. Use MongoDB Compass or other monitoring solutions for comprehensive oversight.
Log file analysis helps identify performance bottlenecks, security issues, and operational problems. Regular log review enables proactive issue resolution.
Performance metrics tracking includes monitoring CPU usage, memory consumption, disk I/O, and network activity related to MongoDB operations.
Update and Upgrade Procedures
MongoDB version upgrades require careful planning and testing. Always backup data before performing version upgrades and test the upgrade process in non-production environments.
Rolling upgrade strategies minimize downtime in replica set configurations. Plan upgrade sequences to maintain high availability during the upgrade process.
Maintain documentation of upgrade procedures and rollback plans for critical production systems.
Alternative Installation Methods
Different installation approaches suit various deployment scenarios and organizational requirements.
Docker Installation
MongoDB Docker containers provide consistent deployment environments across different systems. Docker simplifies dependency management and isolation.
docker run --name mongodb -p 27017:27017 -d mongo:8.0
Docker Compose configurations enable complex multi-container deployments with volume persistence and network configurations. Define services, networks, and storage requirements in YAML format.
Container management best practices include resource limits, health checks, and proper volume mounting for data persistence.
Manual Installation
Binary installation provides maximum control over installation paths and configuration options. Download MongoDB binaries directly from the official website and configure manually.
Custom installation paths allow integration with existing system layouts and organizational standards. Manual installation requires more configuration effort but offers flexibility.
Manual service configuration involves creating systemd service files and configuring startup procedures without package manager automation.
Congratulations! You have successfully installed MongoDB. Thanks for using this tutorial for installing the MongoDB NoSQL database on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official MongoDB website.