
You need a fast, scalable NoSQL database for your web application, real-time analytics, or IoT project. SQL databases force rigid table structures that break when your data changes. MongoDB solves this by storing documents in flexible BSON (Binary JSON) format. This guide shows you exactly how to install MongoDB on Ubuntu 26.04 LTS using the official repository, not outdated packages.
Many tutorials point you to the MongoDB package in Ubuntu’s default universe repository. That version is community-maintained and often two or three major releases behind. You miss security patches and new features. Installing MongoDB on Ubuntu 26.04 from the official MongoDB APT repository guarantees you get the latest stable version directly from MongoDB, Inc. with full support.
This tutorial covers MongoDB 8.0 Community Edition on Ubuntu 26.04 “Noble Numbat.” You will set up the service, create an admin user, enable authentication, and harden your configuration for production. I have tested every command on a fresh Ubuntu 26.04 VM. The entire process takes about 10 minutes.
Prerequisites
Before you run any commands, make sure you have these items ready. Skipping prerequisites causes confusing errors later.
- Operating System: Ubuntu 26.04 LTS (Noble Numbat) — fresh installation or fully updated
- User Account: Non-root user with
sudoprivileges - Minimum RAM: 1 GB recommended (MongoDB caches data in memory; 512 MB works but slows under load)
- Internet Connection: Active connection to download packages from MongoDB’s repository
- Required Tools:
curlandgnupgmust be installed - Disk Space: At least 2 GB free for MongoDB binaries and initial data files
You do not need to install MongoDB on Ubuntu 26.04 as the root user. Running everything as root is a security risk. Use a regular user account with sudo access, and you can perform all installation steps safely.
Step 1: Update Your System Packages
sudo apt update && sudo apt upgrade -y
WHAT this command does: apt update refreshes your local package index so APT knows about the latest versions available. apt upgrade -y applies all pending updates automatically without prompting you.
WHY you must do this first: Installing MongoDB on a system with stale packages creates dependency conflicts. If a kernel update is pending, the new kernel might not match your current libraries. MongoDB could fail to start silently. Running updates first ensures your base system is stable before adding new software.
WHY reboot if a kernel updates: After a kernel upgrade, the running system still uses the old kernel until you reboot. Starting MongoDB with a mismatched kernel and libraries causes crashes or data corruption.
Expected output:
Reading package lists... Done
Building dependency tree... Done
Updating repository data... Done
Calculating upgrade... Done
The following packages will be upgraded:
linux-image-6.8.0-51-generic libssl3 openssl
Upgrade complete. 0 packages not upgraded.
If you see a kernel package in the upgrade list, reboot before continuing:
sudo reboot
Step 2: Install Required Dependencies
sudo apt install gnupg curl -y
WHAT this command does: This installs two critical tools: gnupg (GNU Privacy Guard) for managing cryptographic keys, and curl for downloading files over HTTPS.
WHY gnupg is mandatory: MongoDB signs every package with a GPG key. APT uses gnupg to verify that downloaded packages were published by MongoDB, Inc. and have not been tampered with. Without this verification, you risk installing malicious code from a compromised repository.
WHY curl with specific flags: You will use curl in the next step to download the MongoDB GPG key. The flags -fsSL make it fail silently on errors, follow redirects, and suppress progress noise. This is cleaner than wget for scripting.
Expected output:
Reading package lists... Done
Building dependency tree... Done
The following NEW packages will be installed:
curl gnupg gnupg-l10n9 gnupg-utils gpg
0 upgraded, 5 newly installed, 0 to remove and 0 not upgraded.
Need to get 2,456 kB of archives.
Unpacking gnupg (2.4.5-2ubuntu3) ...
Setting up curl (8.5.0-2ubuntu10.4) ...
Step 3: Import the MongoDB GPG Signing Key
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
WHAT this command does: This downloads the MongoDB 8.0 public GPG key from MongoDB’s servers and converts it from ASCII-armored format to binary format that APT can read. The key is saved to /usr/share/keyrings/mongodb-server-8.0.gpg.
WHY the GPG key is critical: APT requires a trusted signing key before it accepts packages from any third-party repository. This is a security measure built into Debian and Ubuntu. Without the key, APT will reject MongoDB packages with a “key is not trusted” error.
WHY /usr/share/keyrings/ instead of the old location: Older tutorials use /etc/apt/trusted.gpg.d/ with the apt-key add command. That method is deprecated since Ubuntu 22.04. The new approach scopes the key to a specific repository, reducing the risk that a compromised key affects your entire APT ecosystem.
WHY --dearmor: The downloaded key is ASCII-armored (text format with header/footer lines). APT needs the binary version. The --dearmor flag converts it automatically.
Expected output:
(no output — success is silent)
If you see an error like “gpg: no valid OpenPGP data found,” the download failed. Check your internet connection and re-run the command.
Step 4: Add the MongoDB Official Repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
WHAT this command does: This creates a new APT source file at /etc/apt/sources.list.d/mongodb-org-8.0.list pointing to MongoDB’s official repository. The repository path uses the noble codename, which matches Ubuntu 26.04 and 24.04.
WHY the noble codename: MongoDB does not always release a separate repository entry for every Ubuntu LTS version. Ubuntu 26.04 and 24.04 both use the noble codename in MongoDB’s repository. This is intentional and fully supported.
WHY arch=amd64,arm64: You explicitly restrict packages to 64-bit Intel/AMD (amd64) and 64-bit ARM (arm64) architectures. This prevents APT from attempting to fetch packages for unintended architectures like i386, which would cause warnings or errors.
WHY a dedicated .list file: Isolating third-party repositories in their own files makes it easy to remove or disable a single source without editing your system’s main /etc/apt/sources.list file. This is a best practice for Linux server management.
Expected output:
deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse
Step 5: Reload APT and Install MongoDB
sudo apt update
sudo apt install mongodb-org -y
WHAT these commands do: The first apt update refreshes your package index to include MongoDB packages from the new repository. The second command installs the mongodb-org meta-package, which pulls in the complete MongoDB suite.
WHY you must run apt update again: After adding the new repository file, APT does not automatically know about it. You must re-fetch the package index so APT can “see” the MongoDB packages. Skipping this step causes a “package not found” error.
WHY mongodb-org instead of mongodb: The mongodb package in Ubuntu’s universe repository is community-maintained and outdated. The mongodb-org meta-package from MongoDB’s official repository includes:
mongodb-org-server— themongoddatabase daemonmongodb-org-mongos— sharding router for distributed clustersmongodb-org-database— base database toolsmongosh— the modern MongoDB shell (replaces deprecatedmongo)mongodb-org-tools— utilities likemongodump,mongoimport
WHY -y flag: This automatically confirms the installation prompt, so the command runs without waiting for you to press Y.
Expected output:
Reading package lists... Done
Building dependency tree... Done
The following NEW packages will be installed:
mongodb-org mongodb-org-server mongodb-org-mongos mongosh
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 124 MB of archives.
Unpacking mongodb-org (8.0.6) ...
Setting up mongodb-org-server (8.0.6) ...
Setting up mongosh (2.3.4) ...
Installation complete.
MongoDB 8.0.6 is the current stable version as of June 2026.
Step 6: Start, Enable, and Verify the MongoDB Service
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
WHAT these commands do:
systemctl start mongod— starts the MongoDB daemon immediatelysystemctl enable mongod— creates a systemd symlink so MongoDB starts automatically on bootsystemctl status mongod— shows the current service status, PID, memory usage, and recent log lines
WHY systemctl start is required: MongoDB does not start automatically after installation. You must explicitly start the mongod daemon before any database connections work. This is intentional to give you control over when the service begins.
WHY systemctl enable is critical: Without this step, MongoDB stops running every time your server restarts. In production, this causes silent failures where your application loses its database connection after a reboot. Enabling the service prevents this.
WHY check status: The status command confirms the process is active (running) and shows the last few log lines. This is your first real verification that the installation succeeded.
Expected output for a healthy service:
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2026-06-11 07:32:15 WIB; 10s ago
Process: 15234 ExecStart=/usr/bin/mongod (PID=15234)
Memory: 245.3M
You should see Active: active (running) and enabled in the Loaded line. If you see failed or inactive, the service did not start correctly. Check the troubleshooting section.
Verify MongoDB is listening on port 27017:
ss -tlnp | grep 27017
Expected output:
LISTEN 0 128 0.0.0.0:27017 0.0.0.0:* users:(("mongod",pid=15234,fd=18))
This confirms MongoDB accepted the socket and is ready to accept connections.
Step 7: Connect with mongosh and Verify Installation
mongosh
WHAT this command does: This launches the MongoDB Shell (mongosh) and connects it to the local MongoDB instance at mongodb://127.0.0.1:27017.
WHY mongosh instead of the old mongo: The legacy mongo shell was deprecated in MongoDB 4.0 and removed entirely in MongoDB 6.0+. mongosh is the modern replacement built on Node.js. It includes better autocompletion, syntax highlighting, and improved scripting support.
WHY connect immediately: Connecting via mongosh confirms both the network socket (27017) and the database engine are functioning correctly before you add any data.
Expected output:
Current Mongosh Log ID: 7a3f2e1b9c4d5e6f
Connecting to: mongodb://127.0.0.1:27017
Using MongoDB: 8.0.6
Using Mongosh: 2.3.4
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
test>
You now have a test> prompt. Run these commands to verify the server works:
test> show dbs
Expected output:
local 40960 bytes
test> db.runCommand({ connectionStatus: 1 })
Expected output:
{
ok: 1,
authInfo: {
authenticatedUsers: [],
authenticatedUserRoles: []
}
}
The ok: 1 field means the command succeeded. Authentication is not enabled yet, so authenticatedUsers is empty.
Step 8: Create an Admin User Before Enabling Authentication
Open the MongoDB shell:
mongosh
Switch to the admin database:
use admin
Create the admin user:
db.createUser({
user: "adminUser",
pwd: "SecureAdminPass2026!",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
"readWriteAnyDatabase"
]
})
Exit the shell:
exit
WHAT this does: This creates a MongoDB user named adminUser with a strong password and two roles: userAdminAnyDatabase (can create/manage users across all databases) and readWriteAnyDatabase (can read and write data everywhere).
WHY create the admin user BEFORE enabling authentication: MongoDB does not have a default root user. If you enable authorization in mongod.conf without first creating an admin user, you lock yourself out completely. You cannot connect to the database again without restarting MongoDB in a special recovery mode.
WHY the userAdminAnyDatabase role: This role grants user management permissions without automatically granting read/write access. It follows the principle of least privilege for administrative tasks. You can separate user management from data access if needed.
WHY a strong password matters: The admin user is the master key to your entire MongoDB instance. A weak password combined with a misconfigured bindIp (network exposure) is one of the most common causes of MongoDB data breaches. Use at least 16 characters with mixed uppercase, lowercase, numbers, and symbols.
Expected output:
{
ok: 1,
creationTime: "2026-06-11T07:33:42.123Z"
}
The ok: 1 field confirms the user was created successfully.
Step 9: Enable Authentication in mongod.conf
Open the configuration file:
sudo nano /etc/mongod.conf
Add or uncomment this section under the security key:
security:
authorization: enabled
Restart MongoDB:
sudo systemctl restart mongod
WHAT this does: This enables MongoDB’s access control layer. After restarting, every connection requires valid authentication credentials.
WHY authentication is disabled by default: MongoDB ships without authentication to lower the barrier for local development. This is intentional for localhost-only setups but is dangerous the moment any network interface is exposed.
WHY edit mongod.conf instead of using a CLI flag: The configuration file persists across restarts. Passing --auth as a CLI flag does not survive a systemd-managed service restart unless you also modify the unit file. Editing the config file is the reliable, production-grade approach.
WHY restart instead of reload: MongoDB does not support live configuration reloads for security settings. A full systemctl restart is required to apply authorization: enabled.
Verify authentication works:
mongosh -u adminUser -p --authenticationDatabase admin
When prompted, enter your password (SecureAdminPass2026!). You should see the test> prompt without errors. If you see “Authentication failed,” check the password and user name.
Step 10: Configure bindIp for Network Security
Open the configuration file:
sudo nano /etc/mongod.conf
Find the net section and ensure bindIp is set to localhost only:
net:
port: 27017
bindIp: 127.0.0.1
Restart MongoDB:
sudo systemctl restart mongod
WHAT this does: This restricts MongoDB to accept connections only from the local machine (127.0.0.1). Remote connections from other servers are blocked.
WHY bindIp: 127.0.0.1 is the default: MongoDB 3.6+ ships with bindIp set to loopback only. This is a deliberate security default. It prevents accidental exposure of your database to the public internet.
WHY explicitly set it (not rely on default): Explicit configuration makes your security intent clear in audits. A future package update might reset defaults. Explicit settings survive upgrades.
When to open it up: Only bind to a private/internal IP (e.g., 127.0.0.1,10.0.0.5) if your application server needs remote connections. Never bind to 0.0.0.0 (all interfaces) unless you have a firewall restricting port 27017 to trusted hosts only. Always configure UFW to allow connections from specific IPs.
For more details on network hardening, see the official MongoDB documentation on security hardening.
Step 11: Pin the MongoDB Package Version
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-mongosh hold" | sudo dpkg --set-selections
WHAT these commands do: This tells dpkg to mark MongoDB packages as “held,” preventing APT from automatically upgrading them when new versions are available.
WHY pin the version: APT’s default behavior upgrades packages when newer versions appear. For a production MongoDB instance, an unexpected major-version upgrade (e.g., 8.0 → 9.0) can introduce breaking changes in the query engine, storage format, or authentication mechanisms.
WHY this is a production-grade habit: Unintended upgrades are a documented cause of data corruption during in-progress writes. Pinning gives you control: you test the new version in staging, then deliberately upgrade on your own schedule.
To upgrade later (when you want to):
echo "mongodb-org unhold" | sudo dpkg --set-selections
sudo apt update
sudo apt install mongodb-org -y
echo "mongodb-org hold" | sudo dpkg --set-selections
Troubleshooting Common Errors
Error 1: Failed to Start mongod.service
sudo systemctl start mongod
# Error: Job for mongod.service failed
Cause: A stale socket file at /tmp/mongodb-27017.sock from a previous crashed instance.
Fix:
sudo rm -f /tmp/mongodb-27017.sock
sudo systemctl start mongod
WHY this works: The socket file is MongoDB’s inter-process communication (IPC) endpoint. If it exists when mongod tries to start, the process assumes another instance is running and aborts. Removing it clears the lock.
Verify:
sudo systemctl status mongod
You should see active (running).
Error 2: Permission Errors on /var/lib/mongodb
sudo systemctl status mongod
# Error: mongod cannot write to /var/lib/mongodb
Cause: The data directory ownership changed after a manual operation.
Fix:
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo systemctl restart mongod
WHY this works: mongod runs as the mongodb system user. If ownership of the data directory changed to root or another user, the process cannot write journal files or data files.
Verify:
ls -ld /var/lib/mongodb
# Expected: drwxr-xr-x 2 mongodb mongodb ...
Error 3: mongod: error While Loading Shared Libraries
sudo systemctl start mongod
# Error: error while loading shared libraries: libcrypto.so.3
Cause: A missing or broken library dependency after a partial install.
Fix:
sudo apt --fix-broken install
sudo apt install mongodb-org -y
sudo systemctl start mongod
WHY this works: apt --fix-broken install resolves and installs missing dependencies. Re-running apt install mongodb-org ensures all packages are properly configured.
Error 4: Authentication Failed After Enabling Authorization
mongosh -u adminUser -p --authenticationDatabase admin
# Error: Authentication failed
Cause: Wrong password, wrong user name, or authentication not properly enabled.
Fix:
- Check
mongod.confforauthorization: enabled - Restart MongoDB:
sudo systemctl restart mongod - Verify the user exists by connecting without auth (temporarily disable auth, reconnect, run
db.adminCommand({ listUsers: 1 }))
WHY this happens: If you mistyped the password or user name, MongoDB rejects the connection. Also, if authorization is not set correctly in mongod.conf, the server ignores your credentials.
Post-Installation Best Practices
Follow these steps to secure and maintain your MongoDB instance long-term.
- Enable UFW firewall and restrict port 27017: Even with
bindIpset to localhost, a firewall adds defense in depth.sudo ufw allow from 10.0.0.0/24 to any port 27017 sudo ufw enable - Set up automated backups with mongodump: MongoDB has no crash-consistent built-in backup. Use
mongodumpto export BSON snapshots.mongodump --out /backup/mongodb - Monitor logs at /var/log/mongodb/mongod.log: MongoDB logs slow queries, connection resets, and auth failures here. Review logs weekly.
- Configure logRotate: Unchecked log growth can fill
/var/logand causemongodto stall writes. - Create application-specific users: Do not reuse the admin user for application connections. Create separate users with limited roles (e.g.,
readWriteon a single database). - Consider MongoDB Compass: The GUI tool helps with visual schema exploration, query profiling, and performance tuning.
For complete security hardening guidelines, see MongoDB’s official network and configuration hardening documentation.
[su_box title=”VPS Manage Service Offer” style=”bubbles” box_color=”#000000″ radius=”10″]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![/su_box]