UbuntuUbuntu Based

How To Install MongoDB on Ubuntu 24.04 LTS

Install MongoDB on Ubuntu 24.04

MongoDB is a popular NoSQL database that excels at storing and managing large volumes of unstructured data. Its document-oriented approach offers flexibility and scalability for a wide range of applications. Ubuntu 24.04, being a stable and user-friendly Linux distribution, is an excellent choice for running MongoDB in a production or development environment. In this guide, you’ll learn how to install MongoDB on Ubuntu 24.04, configure it properly, secure it, and troubleshoot common issues along the way.

Introduction

MongoDB has gained immense popularity in the software development world due to its horizontal scaling, high performance, and JSON-like data structures that align well with modern application demands. Ubuntu, meanwhile, is frequently chosen for its vast community support and continuous improvement of packages and security patches. By installing MongoDB on Ubuntu 24.04, you’ll experience a smooth setup and streamlined database management.

This tutorial provides a step-by-step approach to installing MongoDB, covering everything from initial system updates to firewall configuration. You’ll learn how to verify the installation, perform initial tests, implement security best practices, and optimize performance for high workloads. Whether you are a system administrator or an enthusiastic developer, following this guide will help you maintain a robust and efficient MongoDB environment on your Ubuntu 24.04 server.

Prerequisites

Before you begin, make sure your Ubuntu server meets the necessary requirements and that you have the appropriate permissions to install new software. Also, confirm that you have reliable network connectivity and any essential system utilities to manage packages and services.

System Requirements

Although MongoDB can run on lightweight systems, minimum requirements ensure more stable performance:

  • Ubuntu 24.04 installed and running
  • At least 2 GB of RAM
  • At least 2 CPU cores (preferably more for production systems)
  • Adequate disk space for existing and future data growth

If you are using a virtual machine or cloud instance, it’s recommended to allocate extra resources to handle future traffic spikes. Proper resource allocation helps you avoid bottlenecks and operating system slowdowns.

Updating the Ubuntu System

It’s prudent to update the package management index before installing any new software. This ensures you have the latest security patches and stable versions of required dependencies. Run the following in your terminal:

sudo apt update
sudo apt upgrade

This process updates the local package database and upgrades any outdated packages, setting the stage for a smooth MongoDB installation.

Installing Required Packages

Some installations may need additional tools commonly used for server maintenance. This can include network utilities, firewall management tools, and text editors. For instance, you could install them as follows:

sudo apt install curl nano ufw

While not strictly mandatory, these utilities simplify system administration tasks and enhance security and usability.

Pre-Installation Steps

To successfully install MongoDB on Ubuntu 24.04, you need to configure the official repository, import the MongoDB GPG key, and ensure that your environment is set up optimally. These steps confirm you’re obtaining the correct binaries and help maintain a trusted software source.

Configuring the MongoDB Repository

Ubuntu’s default repositories may not always have the most recent MongoDB version. For access to the latest features and security updates, add the official MongoDB repository.

  1. Open your sources list file:
    sudo nano /etc/apt/sources.list.d/mongodb-org-7.0.list
    
  2. Paste the following line into the file:
    deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse
    
  3. Save and close the file.

Although the repository URL references focal, MongoDB typically aligns future releases with this repository. Adjust the version numbers if or when the official MongoDB documentation updates for Ubuntu 24.04. Always consult authoritative sources for the latest repository information, ensuring full compatibility with your system.

Adding MongoDB GPG Key

Before Ubuntu trusts the new repository, it needs the GPG key. The GPG key helps authenticate packages and assures your system that the downloaded software is legitimate. Import the key using:

curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-org-7.0.gpg

If you run into any connection problems, verify that your system has a stable internet link and that you typed the key URL correctly. After adding the key successfully, your server should properly validate the MongoDB packages during the installation.

Verifying System Architecture

MongoDB supports 64-bit architectures. Confirm that your Ubuntu installation is indeed 64-bit. You can verify this by running:

uname -m

The output should be something like x86_64. If you see i386 or another 32-bit format, consider switching to a 64-bit version of Ubuntu for full MongoDB compatibility and performance.

Backing Up Existing Data

If your server has existing databases or configurations, it’s prudent to back them up before making any system changes. While adding a new repository and installing MongoDB is generally safe, backups are always a wise precaution. Use a reliable tool like rsync or tar to archive important directories.

Setting Up Firewall Rules

Securing your server before installation prevents unauthorized access. Ubuntu’s Uncomplicated Firewall (UFW) gives an easy interface for opening and closing ports. MongoDB typically listens on port 27017 by default, but you may wish to restrict external traffic to only approved IP addresses. For a basic setup, allow SSH connections and specific ports only:

sudo ufw allow ssh
sudo ufw allow 27017/tcp
sudo ufw enable

Balancing security and accessibility is key. If you plan to run MongoDB in a production environment, consider restricting the database port to internal networks or known whitelisted IP addresses.

