Practical Linux, Windows Server and cloud guides for IT pros.

How to Install MongoDB on Ubuntu: Step-by-Step Guide

MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents with dynamic schemas. This schema-less approach enables agile development and horizontal scalability, making it ideal for handling large volumes of unstructured or semi-structured data.

Filed under

, ,

Published

Written by

Last updated

Mongo

MongoDB is a document database that stores records as BSON documents. BSON uses a structure similar to JSON while supporting additional data types such as dates, binary data and decimal values.

Unlike a conventional relational database, MongoDB does not require every document in a collection to contain the same fields. This flexible document model can simplify applications that work with changing or varied data structures. Applications should still use a deliberate data model, suitable indexes and schema validation where consistency matters.

This guide explains how to install MongoDB 8.0 Community Edition on Ubuntu using MongoDB’s official APT repository. You will also configure the mongod service, enable password authentication and create a separate application user.

Reviewed and updated: 1 July 2026.

MongoDB version used in this guide

MongoDB 8.3 is the current stable release as of July 2026. This guide uses MongoDB 8.0, as MongoDB recommends major releases for users who want a predictable support window and manual control over upgrades. MongoDB 8.0 is supported until 31 October 2029.

MongoDB 8.0 Community Edition supports the following 64-bit Ubuntu LTS releases:

  • Ubuntu 24.04 LTS, known as Noble
  • Ubuntu 22.04 LTS, known as Jammy
  • Ubuntu 20.04 LTS, known as Focal

MongoDB supports x86_64 and ARM64 on supported platforms.

For a new server, Ubuntu 24.04 LTS or Ubuntu 22.04 LTS will usually provide the most practical foundation.

MongoDB Atlas vs a self-managed installation

MongoDB Atlas is MongoDB’s managed cloud database service. Atlas handles much of the infrastructure management, including deployment, monitoring, backups, scaling and availability.

A self-managed MongoDB installation gives you direct control over the operating system, database configuration, storage and network access. It also makes you responsible for:

  • Operating-system and MongoDB updates
  • Backups and recovery testing
  • Monitoring and alerting
  • Authentication and network security
  • High availability
  • Capacity planning

This guide installs one standalone MongoDB server. A standalone server does not provide automatic failover or database redundancy.

MongoDB recommends replica sets as the basis for production deployments that require high availability. Sharding is a separate architecture used to distribute large datasets and high-throughput workloads across multiple servers.

Quick reference

SettingValue
MongoDB editionCommunity Edition
MongoDB release series8.0
Supported Ubuntu releases24.04, 22.04 and 20.04 LTS
Official packagemongodb-org
Service namemongod
Configuration file/etc/mongod.conf
Data directory/var/lib/mongodb
Log file/var/log/mongodb/mongod.log
Default port27017
Default listening address127.0.0.1
MongoDB shellmongosh

Prerequisites

Before you begin, you need:

  • A supported 64-bit Ubuntu system
  • A user account with sudo privileges
  • Internet access to download packages
  • Terminal or SSH access to the server

The procedure assumes that you are installing a new MongoDB deployment. Back up any existing databases and configuration files before replacing an older installation.

Step 1: Check your Ubuntu version

Display the installed Ubuntu release:

cat /etc/os-release

Look for the VERSION_CODENAME value. It should be one of the following:

noble
jammy
focal

You can print only the codename with:

. /etc/os-release
echo "$VERSION_CODENAME"

Stop here if your system returns a different codename. Do not point an unsupported Ubuntu release at a repository intended for another version.

Step 2: Check for conflicting MongoDB packages

MongoDB publishes the official mongodb-org package through its own repository. Ubuntu has also distributed packages named mongodb, mongodb-server and mongodb-server-core.

These Ubuntu packages are not maintained by MongoDB Inc. and can conflict with the official mongodb-org package.

Check whether any conflicting packages are installed:

dpkg -l | grep -E '^ii[[:space:]]+(mongodb|mongodb-server|mongodb-server-core)[[:space:]]'

No output means that the listed conflicting packages are not installed.

If the command finds an existing package, identify whether it contains an active database before removing anything:

systemctl status mongodb --no-pager

Back up any existing databases and configuration before uninstalling or migrating an existing MongoDB deployment.

Do not continue with a package removal unless you understand where the current database files are stored.

Step 3: Install the repository prerequisites

Update the local package index:

sudo apt update

Install curl and GnuPG:

sudo apt install -y curl gnupg

There is no need to download or manually install an old libssl1.1 package. APT resolves the supported dependencies for the official MongoDB packages.

Step 4: Import the MongoDB signing key

