How to Install MongoDB on Fedora

Install MongoDB on Fedora

Installing MongoDB on Fedora can seem daunting, but it’s actually quite straightforward when you know the right steps. Whether you’re a developer building the next big web application or a system administrator managing databases, this comprehensive guide will walk you through every aspect of getting MongoDB up and running on your Fedora system.

MongoDB has become one of the most popular NoSQL databases in the world, and for good reason. Its flexible document-oriented structure makes it perfect for modern applications that need to handle diverse data types and scale rapidly. When combined with Fedora’s cutting-edge features and stability, you get a powerful database platform that’s ready for production use.

What is MongoDB and Why Use It on Fedora?

Understanding MongoDB’s Document-Oriented Architecture

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents called BSON (Binary JSON). Unlike traditional relational databases that use tables and rows, MongoDB organizes data in collections and documents, making it incredibly versatile for handling complex, nested data structures.

This flexibility means you can store different types of data in the same collection without having to define a rigid schema upfront. For example, one document might contain user profile information with basic fields like name and email, while another document in the same collection might include additional fields like social media links or preferences.

The document model naturally maps to objects in programming languages, making it easier for developers to work with. This reduces the impedance mismatch between your application code and the database, resulting in faster development cycles and fewer bugs.

Benefits of Using MongoDB on Fedora Linux

Fedora provides an excellent platform for running MongoDB, especially for development and testing environments. The distribution’s commitment to including the latest software versions means you’ll have access to modern tools and libraries that complement MongoDB perfectly.

Fedora’s package management system, DNF, makes it relatively easy to install and maintain MongoDB, though there are some specific considerations we’ll cover. The operating system’s robust security features also align well with MongoDB’s security capabilities, giving you multiple layers of protection for your data.

Additionally, Fedora’s active community and excellent documentation make it easier to troubleshoot issues and find solutions when you encounter problems during installation or configuration.

Prerequisites and System Requirements

Minimum Hardware Requirements

Before installing MongoDB, ensure your Fedora system meets the minimum requirements. MongoDB needs at least 4GB of RAM for optimal performance, though you can run it with less for development purposes. The database engine is quite efficient, but having adequate memory is crucial for good performance, especially when dealing with large datasets or multiple concurrent connections.

For storage, allocate at least 10GB of free disk space, though this depends heavily on your expected data size. MongoDB uses memory-mapped files, so faster storage (like SSDs) will significantly improve performance compared to traditional hard drives.

Supported Fedora Versions

MongoDB officially supports installation on Fedora through Red Hat Enterprise Linux (RHEL) compatibility. This means you can use the RHEL installation packages on Fedora versions 34, 35, 36, 38, 39, and 41. However, MongoDB doesn’t guarantee full compatibility with Fedora, and newer versions might occasionally have issues.

The most reliable experience typically comes from using Fedora versions that align closely with supported RHEL releases. If you’re running a very recent Fedora version, you might need to use workarounds or alternative installation methods.

Required Permissions and Tools

You’ll need sudo or root access to install MongoDB and configure system services. Make sure you have a terminal application available and basic familiarity with command-line operations. The installation process involves editing system configuration files and managing systemd services, so administrative privileges are essential.

Additionally, ensure your system has internet connectivity for downloading packages and repository information. The installation process will fetch several packages from MongoDB’s official repositories.

Method 1: Installing MongoDB from Official Repository

Adding the MongoDB Repository

The first step in installing MongoDB on Fedora is adding the official MongoDB repository to your system. This ensures you get the latest stable version directly from MongoDB Inc., rather than potentially outdated packages from Fedora’s repositories.

Create a new repository file for MongoDB 6.0 (or your desired version):

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

Add the following content to the file:

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

This configuration tells DNF where to find MongoDB packages and ensures package integrity through GPG signature verification. The baseurl points to the Red Hat 9 repository, which is compatible with recent Fedora versions.

Save the file and exit your text editor. The repository is now configured and ready for package installation.

Installing MongoDB Packages

With the repository configured, you can now install MongoDB using DNF:

sudo dnf install mongodb-org

This command installs the complete MongoDB package, including the server (mongod), the MongoDB shell (mongosh), and various utilities. The installation process might take a few minutes depending on your internet connection speed and system performance.

If you encounter any package conflicts or dependency issues, DNF will typically provide helpful suggestions for resolving them. Pay attention to any warning messages, as they might indicate compatibility concerns with your specific Fedora version.

