Databases

Install MongoDB on Ubuntu 26.04 / 24.04 (Official Repo)

MongoDB installs on Ubuntu from one vendor repository, four commands end to end, and the server finishes listening on localhost with access control off. That default is safe but unusable for anything beyond a test. The shell warns you about it in plain text on every connection until you fix it. This guide walks the full path on both supported releases: repository, install, an admin user, authentication, and remote access you can defend.

Original content from computingforgeeks.com - post 101950

We ran every command in this guide on two lab VMs (tested November 2026 on Ubuntu 26.04 and 24.04 with MongoDB 9.0.4). The run covered a fresh install, an admin user, a firewall rule, a data directory move and a remote connection from a second box. Where the current series changed behaviour that older guides still teach, the relevant step says so. The commands are written version agnostic, and the repository line takes your release name from lsb_release, so the same block runs on either Ubuntu.

Prerequisites

The official repository publishes components for both current LTS series, so start from a supported release and nothing else. Our test boxes were 2 vCPU, 4 GB VMs, which is a lab floor rather than a recommendation. Here is what you need before the first command.

  • Ubuntu 24.04 or 26.04: the repository line in Step 1 resolves the codename from the installed system, and both noble and resolute carry the current server packages.
  • A sudo account: every system step writes under /etc or /var, so a plain user cannot do it.
  • Disk and memory sized for the workload: the packages take about 825 MB, and the storage engine sizes its cache from available RAM, so a 4 GB box gives the database roughly 1.4 GB of cache. A small production node wants 8 to 16 GB of RAM, two or more vCPUs, and an XFS filesystem for the data directory; the server prints a startup warning when the data directory sits on anything else.

Step 1: Add the MongoDB apt repository

Ubuntu ships no MongoDB packages, so everything comes from the vendor repository. Its metadata is signed, and apt verifies the signature against a key you import first. Import the key into a keyring file under /usr/share/keyrings rather than the global trusted store. That way the key signs only this repository:

sudo apt-get update
sudo apt-get install -y gnupg curl ca-certificates
curl -fsSL https://pgp.mongodb.com/server-9.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-9.gpg --dearmor

The command prints nothing on success, which is the confirmation. Check the keyring landed with a real size, then add the repository. The line below takes the codename from the installed system, so it writes the correct component on either release.

ls -l /usr/share/keyrings/mongodb-server-9.gpg
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-9.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/9.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-9.0.list

On the first test box the keyring landed at 2,417 bytes, and the repository line echoed back with resolute in the component path:

Importing the MongoDB signing key and adding the official apt repository on Ubuntu

Refresh the package index and watch for the new repository in the output. A healthy run shows the mongodb-org/9.0 index downloading for both architectures. An error line naming your codename means the repository line has a typo or the release is not one the repository supports:

sudo apt-get update

Here is the run from the test box: the Ubuntu mirrors and the security pocket download first, and the two mongodb-org/9.0 lines are the new repository metadata arriving:

apt-get update picking up the MongoDB 9.0 repository on Ubuntu 26.04

Keep the repository file if you later pin a different series. The component path carries the series name, so moving to a newer series is one line edit plus a key import, not a reinstall. The same file is what apt upgrade uses to pull point releases automatically, which is why deleting it after the install is a common way to stall security updates.

Step 2: Install and start the server

One metapackage pulls in the server, the shell, the tools and the services. The install is about 240 MB of downloads and 825 MB on disk, and it does not start the service by itself.

sudo apt-get install -y mongodb-org

The package list is worth reading once. Eight component packages plus the metapackage land on disk, and the disk figure tells you what the data directory will grow from.

Installing the mongodb-org metapackage with apt on Ubuntu 24.04

Check what apt installed before starting anything. The version in the policy line is the one your applications will connect to. On our second test box the current server package was the only candidate, installed and candidate agreeing at one version:

apt-cache policy mongodb-org-server | head -3