Create the keyring directory if it does not already exist:

sudo install -m 0755 -d /usr/share/keyrings

Download and import the MongoDB 8.0 signing key:

curl -fsSL https://pgp.mongodb.com/server-8.0.asc |
  sudo gpg --dearmor --yes \
  --output /usr/share/keyrings/mongodb-server-8.0.gpg

The signing key allows APT to verify that packages downloaded from the MongoDB repository were signed by MongoDB.

You can confirm that the keyring file exists with:

ls -l /usr/share/keyrings/mongodb-server-8.0.gpg

Step 5: Add the official MongoDB repository

Load the operating-system release information:

. /etc/os-release

Validate that the detected Ubuntu codename is supported:

case "$VERSION_CODENAME" in
  noble|jammy|focal)
    echo "Supported Ubuntu release: $VERSION_CODENAME"
    ;;
  *)
    echo "Unsupported Ubuntu release: $VERSION_CODENAME"
    exit 1
    ;;
esac

Add the MongoDB 8.0 repository using the detected Ubuntu codename:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu ${VERSION_CODENAME}/mongodb-org/8.0 multiverse" |
  sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Display the resulting repository configuration:

cat /etc/apt/sources.list.d/mongodb-org-8.0.list

The repository path should contain noble, jammy or focal, depending on your Ubuntu release.

These repository and signing-key commands follow MongoDB’s official installation procedure for MongoDB 8.0 Community Edition.

Step 6: Install MongoDB Community Edition

Refresh the package index so APT can read the new repository:

sudo apt update

Install MongoDB Community Edition:

sudo apt install -y mongodb-org

The mongodb-org metapackage installs the main MongoDB components, including:

  • The mongod database server
  • The mongos sharded-cluster router
  • The mongosh MongoDB shell
  • MongoDB Database Tools such as mongodump and mongorestore
  • The default /etc/mongod.conf configuration file

Verify the installed server version:

mongod --version

Check the shell version:

mongosh --version

The server version should begin with 8.0.

Step 7: Start and enable MongoDB

Start MongoDB and configure it to start automatically when Ubuntu boots:

sudo systemctl enable --now mongod

Check the service status:

sudo systemctl status mongod --no-pager

You should see:

Active: active (running)

You can also perform direct checks:

sudo systemctl is-active mongod
sudo systemctl is-enabled mongod

The expected output is:

active
enabled

If systemd reports that mongod.service cannot be found, reload the systemd service definitions and try again:

sudo systemctl daemon-reload
sudo systemctl start mongod

MongoDB stores its default database files in /var/lib/mongodb and writes its service log to /var/log/mongodb/mongod.log.

Step 8: Test the local MongoDB connection

Open the MongoDB shell:

mongosh

The shell should connect to the local MongoDB server on port 27017.

Run a basic server-status command:

db.runCommand({ ping: 1 })

A successful response includes:

{ ok: 1 }

Check the current database:

db

Exit the shell:

exit

At this point, MongoDB is running, but authentication is not yet enabled.

MongoDB binds to 127.0.0.1 by default, so only processes running on the same server can connect. Keep this local-only configuration while creating the first administrative account.

Step 9: Create a MongoDB user administrator

Create a user administrator before enabling access control.

Open the shell:

mongosh

Switch to the admin database:

use admin

Create a user called userAdmin:

db.createUser({
  user: "userAdmin",
  pwd: passwordPrompt(),
  roles: [
    {
      role: "userAdminAnyDatabase",
      db: "admin"
    }
  ]
})

Enter a strong, unique password when prompted.

The passwordPrompt() function keeps the password out of the command, terminal output and shell history.

The userAdminAnyDatabase role allows this account to create users, grant roles and manage user access across databases. It does not grant unrestricted read and write access to all application data.

Exit the shell:

exit

Keep the password in an approved password manager or secrets-management system.

Step 10: Enable MongoDB authentication

MongoDB calls its access-control setting authorization.

Open the MongoDB configuration file:

sudo nano /etc/mongod.conf

Find the security section. If it does not exist, add the following block:

security:
  authorization: enabled

YAML uses spaces for indentation. Do not use tabs, and do not create a second security: section if one already exists.

Save the file in Nano by pressing:

Ctrl+O
Enter
Ctrl+X

Restart MongoDB:

sudo systemctl restart mongod

Confirm that the service returned to a running state:

sudo systemctl status mongod --no-pager

Check the recent service logs if MongoDB fails to start:

sudo journalctl -u mongod -n 50 --no-pager

You can also inspect the MongoDB log directly:

sudo tail -n 50 /var/log/mongodb/mongod.log

MongoDB now requires clients to authenticate before performing protected database operations.

Step 11: Authenticate as the user administrator

Connect using the administrative username:

mongosh \
  --host 127.0.0.1 \
  --port 27017 \
  --username userAdmin \
  --authenticationDatabase admin

mongosh prompts for the password and hides it as you type.

Do not place the password directly in the command. Command-line passwords may be exposed through shell history or process-monitoring tools.

After connecting, verify the authenticated session:

db.runCommand({ connectionStatus: 1 })

The response should include the authenticated userAdmin account.

Step 12: Create a separate application user

Applications should not connect using the user-administration account. Create a dedicated user with access only to the database it requires.

While still authenticated as userAdmin, switch to the application database:

use myapp

Create an application account:

db.createUser({
  user: "myappUser",
  pwd: passwordPrompt(),
  roles: [
    {
      role: "readWrite",
      db: "myapp"
    }
  ]
})

Replace myapp and myappUser with names appropriate for your application.

The readWrite role permits the account to read and modify data in the myapp database. It does not grant administrative access to other databases.

MongoDB recommends mapping each application and person to a distinct database user and granting only the privileges that the user requires.

Exit the shell:

exit

Test the application account:

mongosh \
  "mongodb://127.0.0.1:27017/myapp" \
  --username myappUser \
  --authenticationDatabase myapp

Enter the application user’s password when prompted.

Run a write test:

db.installTest.insertOne({
  status: "MongoDB installation successful",
  createdAt: new Date()
})

Read the inserted document:

db.installTest.find()

Remove the test collection when finished:

db.installTest.drop()

Optional: Configure remote MongoDB access

Skip this section when applications run on the same host as MongoDB.

MongoDB listens only on 127.0.0.1 by default. Opening port 27017 in a firewall does not provide remote access unless MongoDB is also configured to listen on a network interface.

Before enabling remote access:

  • Enable authentication
  • Use a private network wherever possible
  • Restrict firewall access to known client addresses
  • Avoid exposing MongoDB directly to the public internet
  • Configure TLS when traffic crosses an untrusted network
  • Use separate database users with limited roles

MongoDB warns administrators to secure authentication and network infrastructure before binding the service to a publicly accessible address.

Find the server’s private IP address

Run:

ip -brief address

Assume the MongoDB server has the private IP address:

10.20.30.10

Add the private address to bindIp

Open the configuration file:

sudo nano /etc/mongod.conf

Locate the net section:

net:
  port: 27017
  bindIp: 127.0.0.1

Add the server’s private IP address:

net:
  port: 27017
  bindIp: 127.0.0.1,10.20.30.10

Do not replace 127.0.0.1. Keeping it allows applications and administrators on the database server to continue using local connections.

Restart MongoDB:

sudo systemctl restart mongod

Verify the listening addresses:

sudo ss -lntp | grep 27017

Restrict access with UFW

Allow only a trusted private subnet:

sudo ufw allow from 10.20.30.0/24 to any port 27017 proto tcp

Alternatively, allow one application server:

sudo ufw allow from 10.20.30.25 to any port 27017 proto tcp

Check the firewall rules:

sudo ufw status numbered

Avoid an unrestricted rule such as:

sudo ufw allow 27017/tcp

That rule permits every reachable source address unless another firewall blocks the connection.

From an authorised remote client, connect with:

mongosh \
  "mongodb://10.20.30.10:27017/myapp" \
  --username myappUser \
  --authenticationDatabase myapp

Useful MongoDB service commands

Start MongoDB:

sudo systemctl start mongod

Stop MongoDB:

sudo systemctl stop mongod

Restart MongoDB:

sudo systemctl restart mongod

View the service status:

sudo systemctl status mongod --no-pager

Follow the systemd log:

sudo journalctl -u mongod -f

Follow the MongoDB log:

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

Disable automatic startup:

sudo systemctl disable mongod

Re-enable automatic startup:

sudo systemctl enable mongod

How to update MongoDB 8.0

The MongoDB repository remains configured after installation. Standard APT updates can therefore install newer packages in the MongoDB 8.0 release series.

Check for available MongoDB updates:

apt list --upgradable 2>/dev/null | grep mongodb

Apply available package updates:

sudo apt update
sudo apt upgrade

Review MongoDB’s release notes before upgrading a production database. Back up the database and test the update in a non-production environment first.

The mongodb-org/8.0 repository keeps the server within the MongoDB 8.0 release series. Moving to another release series requires a planned upgrade using MongoDB’s documented upgrade path.