Verifying the Installation

After installation completes, verify that MongoDB installed correctly by checking the version:

mongod --version

This should display version information for the MongoDB server. If you see version details, the installation was successful. You can also check if the MongoDB service files were installed properly:

systemctl list-unit-files | grep mongod

This command should show the mongod.service file, indicating that the systemd service configuration is in place.

Method 2: Installing MongoDB with OpenSSL 3 Support

Understanding OpenSSL Compatibility Issues

Newer versions of Fedora (39 and later) use OpenSSL 3, which can cause compatibility issues with some MongoDB packages. The standard MongoDB packages were built with OpenSSL 1.1.1, leading to library conflicts and connection problems when using the MongoDB shell.

These compatibility issues typically manifest as SSL/TLS errors when trying to connect to MongoDB instances or when using encrypted connections. The symptoms include connection timeouts, SSL handshake failures, and cryptographic library errors.

Configuration Steps for OpenSSL 3

For Fedora 39 and later versions, you need to modify the repository configuration to use OpenSSL 3-compatible packages. Edit your repository file to use the specialized URL:

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

Update the baseurl to:

baseurl=https://repo.mongodb.org/yum/redhat/9Server/mongodb-org/6.0/x86_64/

This modified URL provides packages compiled with OpenSSL 3 support, ensuring compatibility with recent Fedora versions. After making this change, update your package cache:

sudo dnf clean all
sudo dnf makecache

Then proceed with the standard installation:

sudo dnf install mongodb-org

This approach resolves most OpenSSL-related compatibility issues and provides a more stable MongoDB installation on newer Fedora versions.

Starting and Enabling MongoDB Service

Using Systemctl Commands

Once MongoDB is installed, you need to start the database service. MongoDB runs as a systemd service called mongod, which you can control using standard systemctl commands.

Start the MongoDB service:

sudo systemctl start mongod.service

This command launches the MongoDB daemon, which begins listening for database connections on the default port (27017). The service runs in the background and maintains your databases even after you close your terminal session.

Checking Service Status

Verify that MongoDB started successfully:

sudo systemctl status mongod.service

This command displays detailed information about the service status, including whether it’s running, any error messages, and recent log entries. A properly running MongoDB service should show “active (running)” status with green indicators.

If the service failed to start, the status output will include error messages that can help you diagnose the problem. Common issues include permission problems, configuration errors, or port conflicts.

Enabling Auto-Start on Boot

To ensure MongoDB starts automatically when your system boots:

sudo systemctl enable mongod.service

This creates the necessary symbolic links to start MongoDB during the system initialization process. Without this step, you’ll need to manually start MongoDB each time you restart your computer.

You can verify that auto-start is enabled by checking the service status again – it should show “enabled” in the status information.

Initial MongoDB Configuration

Accessing MongoDB Shell (mongosh)

With MongoDB running, you can connect to it using the MongoDB shell (mongosh). This interactive JavaScript interface allows you to perform database operations, run queries, and administer your MongoDB instance.

Connect to your local MongoDB instance:

mongosh

If everything is working correctly, you should see output similar to:

Current Mongosh Log ID: [unique-id]
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true
Using MongoDB: 6.0.x
Using Mongosh: [version]

This indicates successful connection to your MongoDB server. The shell provides a JavaScript environment where you can interact with your databases using MongoDB’s query language.

Basic Database Operations

Once connected to the MongoDB shell, you can perform basic operations to test your installation. Create a test database:

use testdb

Insert a document into a collection:

db.users.insertOne({name: "John Doe", email: "[email protected]", age: 30})

Query the data to verify it was stored correctly:

db.users.find()

These basic operations confirm that your MongoDB installation can create databases, collections, and documents successfully. If these commands work without errors, your installation is functioning properly.

Configuration File Settings

MongoDB’s main configuration file is located at /etc/mongod.conf. This YAML-formatted file controls various aspects of MongoDB’s behavior, including network settings, storage options, and security configurations.

Key configuration options include:

  • bindIp: Controls which IP addresses MongoDB listens on (default: 127.0.0.1)
  • port: The port number for database connections (default: 27017)
  • dbPath: Directory where MongoDB stores data files (default: /var/lib/mongo)
  • logPath: Location of MongoDB log files (default: /var/log/mongodb/mongod.log)