Enable and start the service, then read the status instead of trusting the exit code. A healthy service shows active (running), the unit file under /usr/lib/systemd, and idle memory around 80 MB; the cache grows later, on first use:

sudo systemctl enable --now mongod
systemctl status mongod --no-pager

The status below comes from the first test box minutes after the install, with the unit enabled and the process holding one config file argument.

systemctl status showing the mongod service active and enabled

Confirm the binary reports its own build, and note the distmod line: it names the Ubuntu release the package was built for, which is how you catch an install that pulled packages for the wrong series:

mongod --version

The build block below is from the first test box, and the distmod value in it matches the release name the repository line wrote in Step 1. If yours names a different release, the install pulled packages for the wrong series:

mongod --version output showing MongoDB 9.0.4 on Ubuntu 26.04

Neither of our test boxes needed a reboot after the install; /var/run/reboot-required was absent on both. The install lays down a small set of files that every later step touches. It is worth knowing where each one lives before you edit anything:

WhatPath or value
Server config/etc/mongod.conf
Data directory/var/lib/mongodb
Log file/var/log/mongodb/mongod.log
Service unitmongod.service, starts mongod --config /etc/mongod.conf
Default port27017, bound to 127.0.0.1
Shellmongosh, installed with the server

The config file is YAML with strict two space indentation, which is why every edit in this guide is a targeted sed replacement rather than a rewrite. One wrong indent level and the service refuses the file at the next restart, with the offending line named in the journal. Both path entries move cleanly if you need them to, which Step 5 covers.

Step 3: Create the admin user and enable authentication

A fresh install accepts every connection without a password. Open a shell session and confirm the baseline. You should see three system databases, and the startup warnings that say access control is not enabled. Those warnings disappear only when you finish this step.

mongosh
show dbs

The full first session, captured on the second test box, shows the warnings block, the three system databases and a first document written to a test database.

First mongosh session on Ubuntu with the startup warnings, show dbs and an insert

Create the admin user while authentication is still off, because only a localhost connection can do it after the switch. The user lives in the admin database and holds two roles: one to manage users, one to read and write data. passwordPrompt() keeps the password out of the shell history:

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

Our run below shows the command with the prompt line and the masked password entry. The password never touches the command line this way, so it stays out of the shell history and out of any process listing.

Creating the cfgadmin user with passwordPrompt in mongosh

The server answers with { ok: 1 }. Leave the shell with exit, because the next block runs in the system shell, not in mongosh. Switch authentication on by editing /etc/mongod.conf and restarting the service. The security block is commented out in the stock file, and the two lines below replace it in place:

sudo sed -i 's/^#security:/security:\n  authorization: enabled/' /etc/mongod.conf
sudo systemctl restart mongod && sleep 3 && systemctl is-active mongod

Verify the switch from both sides, because each side fails differently. An anonymous session must now be refused, and the named user must connect. The refusal is the confirmation that the config change took effect, so do not skip it.

mongosh --eval "db.getUsers()"
mongosh -u cfgadmin -p --authenticationDatabase admin --eval "db.adminCommand({listDatabases:1}).databases.map(d=>d.name).join(' ')"

Both checks below come from the first test box, run back to back after the restart. First the anonymous refusal, then the named login that lists the databases.

Verifying authentication: anonymous access fails, the admin user connects

Our run of the second command answered with the three system databases, which confirms the named login works end to end. Keep the two roles separate in your head. A user with only the administration role can create accounts but cannot read a collection, which is the failure mode behind half the authentication questions we see in comments. Our guide to configuring MongoDB authentication goes deeper on roles and per-database users.

Step 4: Open remote access safely

By default the server binds to 127.0.0.1, so it ignores every network interface. Point bindIp at all interfaces, restart, and confirm the listener moved before you open any firewall port. The ss line is the one that tells you the truth:

sudo sed -i 's/  bindIp: 127.0.0.1/  bindIp: 0.0.0.0/' /etc/mongod.conf
sudo systemctl restart mongod && sleep 3 && systemctl is-active mongod
ss -tln | grep 27017
sudo ufw allow 27017/tcp