Installation Process

After completing all preliminary steps, you can comfortably install MongoDB on Ubuntu 24.04. With the repository and GPG key in place, the system will fetch the latest MongoDB packages, ensuring your database runs on a stable and secure version.

Installing MongoDB Community Edition

Perform an update on your package list to reflect the newly added repository, then install MongoDB:

sudo apt update
sudo apt install mongodb-org

This command installs the main mongodb-org package, which includes mongod (the daemon process), mongos (the sharded database router), and the MongoDB shell tools. Alternatively, you can install components individually if you only require specific tools.

During the installation, apt may prompt you to confirm the download and installation of packages. Confirm these prompts to proceed.

Verifying Installation Success

Once the installation is finished, you can double-check by inspecting the package information:

mongod --version

This command should display the installed MongoDB version. Confirm that it matches the expected release from the official repository.

Starting the MongoDB Service

MongoDB includes a systemd service file, enabling you to manage the daemon with familiar service commands. To start the daemon, run:

sudo systemctl start mongod

It’s a good idea to monitor the status immediately afterward. If the service fails to start, the error log will hint at missing dependencies or permission conflicts.

Enabling Automatic Startup

Ensuring MongoDB starts on system boot is vital for production and development servers alike. Use:

sudo systemctl enable mongod

Now, even after a reboot, MongoDB will automatically begin running. You can confirm by checking the service status after a fresh boot if necessary.

Checking Service Status

Verifying the status of MongoDB is crucial to ensure everything is working correctly. Observe the status with:

sudo systemctl status mongod

A running state indicates the daemon is active. If for any reason it’s not running, consult the system logs in /var/log/mongodb or use journalctl -u mongod to gather more information. Potential causes of startup issues include insufficient memory, incorrect file permissions, or conflicts with other services.

Configuration Steps

With MongoDB successfully installed and running, you can tweak its configuration files to match your environment’s needs. Proper configuration ensures a secure, high-performing, and reliable database.

Basic MongoDB Configuration

The main MongoDB configuration file is located at /etc/mongod.conf. This file governs settings such as storage paths, network bindings, and logging. Here is an example snippet:

storage:
  dbPath: /var/lib/mongodb
systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
net:
  port: 27017
  bindIp: 127.0.0.1

If this is your first MongoDB environment, the defaults are typically sufficient for a test or development scenario. However, for production use, consider adjusting parameters to accommodate larger datasets and concurrency.

Security Settings

By default, MongoDB does not enforce authentication, which leaves it accessible if bound to external interfaces. For a more secure setup, enable authentication and create an administrative user. In /etc/mongod.conf, locate the security section and add:

security:
  authorization: enabled

Restart the MongoDB service to apply the changes:

sudo systemctl restart mongod

You can then enter the MongoDB shell to create an admin user. This step is expanded in the Security Best Practices section, ensuring your data stays protected.

Network Configuration

Binding MongoDB to 127.0.0.1 permits only local connections. If your application resides on the same server, this setup is fine. If you have distributed architecture, you might modify bindIp to include server IP addresses. Always weigh the trade-off between convenience and security when exposing ports to external networks.

Performance Optimization

Many MongoDB performance enhancements revolve around hardware resource allocation and careful configuration. Items to consider include:

  • Adjusting the storage.wiredTiger.engineConfig.cacheSizeGB parameter for your available RAM
  • Using RAID or SSDs for faster read/write operations
  • Tuning Linux kernel parameters for high I/O workloads

Performance improvements often require iterative testing and monitoring to find the optimal balance for CPU, memory, and storage resources.

Setting Up Authentication

After enabling authorization, create a new user with the necessary roles to administer your databases. From the MongoDB shell, run:

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

Log out and log back in using the admin credentials, and you’ll have administrative access. These measures lay the groundwork for a high level of security.

Testing the Installation

Once you complete the primary configuration, it’s time to test your MongoDB environment. Testing ensures that everything is functioning as intended and helps confirm the stability of your setup.

Connecting to the MongoDB Shell

To open the MongoDB shell, use the following command:

mongosh

If you have authentication enabled, specify the username and database:

mongosh --username adminUser --authenticationDatabase admin

Creating a Test Database

In the shell, you can switch to a new database just by using it. For example:

use testDatabase

If testDatabase doesn’t exist, MongoDB will create it once you insert data. This lazy creation makes MongoDB highly flexible and straightforward for new projects.

Basic CRUD Operations

Let’s insert a simple document into a collection, then read it back:

db.widgets.insertOne({ name: "Test Widget", price: 12.99 })
db.widgets.find()

This verifies that your writes and reads are functioning normally. Updating or deleting documents follows a similar syntax, ensuring you have full control over your collections.

Running Diagnostic Tests

MongoDB includes diagnostic commands like db.serverStatus() to review server metrics, memory usage, and other performance indicators. Checking these periodically helps you catch potential issues before they escalate.

Verifying Connectivity