For most installations, the default configuration works well, but you might need to modify settings based on your specific requirements.

Setting Up User Authentication and Security

Creating Administrative Users

By default, MongoDB starts without authentication enabled, which means anyone with network access can perform any database operation. For production use, you should enable authentication and create administrative users.

First, connect to MongoDB and switch to the admin database:

use admin

Create an administrative user with full privileges:

db.createUser({
  user: "admin",
  pwd: "your_secure_password",
  roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
})

This creates a user with administrative privileges across all databases. Choose a strong password and store it securely, as this account will have complete control over your MongoDB installation.

Enabling Authentication

To enable authentication, you need to modify the MongoDB configuration file. Edit /etc/mongod.conf:

sudo nano /etc/mongod.conf

Add or uncomment the security section:

security:
  authorization: enabled

Save the file and restart MongoDB:

sudo systemctl restart mongod.service

After restarting, you’ll need to authenticate when connecting to MongoDB:

mongosh -u admin -p --authenticationDatabase admin

Database-Specific User Management

For applications, create users with limited privileges for specific databases rather than using administrative accounts. Switch to your application database and create a user:

use myappdb
db.createUser({
  user: "appuser",
  pwd: "app_password",
  roles: ["readWrite"]
})

This approach follows the principle of least privilege, ensuring applications can only access the data they need.

Common Installation Issues and Solutions

Package Compatibility Problems

One of the most frequent issues when installing MongoDB on Fedora is package compatibility. Since MongoDB doesn’t officially support Fedora, you might encounter dependency conflicts or version mismatches.

If you see errors about missing dependencies or conflicting packages, try updating your system first:

sudo dnf update

Sometimes, installing additional compatibility packages helps resolve dependency issues:

sudo dnf install compat-openssl10

OpenSSL Configuration Errors

OpenSSL version conflicts are particularly common on Fedora 39 and later. If you encounter SSL-related errors when using mongosh, the issue is likely related to OpenSSL version mismatches.

The error typically looks like:

MongoServerError: SSL routines::unsafe legacy renegotiation disabled

To resolve this, install MongoDB packages specifically compiled for OpenSSL 3, or use the repository configuration mentioned in the OpenSSL 3 support section.

Service Startup Issues

If MongoDB fails to start, check the system logs for detailed error messages:

sudo journalctl -u mongod.service -f

Common startup issues include:

  • Permission problems: Ensure the mongodb user has access to data and log directories
  • Port conflicts: Another service might be using port 27017
  • Disk space: Insufficient disk space can prevent MongoDB from starting
  • Configuration errors: Syntax errors in mongod.conf will prevent startup

Testing Your MongoDB Installation

Connection Testing

After installation and configuration, thoroughly test your MongoDB setup to ensure everything works correctly. Start with basic connectivity testing using the MongoDB shell:

mongosh --eval "db.adminCommand('ismaster')"

This command should return status information about your MongoDB instance. If authentication is enabled, include credentials:

mongosh -u admin -p --authenticationDatabase admin --eval "db.adminCommand('ismaster')"

Creating Sample Databases

Test database operations by creating a sample database and performing various operations:

use sampledb
db.products.insertMany([
  {name: "Laptop", price: 999, category: "Electronics"},
  {name: "Chair", price: 199, category: "Furniture"},
  {name: "Book", price: 29, category: "Education"}
])

Query the data using different methods:

// Find all products
db.products.find()

// Find products by category
db.products.find({category: "Electronics"})

// Find products within a price range
db.products.find({price: {$gte: 100, $lte: 500}})

Performance Verification

Test MongoDB’s performance with a larger dataset to ensure your installation can handle realistic workloads:

// Insert multiple documents quickly
for(let i = 0; i < 1000; i++) {
  db.testcollection.insertOne({
    index: i,
    data: "Sample data entry " + i,
    timestamp: new Date()
  })
}

// Test query performance
db.testcollection.find({index: {$gt: 500}}).explain("executionStats")

The explain() method provides performance statistics, helping you verify that queries execute efficiently.

Best Practices for MongoDB on Fedora

Security Recommendations

Securing your MongoDB installation is crucial, especially if it’s accessible over a network. Beyond enabling authentication, consider these security measures:

Always change default passwords and use strong, unique credentials for all database users. Implement role-based access control by creating users with minimal necessary privileges rather than using administrative accounts for applications.