On the test box the listener moved to 0.0.0.0:27017 after the restart, and ufw wrote its rules. The firewall itself was inactive on that VM, which the status line after the command shows:

Changing bindIp to 0.0.0.0, confirming the listener and opening port 27017 in ufw

With authentication off, bindIp: 0.0.0.0 would publish an open database to every host that can reach it, so never reverse the order of this step and Step 3. Test the path from a second machine rather than from the server itself. A localhost connection succeeds even when the network path is broken, so the test only means something from outside:

mongosh mongodb://[email protected]:27017/admin --authenticationDatabase admin -p

Our second test host logged in over the wire, and the ping plus the server version came back across the network. That pair proves the whole path at once, because the credentials, the firewall port and the bind address all have to agree for the shell to answer.

Connecting to the Ubuntu MongoDB server from a second host over the network

We tested exactly this between two VMs, ran db.adminCommand({ ping: 1 }) over the wire and got { ok: 1 } from the remote host. On a cloud server the vendor firewall sits in front of ufw, so open the port there as well or the connection times out with no error on the server side. Two hardening notes before you treat this as done. The login sends the password in plaintext. Put TLS on the listener with the net.tls block of the config file, or reach the server through an SSH tunnel when the traffic leaves your network. And where the host has a private interface, name it in bindIp instead of using 0.0.0.0, because the narrower listener removes most of the exposure on its own. If the database only ever serves applications on the same host, skip this step entirely and leave the listener on localhost.

Step 5: Move the data directory

The stock data path lives under /var/lib, which on many servers shares a partition with the system root. If you provisioned a separate disk for the database, move the directory now, while the database holds nothing you cannot re-copy. The copy uses rsync, which minimized cloud images sometimes leave out, so install it first if the command comes back not found. Stop the service before copying. A copy taken while mongod runs is not consistent:

sudo systemctl stop mongod
sudo mkdir -p /srv/mongodb/data
sudo rsync -av /var/lib/mongodb/ /srv/mongodb/data/
sudo chown -R mongodb:mongodb /srv/mongodb/data
sudo mv /var/lib/mongodb /var/lib/mongodb.bak

Point dbPath in /etc/mongod.conf at the new directory, then start the service and read the status. The ownership line matters: the service runs as the mongodb user, and a data directory it cannot write fails the start with a permission error, not a path error:

sudo sed -i 's|  dbPath: /var/lib/mongodb|  dbPath: /srv/mongodb/data|' /etc/mongod.conf
sudo systemctl start mongod && sleep 3 && systemctl is-active mongod

Our move on the second test box ran end to end. The copy runs first, then the ownership change, then the config edit, and the service comes back on the new path.

Moving the MongoDB data directory with rsync and editing dbPath in mongod.conf

Our move copied 210 MB of WiredTiger files and the service came back active on the new path. Keep /var/lib/mongodb.bak until the first backup cycle completes on the new disk, then delete it; the directory is the only copy of everything the database has written so far. On the new filesystem, check the XFS startup warning is gone in the log:

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

On the test box the tail after the move showed clean connection logs and no filesystem warning, which is the confirmation the new disk is fit for the database. If the warning reappears, the directory landed on the wrong partition.

Step 6: Read the memory and queue settings

The storage engine sizes its own cache automatically at half of available RAM minus one gigabyte. On our 4 GB test box that came out at 1.4 GB, read straight from the server. You rarely need to change it. You do need to know what it is when a memory alarm fires.

mongosh -u cfgadmin -p --authenticationDatabase admin --quiet admin --eval 'print(Math.round(db.serverStatus().wiredTiger.cache["maximum bytes configured"]/1073741824*10)/10 + " GB")'

Both readings below come from the first test box, together with the memory the system reports, so the cache number can be compared with the box size.

Reading the WiredTiger cache ceiling and the 9.0 queue ticket settings

