MongoDB is a document database that stores data as flexible JSON-like documents, which suits applications whose data model changes often. In this tutorial you will install MongoDB 8.0 Community Edition on Ubuntu 24.04 from MongoDB's official repository, create an administrator, turn on access control, allow connections from a single application server, and schedule compressed backups with mongodump.
Prerequisites
To follow this guide you need:
- A server running Ubuntu 24.04 LTS (x86_64 or arm64), for example a CubePath VPS, with at least 2 GB of RAM.
- A non-root user with
sudoprivileges. - UFW enabled with SSH allowed, if you plan to accept remote connections.
- The IP address of the application server that will connect, referred to as
your_app_server_ip, if you need remote access.
NoteUbuntu's own repositories do not include a current MongoDB server package. Install it from
repo.mongodb.orgas shown below, and do not mix it with anymongodbpackage from other sources.
Step 1 - Adding the MongoDB repository
Install the tools needed to download and convert the repository signing key:
sudo apt update
sudo apt install gnupg curl
Download MongoDB's 8.0 key and store it in /etc/apt/keyrings:
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg --dearmor -o /etc/apt/keyrings/mongodb-server-8.0.gpg
Add the repository for Ubuntu 24.04 (noble), restricted to that key:
echo "deb [ arch=amd64,arm64 signed-by=/etc/apt/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
Step 2 - Installing MongoDB
Refresh the package index and install the mongodb-org metapackage. It pulls in the server (mongod), the shell (mongosh) and the database tools (mongodump, mongorestore):
sudo apt update
sudo apt install mongodb-org
The package does not start the service. Enable it at boot and start it now:
sudo systemctl enable --now mongod
Check that it is running:
sudo systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-09-25 10:04:12 UTC; 5s ago
Confirm the server answers:
mongosh --quiet --eval 'db.runCommand({ ping: 1 })'
{ ok: 1 }
The main locations are:
| Path | Purpose |
|---|---|
/etc/mongod.conf | Server configuration (YAML) |
/var/lib/mongodb | Data files |
/var/log/mongodb/mongod.log | Server log (JSON lines) |
Step 3 - Creating an administrator and enabling authentication
A fresh MongoDB installation accepts connections without a password from anyone who can reach it. Before exposing it, create an administrative user while access control is still off, then turn it on.
Open the shell:
mongosh
Switch to the admin database and create the user. passwordPrompt() asks for the password interactively so it is not stored in your shell history:
use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(),
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
{ ok: 1 }
Type exit to leave the shell. Now enable access control in the configuration file:
sudo nano /etc/mongod.conf
Find the commented #security: line and replace it with:
security:
authorization: enabled
YAML is sensitive to indentation: use two spaces, never tabs. Restart the service:
sudo systemctl restart mongod
Verify that unauthenticated clients can no longer read data:
mongosh --quiet --eval 'db.getMongo().getDBNames()'
MongoServerError[Unauthorized]: Command listDatabases requires authentication
Connect as the administrator; you will be asked for the password:
mongosh -u admin --authenticationDatabase admin
Step 4 - Creating an application user
Applications should use a user limited to their own database. While connected as admin, switch to the application database and create the user there:
use appdb
db.createUser({
user: "appuser",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "appdb" } ]
})
The database is created when the first document is written. Test the new user by inserting and reading a document:
mongosh "mongodb://[email protected]:27017/appdb?authSource=appdb" --eval 'db.test.insertOne({ hello: "world" }); db.test.findOne()'
{ _id: ObjectId('66f3...'), hello: 'world' }
Step 5 - Allowing remote connections
Skip this step if the application runs on the same server. By default mongod listens only on 127.0.0.1. Open the configuration file:
sudo nano /etc/mongod.conf
Add your server's private address to bindIp in the net section:
net:
port: 27017
bindIp: 127.0.0.1,your_server_private_ip
Use the address the application server reaches, ideally on a private network. Restart MongoDB and check the listening sockets:
sudo systemctl restart mongod
sudo ss -tlnp | grep 27017
LISTEN 0 4096 10.0.0.5:27017 0.0.0.0:* users:(("mongod",pid=5230,fd=15))
LISTEN 0 4096 127.0.0.1:27017 0.0.0.0:* users:(("mongod",pid=5230,fd=14))
Allow port 27017 only from the application server:
sudo ufw allow from your_app_server_ip to any port 27017 proto tcp
From the application server, test the connection:
mongosh "mongodb://appuser@your_server_private_ip:27017/appdb?authSource=appdb" --eval 'db.runCommand({ ping: 1 })'
WarningTraffic between client and server is unencrypted unless you configure TLS (
net.tls.mode: requireTLSwithnet.tls.certificateKeyFilepointing to a combined certificate and key PEM file). Keep MongoDB on a private network, or set up TLS before connecting over the public internet.
Step 6 - Automating backups with mongodump
mongodump exports databases to BSON. It works well for small and medium databases; for large data sets, filesystem snapshots or a replica set member dedicated to backups are more practical.
Create a user with the built-in backup role. Connect as admin with mongosh -u admin --authenticationDatabase admin and run:
use admin
db.createUser({
user: "backup",
pwd: passwordPrompt(),
roles: [ { role: "backup", db: "admin" } ]
})
Store the password in a configuration file that only root can read, so it does not appear in the process list:
sudo install -d -m 700 /etc/mongodb-backup
sudo nano /etc/mongodb-backup/mongodump.yaml
password: your_backup_password
sudo chmod 600 /etc/mongodb-backup/mongodump.yaml
Create the backup script:
sudo nano /usr/local/bin/mongo-backup
#!/usr/bin/env bash
set -euo pipefail
backup_dir="/var/backups/mongodb"
retention_days=7
stamp="$(date +%Y%m%d-%H%M%S)"
install -d -m 700 "$backup_dir"
mongodump \
--config=/etc/mongodb-backup/mongodump.yaml \
--uri="mongodb://[email protected]:27017/?authSource=admin" \
--archive="${backup_dir}/mongodb-${stamp}.archive.gz" \
--gzip
find "$backup_dir" -type f -name '*.archive.gz' -mtime +"$retention_days" -delete
Make it executable and run it once:
sudo chmod 755 /usr/local/bin/mongo-backup
sudo /usr/local/bin/mongo-backup
sudo ls -lh /var/backups/mongodb
-rw-r--r-- 1 root root 4.2K Sep 25 10:31 mongodb-20260925-103110.archive.gz
Schedule it with a systemd service and timer:
sudo nano /etc/systemd/system/mongo-backup.service
[Unit]
Description=Dump MongoDB databases
After=mongod.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/mongo-backup
sudo nano /etc/systemd/system/mongo-backup.timer
[Unit]
Description=Daily MongoDB backup
[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mongo-backup.timer
systemctl list-timers mongo-backup.timer
Restoring a backup
Restoring needs the built-in restore role. Grant it to the admin user from a mongosh -u admin --authenticationDatabase admin session:
use admin
db.grantRolesToUser("admin", [ { role: "restore", db: "admin" } ])
Then restore the archive into the running server:
mongorestore --uri="mongodb://[email protected]:27017/?authSource=admin" --archive=/var/backups/mongodb/mongodb-20260925-103110.archive.gz --gzip --drop
--drop replaces existing collections with the ones in the backup, so test restores on a separate server first.
Troubleshooting
mongod fails to start after editing the configuration: usually a YAML indentation error. Check the reason with sudo journalctl -u mongod -n 30 and the end of /var/log/mongodb/mongod.log.
MongoServerError: Authentication failed: the user was created in a different database than the one in authSource. Users created under use admin need authSource=admin; appuser was created in appdb.
MongoNetworkError: connect ECONNREFUSED from the application server: bindIp does not include the address you are connecting to, or UFW blocks the source. Check ss -tlnp and sudo ufw status.
Startup warnings in mongosh: MongoDB prints recommendations about kernel settings and resource limits when you connect. Read them once after installation and follow the linked production notes for your version.
Conclusion
MongoDB 8.0 is now installed from the official repository on Ubuntu 24.04, with access control enabled, a least-privilege application user, remote access limited to one host and nightly compressed backups. As next steps, configure TLS for any connection that leaves a private network, create indexes for your most frequent queries (check them with explain()), and consider a three-member replica set for automatic failover.