Troubleshooting MongoDB on Ubuntu

Unable to locate package mongodb-org

Check the repository file:

cat /etc/apt/sources.list.d/mongodb-org-8.0.list

Confirm that it contains the correct Ubuntu codename and MongoDB 8.0 path.

Refresh the package index:

sudo apt update

Check whether APT can see the package:

apt-cache policy mongodb-org

Unit mongod.service not found

Reload systemd:

sudo systemctl daemon-reload

Start the service again:

sudo systemctl start mongod

MongoDB fails after editing mongod.conf

Inspect the service log:

sudo journalctl -u mongod -n 100 --no-pager

Common causes include:

  • Incorrect YAML indentation
  • Tab characters in the configuration
  • Duplicate security or net sections
  • An invalid IP address under bindIp
  • Incorrect permissions on the data or log directories

Review the configuration:

sudo cat /etc/mongod.conf

Authentication fails

Confirm that you are using the database where the account was created.

For the user administrator:

mongosh \
  --username userAdmin \
  --authenticationDatabase admin

For the application user created in myapp:

mongosh \
  "mongodb://127.0.0.1:27017/myapp" \
  --username myappUser \
  --authenticationDatabase myapp

The authentication database is part of the user’s identity. A user created in myapp is different from a user with the same name created in admin.

MongoDB works locally but not remotely

Check each layer:

  1. Confirm that bindIp includes the server’s private IP address.
  2. Restart MongoDB after changing /etc/mongod.conf.
  3. Verify the listening socket with ss -lntp.
  4. Check UFW and any cloud-provider firewall or security group.
  5. Confirm that routing exists between the client and server.
  6. Test TCP connectivity from the client.
  7. Verify the username and authentication database.

On a Linux client, test the TCP connection with:

nc -vz 10.20.30.10 27017

A successful TCP test confirms network connectivity. It does not confirm that MongoDB authentication will succeed.

Backing up MongoDB

Installing MongoDB Database Tools provides mongodump and mongorestore.

A reliable backup process should include:

  • Scheduled backups
  • Encrypted backup storage
  • Copies stored away from the database server
  • Retention rules
  • Monitoring for failed backups
  • Regular restoration tests
  • Documented recovery procedures

A backup that has never been restored in a test environment should not be treated as a verified recovery method.

Production replica sets and large databases may require a snapshot-based or managed backup design rather than relying only on mongodump.

What are the advantages of MongoDB?

Flexible document model

MongoDB stores records as BSON documents inside collections. Documents can contain nested objects, arrays and fields that vary between records.

This model can work well for application data that does not map cleanly to a fixed set of relational columns. MongoDB also supports schema validation when an application requires stronger structural controls.

Querying and indexing

MongoDB supports filters, projections, sorting, aggregation pipelines and multiple index types.

Indexes can improve query performance when they match the application’s access patterns. Poorly selected or excessive indexes can increase storage usage and write overhead, so indexes should be monitored and reviewed.

High availability through replica sets

A MongoDB replica set maintains copies of the same data across multiple mongod instances.

The replica set can elect a new primary when the existing primary becomes unavailable. This architecture provides redundancy and automatic failover when deployed across suitable failure domains.

The standalone server installed in this guide is not a replica set and does not provide this protection.

Horizontal scaling through sharding

MongoDB sharding distributes data across multiple servers.

Sharding can support databases that exceed the storage or processing capacity of one server. It introduces additional components and operational complexity, so it should be designed around a suitable shard key and a measured scaling requirement.

Storage caching and compression

MongoDB Community Edition uses the WiredTiger storage engine by default.

WiredTiger uses an internal cache alongside the operating system’s filesystem cache. It also supports compression for collection and index data. MongoDB is therefore able to keep frequently accessed data in memory while retaining durable data on disk. It should not be described as an in-memory database.

Conclusion

You have installed MongoDB 8.0 Community Edition from MongoDB’s official Ubuntu repository, enabled the mongod service and configured password authentication.

The installation now has:

  • An administrative account for managing database users
  • A separate least-privilege application account
  • Local-only network access by default
  • An optional method for controlled private-network access
  • Service and log commands for basic administration

The resulting server is a standalone MongoDB deployment. Add a tested backup process before storing important data. Production environments that require automatic failover should use a properly designed replica set rather than relying on one database server.

Leave a Reply

Your email address will not be published. Required fields are marked *

Find more on the site

Keep reading by topic.

If this post was useful, the fastest way to keep going is to pick the topic you work in most often.

Want another useful post?

Browse the latest posts, or support TurboGeek if the site saves you time regularly.

Translate »