Older guides also teach a fixed ticket count for the storage engine, set through a setParameter named wiredTigerConcurrentReadTransactions. MongoDB renamed those ticket parameters in the 6.0 series and made them dynamic in 7.0. The server tunes admission itself now, instead of asking you for a fixed number. The numbers worth watching live under db.serverStatus().queues.execution, which reports an execution queue with throughput probing and a starting ticket count per priority that the server adjusts while it runs. Our server started with four read tickets in the normal priority, as the figure above shows.

One permission note our own test run hit: the admin user from Step 3 cannot read serverStatus, because the administration role does not carry it. The clean answer is a separate monitoring user that holds clusterMonitor and nothing else. On a single-admin lab server like ours, granting the role to the admin account keeps the setup simple, and that is what the block below does:

use admin
db.grantRolesToUser("cfgadmin", ["clusterMonitor"])

After the grant the same command that failed for us above returned the cache figure and the queue numbers, with no restart needed. Roles apply on the next authentication, so reconnect before expecting the new access.

Troubleshooting

MongoServerError: Command usersInfo requires authentication

You switched authentication on and connected without credentials, or you are connecting as a user that exists but in the wrong database. Every user belongs to the database where it was created, so pass --authenticationDatabase admin explicitly and retry. If the error persists, list your users from a localhost session before assuming the password is wrong, because a typo in a one-off createUser is easier than it sounds.

The service fails to start after moving the data directory

Read the journal before touching the config again: journalctl -u mongod -n 20. The two causes in practice are ownership, fixed with chown -R mongodb:mongodb on the new path, and a dbPath line that does not match the directory you actually created. We keep the old directory as .bak precisely so a bad move costs one config edit to undo.

The repository has no Release file for your codename

That error during apt-get update means the repository line names a series the vendor does not publish. It usually appears because lsb_release returned an interim release name, or because the file was copied from an older guide with a hardcoded name. Check the codename with lsb_release -cs, and write the repository line exactly as Step 1 shows it rather than copying one from a post written for a previous series.

What to watch after the first week

A stable single-node install shows a flat cache near the ceiling Step 6 printed, short queue lengths under queues.execution, and a connection count that matches your application pool sizes. We check four numbers in the first week, because each one fails differently:

  • Cache occupancy: steady near the ceiling from Step 6 is healthy; continuous eviction under light load means the working set wants more RAM than the box has.
  • Queue length: a non-zero value under queues.execution during normal traffic, not just during a batch job, is the first sign of contention.
  • Startup warnings: warnings reappearing in the log after a config change mean the change broke a setting, so read the log before the dashboard.
  • Connections current: it should match your application pool sizes; a slow climb with no matching deployment usually means a client is opening connections without closing them.

These paths pair well with setting up MongoDB replication on Ubuntu, the next resilience step once a single node is proven, and with installing MongoDB Compass when you want to read the same numbers in a GUI. For the Debian side of the same install, our guide to MongoDB on Debian follows the same repository pattern. MongoDB on Linux Mint covers the desktop variant.

Keep reading

Upgrade Ubuntu 24.04 to Ubuntu 26.04 LTS (Step by Step) Ubuntu Upgrade Ubuntu 24.04 to Ubuntu 26.04 LTS (Step by Step) UFW Firewall Commands with Examples on Ubuntu 26.04 / 24.04 Security UFW Firewall Commands with Examples on Ubuntu 26.04 / 24.04 Backup and Restore Linux Systems with Timeshift Debian Backup and Restore Linux Systems with Timeshift Deploy Collabora Online Office on Ubuntu with Let’s Encrypt SSL Cloud Deploy Collabora Online Office on Ubuntu with Let’s Encrypt SSL Install CyberPanel on Ubuntu 26.04 / 24.04 with Let’s Encrypt Ubuntu Install CyberPanel on Ubuntu 26.04 / 24.04 with Let’s Encrypt How To Install and Use MongoDB 8.0 in Linux Mint Databases How To Install and Use MongoDB 8.0 in Linux Mint

Leave a Comment

Press ESC to close