Configure firewall rules to restrict network access to MongoDB:

sudo firewall-cmd --permanent --add-port=27017/tcp --source=192.168.1.0/24
sudo firewall-cmd --reload

This example allows MongoDB connections only from the local network subnet. Adjust the source parameter according to your network configuration.

Performance Optimization

Optimize MongoDB performance on Fedora by adjusting several system-level settings. Disable transparent huge pages, which can cause performance issues:

echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag

To make this change permanent, add these commands to your system startup scripts.

Set appropriate file descriptor limits in /etc/security/limits.conf:

mongodb soft nofile 64000
mongodb hard nofile 64000
mongodb soft nproc 32000
mongodb hard nproc 32000

Backup and Maintenance

Establish regular backup procedures to protect your data. MongoDB provides several backup methods, with mongodump being the most straightforward for smaller databases:

mongodump --db myappdb --out /backup/mongodb/$(date +%Y%m%d)

For larger databases or production environments, consider using MongoDB’s built-in replication features or file system snapshots for more efficient backups.

Schedule regular maintenance tasks using cron jobs, including log rotation and index optimization. MongoDB’s logs can grow quite large over time, so implement proper log management:

sudo logrotate -f /etc/logrotate.d/mongod

Troubleshooting Guide

Log File Analysis

When MongoDB issues occur, the log files provide valuable diagnostic information. The main MongoDB log is located at /var/log/mongodb/mongod.log. Common log entries to watch for include:

  • Connection errors indicating network or authentication problems
  • Warning messages about low disk space or memory
  • Index-related warnings suggesting performance optimization opportunities
  • Replication errors if you’re using replica sets

Use tail to monitor logs in real-time:

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

Common Error Messages

Several error messages appear frequently during MongoDB installation and operation on Fedora:

“Failed to start mongod.service”: Usually indicates configuration problems or permission issues. Check the service status and logs for specific details.

“Connection refused”: MongoDB isn’t running or isn’t listening on the expected port. Verify the service is active and check the bindIp configuration.

“Authentication failed”: Incorrect credentials or authentication database. Ensure you’re using the correct username, password, and authentication database.

Recovery Procedures

If MongoDB becomes unresponsive or corrupted, several recovery options are available. For minor issues, try restarting the service:

sudo systemctl restart mongod.service

If MongoDB won’t start due to unclean shutdown, you might need to repair the database:

sudo -u mongodb mongod --repair --dbpath /var/lib/mongo

Warning: Always backup your data before attempting repairs, as this process can result in data loss.

For more serious corruption, restore from a recent backup rather than attempting repairs, as this ensures data integrity and consistency.

Frequently Asked Questions

Q1: Can I install multiple versions of MongoDB on the same Fedora system?
A: Yes, but it requires careful configuration management. You’ll need to use different ports, data directories, and service names for each version. Consider using containers or virtual machines for better isolation when running multiple MongoDB versions.

Q2: Why does MongoDB installation fail on newer Fedora versions?
A: MongoDB packages are primarily designed for Red Hat Enterprise Linux, and newer Fedora versions sometimes introduce changes that break compatibility. The most common issue is OpenSSL version conflicts, which can be resolved using the OpenSSL 3-compatible repository configurations mentioned in this guide.

Q3: How much disk space does MongoDB require for a typical installation?
A: The MongoDB software itself requires about 500MB of disk space. However, database files can grow significantly depending on your data. Plan for at least 10GB of free space for development use, and much more for production databases with substantial data volumes.

Q4: Is it safe to run MongoDB without authentication in a development environment?
A: While MongoDB starts without authentication by default, it’s recommended to enable authentication even in development environments. This practice helps you catch authentication-related issues early and establishes good security habits. You can use simple passwords for development, but always enable authentication.

Q5: What should I do if MongoDB consumes too much memory on my Fedora system?
A: MongoDB uses memory-mapped files and caches data aggressively for performance. You can limit memory usage by configuring the WiredTiger storage engine cache size in the mongod.conf file. Add storage.wiredTiger.engineConfig.cacheSizeGB setting to control memory usage, typically setting it to 60% of available RAM minus other system requirements.

Marshall Anthony is a professional Linux DevOps writer with a passion for technology and innovation. With over 8 years of experience in the industry, he has become a go-to expert for anyone looking to learn more about Linux.

Related Posts