--- title: "How to Install and Secure MongoDB 8.0 on Ubuntu 24.04" description: "Install MongoDB 8.0 Community on Ubuntu 24.04 from the official repository, enable authentication, restrict remote access and automate mongodump backups." category: "Database Management" language: en source: https://cubepath.com/docs/database-management/mongodb-installation-and-configuration updated: 2026-09-25 --- # How to Install and Secure MongoDB 8.0 on Ubuntu 24.04 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 `sudo` privileges. - 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. > Note: Ubuntu's own repositories do not include a current MongoDB server package. Install it from `repo.mongodb.org` as shown below, and do not mix it with any `mongodb` package from other sources. ## Step 1 - Adding the MongoDB repository Install the tools needed to download and convert the repository signing key: ```bash sudo apt update sudo apt install gnupg curl ``` Download MongoDB's 8.0 key and store it in `/etc/apt/keyrings`: ```bash 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: ```bash 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`): ```bash sudo apt update sudo apt install mongodb-org ``` The package does not start the service. Enable it at boot and start it now: ```bash sudo systemctl enable --now mongod ``` Check that it is running: ```bash sudo systemctl status mongod ``` ```output ● 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: ```bash mongosh --quiet --eval 'db.runCommand({ ping: 1 })' ``` ```output { 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: ```bash 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: ```javascript use admin db.createUser({ user: "admin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" } ] }) ``` ```output { ok: 1 } ``` Type `exit` to leave the shell. Now enable access control in the configuration file: ```bash sudo nano /etc/mongod.conf ``` Find the commented `#security:` line and replace it with: ```yaml security: authorization: enabled ``` YAML is sensitive to indentation: use two spaces, never tabs. Restart the service: ```bash sudo systemctl restart mongod ``` Verify that unauthenticated clients can no longer read data: ```bash mongosh --quiet --eval 'db.getMongo().getDBNames()' ``` ```output MongoServerError[Unauthorized]: Command listDatabases requires authentication ``` Connect as the administrator; you will be asked for the password: ```bash 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: ```javascript 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: ```bash mongosh "mongodb://appuser@127.0.0.1:27017/appdb?authSource=appdb" --eval 'db.test.insertOne({ hello: "world" }); db.test.findOne()' ``` ```output { _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: ```bash sudo nano /etc/mongod.conf ``` Add your server's private address to `bindIp` in the `net` section: ```yaml 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: ```bash sudo systemctl restart mongod sudo ss -tlnp | grep 27017 ``` ```output 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: ```bash sudo ufw allow from your_app_server_ip to any port 27017 proto tcp ``` From the application server, test the connection: ```bash mongosh "mongodb://appuser@your_server_private_ip:27017/appdb?authSource=appdb" --eval 'db.runCommand({ ping: 1 })' ``` > Warning: Traffic between client and server is unencrypted unless you configure TLS (`net.tls.mode: requireTLS` with `net.tls.certificateKeyFile` pointing 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: ```javascript 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: ```bash sudo install -d -m 700 /etc/mongodb-backup sudo nano /etc/mongodb-backup/mongodump.yaml ``` ```yaml password: your_backup_password ``` ```bash sudo chmod 600 /etc/mongodb-backup/mongodump.yaml ``` Create the backup script: ```bash sudo nano /usr/local/bin/mongo-backup ``` ```bash #!/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://backup@127.0.0.1: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: ```bash sudo chmod 755 /usr/local/bin/mongo-backup sudo /usr/local/bin/mongo-backup sudo ls -lh /var/backups/mongodb ``` ```output -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: ```bash sudo nano /etc/systemd/system/mongo-backup.service ``` ```ini [Unit] Description=Dump MongoDB databases After=mongod.service [Service] Type=oneshot ExecStart=/usr/local/bin/mongo-backup ``` ```bash sudo nano /etc/systemd/system/mongo-backup.timer ``` ```ini [Unit] Description=Daily MongoDB backup [Timer] OnCalendar=*-*-* 03:30:00 Persistent=true [Install] WantedBy=timers.target ``` ```bash 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: ```javascript use admin db.grantRolesToUser("admin", [ { role: "restore", db: "admin" } ]) ``` Then restore the archive into the running server: ```bash mongorestore --uri="mongodb://admin@127.0.0.1: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.