If you have external services or microservices, test their ability to connect to MongoDB. Confirm the correct port is open and that credentials align with your newly created user roles. This step is especially crucial in production environments, ensuring data flows seamlessly between components.

Common Issues and Troubleshooting

Even with thorough preparation, you might encounter unexpected issues. Knowing how to address them quickly minimizes downtime.

Permission Errors

Insufficient privileges can lead to errors when installing or configuring MongoDB. Always run package installations with sudo rights, and ensure the mongodb user has read/write permission for database directories. Verify file ownership with:

ls -l /var/lib/mongodb

Connection Issues

If remote connections fail, double-check firewall rules and network bindings. A quick test is to use telnet server_ip 27017 from another machine to see if the port is accessible. Alternatively, try binding MongoDB to 0.0.0.0 temporarily to eliminate IP binding as a cause, then refine the security policy afterward.

Service Startup Problems

A crashed or unresponsive MongoDB service sometimes indicates configuration file errors. Inspect /var/log/mongodb/mongod.log or use systemctl status mongod for diagnostic messages. Review the mongod.conf file to confirm correct indentation and valid YAML syntax.

Package Conflicts

Occasionally, older MongoDB packages or third-party repositories can clash with the official repository. Remove any conflicting packages, then refresh the apt cache to ensure the correct source is used:

sudo apt remove mongodb
sudo apt update

Installing afresh from MongoDB’s official repository typically resolves these conflicts.

Log File Analysis

Locate logs in /var/log/mongodb for meaningful details when debugging. Critical warnings or errors often appear in these logs, so scanning them regularly can help you detect minor issues early. Tools like grep and tail -f prove invaluable during log monitoring.

Security Best Practices

Protecting your data is paramount, especially if your database is exposed to the internet or handles sensitive information. By implementing robust security measures, you reduce the risk of unauthorized access or data loss.

User Authentication Setup

Enabling authorization and creating strong passwords for user accounts is the first layer of defense. Encourage unique, complex credentials that combine alphanumeric and special characters. Change default settings whenever possible to reduce common attack vectors.

Access Control Configuration

MongoDB supports role-based access. Assign roles that grant only the privileges necessary for each user. For instance, a read-only user can access data without having permission to write or delete documents. This principle of least privilege limits the impact of any single account breach.

Network Security

Configuring your server’s firewall to restrict external traffic is crucial. Only open MongoDB’s default port to specific IPs. For multi-node clusters, consider using an internal private network. Use SSH tunnels or VPN connections to further secure traffic. Maintaining a dedicated VLAN for database traffic is also common in production deployments.

SSL/TLS Implementation

SSL/TLS encryption is vital if your database is accessed over untrusted networks. Generate a Certificate Authority (CA) or obtain certificates from a trusted CA, then configure them in mongod.conf:

net:
  ssl:
    mode: requireSSL
    PEMKeyFile: /etc/ssl/mongodb.pem

Restart MongoDB for changes to take effect. Encrypted traffic helps safeguard credentials and data from interception or tampering.

Security Checklist

  • Always enable authorization
  • Regularly rotate passwords
  • Keep MongoDB and the operating system updated
  • Restrict MongoDB to listen on local or private networks when possible

Performance Optimization

Optimizing MongoDB’s performance is an ongoing process. Fine-tuning configurations and hardware resources can dramatically improve database responsiveness under heavy loads.

Memory Configuration

MongoDB’s WiredTiger storage engine caches frequently accessed data in RAM. Ensure you allow sufficient memory for WiredTiger to operate efficiently, especially under workloads with extensive reads and writes. Monitor memory usage with db.serverStatus() or external tools to gauge usage patterns.

Storage Engine Settings

WiredTiger is the default storage engine, offering comprehensive capabilities and compression. For specialized workloads, you might evaluate the in-memory storage engine (for extremely high performance with ephemeral data). However, the default engine is well-suited for most production use cases.

Index Optimization

Indexes accelerate queries by allowing MongoDB to find data quickly without scanning entire collections. Add relevant indexes for frequently queried fields, but keep in mind that excessive indexing consumes additional memory and slows writes. Use db.collection.createIndex() and validate the results with db.collection.getIndexes().

Resource Allocation

Operating large databases may demand dedicated servers with fast SSD storage, ample memory, and powerful CPUs. Identifying resource bottlenecks typically involves monitoring solutions like the MongoDB Database Profiler or open-source tools such as htop or iostat. Regularly analyze system loads for balanced resource usage.

Monitoring Setup

Continuous monitoring prevents unpleasant surprises. Solutions range from the official MongoDB Cloud Manager or Ops Manager to open-source alternatives like Grafana and Prometheus. Track essential metrics such as CPU usage, RAM consumption, cache eviction, and disk I/O to maintain consistent performance.

Congratulations! You have successfully installed MongoDB. Thanks for using this tutorial for installing MongoDB database on Ubuntu 24.04 LTS 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