How To Install MongoDB on Fedora 42
Installing MongoDB on Fedora 42 requires careful attention to repository configuration and security practices. This comprehensive guide walks you through every step of the installation process, from initial setup to advanced configuration and troubleshooting.
MongoDB’s document-oriented NoSQL architecture makes it an essential database solution for modern web applications. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents that can vary in structure. This flexibility, combined with horizontal scaling capabilities, has made MongoDB a popular choice among developers building dynamic applications.
Fedora users face unique challenges when installing MongoDB due to licensing considerations. The Server Side Public License (SSPL) under which MongoDB operates led to its removal from default Fedora repositories. However, MongoDB’s official repositories provide a reliable installation path that ensures you receive the latest stable releases with proper security updates.
This guide covers everything from basic installation to production-ready configuration, ensuring your MongoDB deployment is secure, optimized, and maintainable.
Prerequisites and System Requirements
Before beginning the MongoDB installation on Fedora 42, verify your system meets the necessary requirements. Your system needs at least 4GB of RAM for optimal performance, though MongoDB can run with less memory for development purposes. Ensure you have adequate disk space—allocate at least 10GB for the database files, logs, and temporary storage.
Administrative privileges are essential throughout this process. You’ll need sudo access to install packages, modify system configurations, and manage services. A stable internet connection is required to download packages from MongoDB’s official repository and any dependencies.
Basic familiarity with the terminal and text editors like nano
or vim
will help you navigate the configuration process efficiently. Understanding fundamental Linux concepts such as services, file permissions, and package management will enhance your ability to troubleshoot any issues that arise.
Understanding MongoDB Licensing and Availability on Fedora
MongoDB’s absence from default Fedora repositories stems from licensing compatibility issues. The Server Side Public License (SSPL) that governs MongoDB conflicts with Fedora’s commitment to Free Software principles. This licensing model requires organizations providing MongoDB as a service to open-source their entire service stack, which creates complications for some use cases.
The Fedora Project has expressed security concerns about including MongoDB in their default repositories. These concerns relate to the complexity of maintaining security patches and ensuring timely updates across different MongoDB versions. By using MongoDB’s official repository, you bypass these distribution-level concerns while receiving updates directly from the developers.
MongoDB’s official stance supports installation on Red Hat Enterprise Linux and compatible distributions, including Fedora. The company provides dedicated repository configurations that ensure compatibility and security. While this approach requires additional configuration steps, it guarantees access to the latest features and security patches.
Understanding these licensing implications helps you make informed decisions about MongoDB deployment in your organization. For commercial deployments, review the SSPL terms carefully to ensure compliance with your business model.
Method 1: Installing MongoDB via Official Repository
Adding the MongoDB Repository
The first step involves configuring MongoDB’s official repository on your Fedora 42 system. This process requires creating a repository configuration file that tells the DNF package manager where to find MongoDB packages.
Create the repository configuration file using your preferred text editor:
sudo nano /etc/yum.repos.d/mongodb-org-8.0.repo
Add the following repository configuration:
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
This configuration specifies the repository URL, enables GPG signature verification, and points to MongoDB’s public key for package authentication. The baseurl
points to the Red Hat 9 repository, which maintains compatibility with Fedora systems due to their shared Enterprise Linux heritage.
Save and close the file after entering the configuration. The GPG key verification ensures package integrity and authenticity, protecting against tampered or malicious packages.
Installing MongoDB Packages
With the repository configured, update your system’s package cache to recognize the new MongoDB repository:
sudo dnf makecache
This command downloads package metadata from all enabled repositories, including the newly added MongoDB repository. The process may take a few moments depending on your internet connection speed.
Install MongoDB using the DNF package manager:
sudo dnf install mongodb-org
The installation includes several components:
- mongodb-org-server: The core mongod daemon that manages data storage
- mongodb-org-mongos: The routing service for sharded clusters
- mongodb-org-shell: The MongoDB command-line interface (mongosh)
- mongodb-org-tools: Utilities for import, export, and database administration
During installation, DNF automatically resolves dependencies and downloads required packages. The process typically downloads 200-300MB of data, depending on system architecture and existing dependencies.
Verify the installation by checking the MongoDB version:
mongod --version
This command displays version information and confirms successful installation. The output should show MongoDB version 8.0.x along with build information and supported storage engines.
Service Configuration and Startup
MongoDB installation includes systemd service configuration for automatic startup and management. Start the MongoDB service using:
sudo systemctl start mongod.service
Enable MongoDB to start automatically during system boot:
sudo systemctl enable mongod.service
Verify the service status to ensure proper operation:
sudo systemctl status mongod.service
The status command displays detailed information about the service state. A properly configured service shows “active (running)” status with recent log entries indicating successful startup.
If the service fails to start, check the system logs for error messages:
sudo journalctl -u mongod.service --no-pager -l
Common startup issues include permission problems, port conflicts, or configuration errors. The service logs provide specific error messages that guide troubleshooting efforts.
Method 2: Alternative Installation Approaches
Installing Different MongoDB Versions
While MongoDB 8.0 represents the latest stable release, some applications require specific versions for compatibility. To install MongoDB 7.0 or earlier versions, modify the repository configuration accordingly.
For MongoDB 7.0, create a different repository file:
sudo nano /etc/yum.repos.d/mongodb-org-7.0.repo
Use this configuration for MongoDB 7.0:
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-7.0.asc
After creating the appropriate repository file, follow the same installation steps using dnf install mongodb-org
. This approach allows you to maintain specific version requirements while benefiting from official repository updates.
Version-specific installations require careful consideration of feature compatibility and upgrade paths. MongoDB maintains backward compatibility within major versions, but significant changes occur between major releases.
Manual Installation Considerations
Docker provides an alternative deployment method that isolates MongoDB from the host system. This approach offers consistent environments across different systems and simplified backup procedures.
To install MongoDB via Docker:
sudo dnf install docker
sudo systemctl start docker
sudo systemctl enable docker
sudo docker pull mongo:8.0
Run MongoDB in a Docker container:
sudo docker run --name mongodb -d -p 27017:27017 -v mongodb_data:/data/db mongo:8.0
Docker deployment simplifies version management and provides built-in isolation. However, it requires additional Docker knowledge and resource overhead compared to native installation.
Post-Installation Configuration
Initial MongoDB Connection and Testing
After successful installation, establish your first connection to MongoDB using the mongosh
command-line client. This modern shell replaces the legacy mongo shell and provides enhanced functionality.
Connect to your MongoDB instance:
mongosh
The shell connects to localhost:27017
by default, displaying connection information and MongoDB version details. A successful connection shows the MongoDB prompt, indicating your installation is operational.
Test basic database operations to verify functionality:
use testdb
db.users.insertOne({name: "John", email: "john@example.com"})
db.users.findOne()
These commands create a test database, insert a document, and retrieve it. Successful execution confirms that MongoDB is properly configured and accepting operations.
Exit the MongoDB shell by typing exit
or pressing Ctrl+C. This initial testing verifies that your installation can handle basic database operations before proceeding to advanced configuration.
Configuration File Customization
MongoDB’s configuration file, located at /etc/mongod.conf
, controls various operational parameters. Understanding and customizing this file optimizes MongoDB for your specific environment.
View the default configuration:
sudo cat /etc/mongod.conf
The configuration uses YAML format and includes sections for storage, network, and logging parameters. Key areas include:
Network Configuration: Controls which interfaces MongoDB binds to and the listening port. The default configuration binds only to localhost for security.
Storage Settings: Defines data directory paths and storage engine options. The WiredTiger storage engine is the default and recommended option for most use cases.
Logging Configuration: Specifies log file locations and verbosity levels. Proper logging configuration aids troubleshooting and monitoring.
Create a backup before modifying the configuration:
sudo cp /etc/mongod.conf /etc/mongod.conf.backup
Edit the configuration file to customize settings:
sudo nano /etc/mongod.conf
After making changes, restart MongoDB to apply the new configuration:
sudo systemctl restart mongod.service
Always verify that MongoDB starts successfully after configuration changes. Monitor the service logs for any error messages that indicate configuration problems.
Security Configuration and User Authentication
Enabling Authentication
MongoDB installations default to no authentication for simplicity, but production deployments require proper user authentication. This security measure prevents unauthorized access to your databases and protects sensitive information.
Before enabling authentication, create an administrative user while authentication is disabled. Connect to MongoDB:
mongosh
Switch to the admin database and create the first user:
use admin
db.createUser({
user: "admin",
pwd: "securePassword123",
roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
})
Replace "securePassword123"
with a strong password that includes uppercase letters, lowercase letters, numbers, and special characters. This administrative user has comprehensive privileges across all databases.
Enable authentication by editing the MongoDB configuration file:
sudo nano /etc/mongod.conf
Add or uncomment the security section:
security:
authorization: enabled
Restart MongoDB to enable authentication:
sudo systemctl restart mongod.service
Test authentication by connecting with credentials:
mongosh -u admin -p securePassword123 --authenticationDatabase admin
Successful authentication confirms that security measures are properly configured and operational.
User Management and Role-Based Access
MongoDB’s role-based access control system provides granular permissions for different users and applications. This approach follows the principle of least privilege, granting only necessary permissions to each user.
Create database-specific users with limited privileges. Connect as the administrative user and switch to your application database:
use myapp
db.createUser({
user: "appuser",
pwd: "appPassword456",
roles: ["readWrite"]
})
This user can read and write documents in the “myapp” database but cannot access other databases or perform administrative functions.
MongoDB includes several built-in roles:
- read: Provides read-only access to specified databases
- readWrite: Allows reading and writing documents and indexes
- dbAdmin: Grants database administration privileges
- userAdmin: Enables user and role management for specific databases
Test user permissions by connecting with the new credentials:
mongosh -u appuser -p appPassword456 --authenticationDatabase myapp
Verify that the user can perform authorized operations but receives errors when attempting unauthorized actions. This testing confirms that role-based access control is functioning correctly.
MongoDB Management and Maintenance
Service Management Commands
Effective MongoDB administration requires familiarity with systemd service management commands. These tools control MongoDB startup, shutdown, and monitoring processes.
Start MongoDB when needed:
sudo systemctl start mongod.service
Stop MongoDB gracefully during maintenance:
sudo systemctl stop mongod.service
Restart MongoDB after configuration changes:
sudo systemctl restart mongod.service
Check service status and recent activity:
sudo systemctl status mongod.service --no-pager -l
The --no-pager
option displays full output without pagination, while -l
shows complete log lines without truncation. This combination provides comprehensive status information for troubleshooting.
Monitor MongoDB logs in real-time:
sudo tail -f /var/log/mongodb/mongod.log
Real-time log monitoring helps identify performance issues, connection problems, and security events as they occur.
Backup and Maintenance Basics
Regular backups protect against data loss and enable disaster recovery. MongoDB provides several backup strategies depending on your requirements and infrastructure.
Use mongodump
for logical backups that export data in BSON format:
mongodump --host localhost:27017 --out /backup/mongodb/$(date +%Y%m%d)
This command creates a complete backup of all databases in a timestamped directory. The backup includes documents, indexes, and collection metadata.
Restore data from backups using mongorestore
:
mongorestore --host localhost:27017 /backup/mongodb/20240815
For large databases, consider incremental backups or replica set configurations that provide continuous data protection. These advanced strategies minimize backup time and recovery point objectives.
Schedule regular maintenance tasks including index optimization and log rotation. MongoDB’s built-in maintenance features handle most routine tasks automatically, but periodic monitoring ensures optimal performance.
Troubleshooting Common Issues
Installation Problems
Repository access issues often prevent successful MongoDB installation. Verify repository configuration by checking the file contents:
cat /etc/yum.repos.d/mongodb-org-8.0.repo
Ensure the repository URL is accessible and GPG keys are properly configured. Network connectivity problems may require proxy configuration or firewall adjustments.
GPG key verification failures can halt installation. Manually import MongoDB’s GPG key if automatic verification fails:
sudo rpm --import https://pgp.mongodb.com/server-8.0.asc
Package dependency conflicts sometimes occur with existing software. Use DNF’s conflict resolution features to identify and resolve conflicting packages:
sudo dnf install mongodb-org --allowerasing
The --allowerasing
option allows DNF to remove conflicting packages, but review the proposed changes carefully before proceeding.
SELinux policies may prevent MongoDB installation or operation. Check SELinux status and temporarily disable it for testing:
sudo getenforce
sudo setenforce 0
If MongoDB works with SELinux disabled, configure appropriate policies rather than permanently disabling SELinux.
Service and Connection Issues
MongoDB service startup failures often indicate configuration or permission problems. Examine service logs for specific error messages:
sudo journalctl -u mongod.service --since "1 hour ago"
Common startup issues include:
Port Conflicts: Another service using port 27017 prevents MongoDB startup. Check for conflicting services:
sudo netstat -tlnp | grep 27017
Permission Errors: Incorrect file permissions on data directories cause startup failures. Fix MongoDB directory ownership:
sudo chown -R mongod:mongod /var/lib/mongo
sudo chown -R mongod:mongod /var/log/mongodb
Configuration Errors: YAML syntax errors in the configuration file prevent service startup. Validate configuration syntax using online YAML validators or by attempting to restart the service.
Connection timeout problems may indicate network configuration issues. Verify that MongoDB listens on the expected interface:
sudo netstat -tlnp | grep mongod
Firewall rules might block MongoDB connections. Configure firewalld to allow MongoDB traffic:
sudo firewall-cmd --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
Performance Optimization and Best Practices
MongoDB performance depends on proper system configuration and resource allocation. Several system-level optimizations enhance database performance.
Memory Configuration: MongoDB benefits from large amounts of available memory for caching. Adjust the vm.max_map_count parameter for optimal memory mapping:
echo 'vm.max_map_count=262144' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
Transparent Huge Pages: Disable transparent huge pages to prevent performance degradation:
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 it to system startup scripts:
sudo nano /etc/rc.local
Add these lines to disable transparent huge pages at boot:
echo 'never' > /sys/kernel/mm/transparent_hugepage/enabled
echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag
File Descriptor Limits: Increase system file descriptor limits to support high connection counts:
echo 'mongod soft nofile 64000' | sudo tee -a /etc/security/limits.conf
echo 'mongod hard nofile 64000' | sudo tee -a /etc/security/limits.conf
Monitor MongoDB performance using built-in tools and system monitoring utilities. Regular performance analysis identifies optimization opportunities and prevents resource exhaustion.
Uninstalling MongoDB
Complete MongoDB removal requires stopping services, removing packages, and cleaning data directories. This process ensures no residual files remain on your system.
Stop the MongoDB service before removal:
sudo systemctl stop mongod.service
Disable the service to prevent startup attempts:
sudo systemctl disable mongod.service
Remove all MongoDB packages:
sudo dnf erase $(rpm -qa | grep mongodb-org)
This command identifies all MongoDB-related packages and removes them completely. The process may take several minutes depending on the number of installed components.
Remove MongoDB data directories and log files:
sudo rm -rf /var/lib/mongo
sudo rm -rf /var/log/mongodb
Warning: This step permanently deletes all MongoDB data. Ensure you have proper backups before proceeding.
Remove MongoDB configuration files:
sudo rm -f /etc/mongod.conf
sudo rm -f /etc/yum.repos.d/mongodb-org-*.repo
Clean the package cache to remove downloaded MongoDB packages:
sudo dnf clean packages
Verify complete removal by searching for remaining MongoDB files:
sudo find / -name "*mongo*" 2>/dev/null
Any remaining files can be manually removed if they’re not needed by other applications.
Congratulations! You have successfully installed MongoDB. Thanks for using this tutorial for installing the MongoDB database on your Fedora 42 Linux system. For additional Apache or useful information, we recommend you check the official MongoDB website.