Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code: Skills Get Started
FAQ’s Sections
Administration Linux Virtual Servers

How to Install and Configure MongoDB on a VPS (Complete 2024 Guide)

MongoDB is one of the most widely adopted NoSQL databases in the world — and for good reason. Its flexible document model, high-throughput read/write performance, and native horizontal scalability make it the go-to backend for modern APIs, SaaS platforms, CRMs, e-commerce engines, and data-intensive applications. Unlike managed cloud database services, running MongoDB on your own VPS Hosting gives you complete control over performance tuning, security hardening, and long-term costs.

This guide walks you through a production-grade MongoDB Community Edition 8.0 installation on a Linux VPS — covering official repository setup for Debian 12 and Ubuntu LTS, service management, user and database creation, security hardening (authentication, network binding, firewall rules), backup strategies, and common troubleshooting steps. Whether you're launching your first application or migrating an existing workload, this guide gets MongoDB running reliably from day one.

1. Prerequisites

Before you begin, make sure the following conditions are met:

RequirementDetails
VPS accessRoot or sudo-level SSH access
Operating system64-bit Debian 12 (Bookworm) or Ubuntu 22.04/24.04 LTS
RAMMinimum 1 GB; 2 GB+ recommended for production
StorageSSD-backed storage strongly recommended
FirewallUFW or iptables available

> Important: MongoDB 8.0 officially supports Debian 12 and Ubuntu LTS releases. Always install from MongoDB's official repositories — never use the mongodb package bundled with your Linux distribution, as it is outdated, unsupported, and can conflict with the official mongodb-org package.

If you don't yet have a server, AlexHost's VPS Hosting plans offer SSD-backed Linux VPS instances on high-performance infrastructure — ideal for running production database workloads.

Update Your System First

Always start with a fully updated system:

sudo apt-get update && sudo apt-get -y upgrade
sudo apt-get install -y gnupg curl

2. Install MongoDB on Debian 12 (Bookworm)

MongoDB is not available in the default Debian repositories, so you must add the official MongoDB APT repository manually.

Step 1 — Import the MongoDB GPG Signing Key

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | 
  sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg

This downloads and stores the GPG key used to verify package integrity. Without this step, APT will refuse to install packages from the MongoDB repository.

Step 2 — Add the Official MongoDB Repository

echo "deb [signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] 
https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" | 
  sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list > /dev/null

Step 3 — Install MongoDB Community Edition

sudo apt-get update
sudo apt-get install -y mongodb-org

APT will now pull the latest MongoDB 8.0 release directly from MongoDB's official CDN.

3. Install MongoDB on Ubuntu LTS (24.04 / 22.04)

The process is nearly identical to Debian, but the repository URL differs by Ubuntu codename.

Step 1 — 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

Step 2 — Add the Repository for Your Ubuntu Version

Ubuntu 24.04 (Noble Numbat):

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

Ubuntu 22.04 (Jammy Jellyfish):

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

Step 3 — Install MongoDB Community Edition

sudo apt-get update
sudo apt-get install -y mongodb-org

4. Start and Enable the MongoDB Service

Once installed, use systemctl to start MongoDB and configure it to launch automatically on server reboot.

sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod --no-pager

Why daemon-reload?

MongoDB's official documentation specifically recommends running systemctl daemon-reload before starting the service. If you skip this step and see the error "Unit mongod.service not found", run daemon-reload first — it forces systemd to re-read unit files from disk.

Expected Output

A healthy MongoDB service will show output similar to:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled)
     Active: active (running) since ...

If the status shows failed or inactive, jump to the Troubleshooting section.

5. Create Databases and Users

MongoDB does not enforce authentication by default after a fresh install. This means you should create your admin and application users before enabling authentication — otherwise you risk locking yourself out.

Open the MongoDB Shell

Connect to MongoDB locally on the VPS:

mongosh

Step 1 — Create an Administrative User

Switch to the admin database and create a privileged admin account:

use admin

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

> Security tip: Replace STRONG_PASSWORD_HERE with a randomly generated password of at least 20 characters. Use a password manager or run openssl rand -base64 24 on your server to generate one.

Step 2 — Create an Application Database and User

Create a dedicated database and a least-privilege user scoped only to that database:

use myapp

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

This follows the principle of least privilege — your application only has read/write access to its own database, not the entire MongoDB instance.

Step 3 — Verify Users Were Created

use admin
db.getUsers()

Exit the shell:

exit

6. Secure Your MongoDB Instance

This is the most critical section of the guide. Misconfigured MongoDB instances exposed to the public internet have been responsible for numerous high-profile data breaches. MongoDB's own security checklist is explicit: harden your instance before exposing it to any network.

By default, MongoDB may listen on all network interfaces. Restrict it to localhost unless you have a specific, justified need for remote access.

Edit /etc/mongod.conf:

net:
  bindIp: 127.0.0.1

Apply the change:

sudo systemctl restart mongod

This ensures MongoDB is only reachable from the server itself — not from the public internet.

B) Enable Authentication

Without authentication enabled, any local process can connect to MongoDB without a password. Edit /etc/mongod.conf:

security:
  authorization: enabled

Restart the service:

sudo systemctl restart mongod

Now test that authentication is enforced:

mongosh -u admin -p --authenticationDatabase admin

C) Configure the Firewall

If you need to allow remote connections (e.g., from an application server on a different machine), restrict port 27017 to a specific trusted IP address only. Never open port 27017 to 0.0.0.0/0.

Using UFW:

sudo ufw allow from YOUR.TRUSTED.IP.ADDRESS to any port 27017 proto tcp
sudo ufw enable
sudo ufw status

Verify the rule is active:

sudo ufw status verbose

D) Use SSH Tunneling for Secure Remote Access (Best Practice)

The safest way to access MongoDB remotely is through an SSH tunnel. This avoids opening port 27017 entirely and encrypts all traffic in transit.

From your local machine:

ssh -L 27017:127.0.0.1:27017 root@YOUR_VPS_IP

Then connect from your local MongoDB shell as if it were local:

mongosh "mongodb://myapp_user:PASS@127.0.0.1:27017/myapp?authSource=myapp"

This approach is strongly recommended for developers accessing production databases from laptops or remote workstations.

Security Hardening Summary

Security MeasureConfiguration LocationPriority
Bind to localhost only/etc/mongod.confnet.bindIpCritical
Enable authentication/etc/mongod.confsecurity.authorizationCritical
Firewall port restrictionUFW / iptablesHigh
SSH tunnel for remote accessClient-side SSH configHigh
Use least-privilege DB usersmongoshdb.createUser()High
Keep MongoDB updatedapt-get upgrade mongodb-orgMedium

7. Backup and Restore

Regular backups are non-negotiable for any production database. MongoDB includes mongodump and mongorestore as part of the MongoDB Database Tools package.

Create a Compressed Backup Archive

mongodump 
  --username admin 
  --password STRONG_PASSWORD_HERE 
  --authenticationDatabase admin 
  --archive=/root/mongo-backup.archive 
  --gzip

This creates a single compressed archive file containing a logical dump of all databases.

Restore from a Backup Archive

mongorestore 
  --username admin 
  --password STRONG_PASSWORD_HERE 
  --authenticationDatabase admin 
  --archive=/root/mongo-backup.archive 
  --gzip

Automate Backups with Cron

Schedule daily backups using cron:

crontab -e

Add the following line to run a backup every day at 2:00 AM:

0 2 * * * mongodump --username admin --password PASS --authenticationDatabase admin --archive=/root/backups/mongo-$(date +%F).archive --gzip

> Pro tip: For off-site redundancy, consider syncing backup archives to an external storage location using rsync or rclone. Never store your only backup on the same server as your database.

8. Troubleshooting Common Issues

Check Service Logs

The first place to look when MongoDB fails to start or behaves unexpectedly:

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

This shows the last 200 lines of MongoDB's systemd journal — usually enough to identify the root cause.

Verify MongoDB Is Listening on the Expected Port

sudo ss -lntp | grep 27017

Expected output if MongoDB is running and bound to localhost:

LISTEN  0  128  127.0.0.1:27017  0.0.0.0:*  users:(("mongod",...))

If there is no output, MongoDB is not running or is bound to a different interface.

Check the Installed MongoDB Version

mongod --version

Common Error Messages and Fixes

ErrorLikely CauseFix
Unit mongod.service not foundsystemd hasn't loaded the unit fileRun sudo systemctl daemon-reload
Address already in usePort 27017 is occupied by another processRun `sudo ss -lntpgrep 27017` to identify the conflict
Authentication failedWrong credentials or wrong authSourceVerify username, password, and authenticationDatabase
Connection refusedMongoDB not running or bound to wrong IPCheck bindIp in mongod.conf and service status
mongod.conf permission deniedFile permissions issueRun sudo chmod 600 /etc/mongod.conf

9. Final Thoughts

Running MongoDB on a VPS is a proven, cost-effective approach for production workloads that demand flexibility, performance, and full infrastructure control. By following this guide, you've installed MongoDB 8.0 from official repositories, configured authentication and network binding, created least-privilege database users, set up firewall rules, and established a backup routine.

A few key takeaways to remember:

  • Always enable authentication — an unauthenticated MongoDB instance is a critical security vulnerability.
  • Never expose port 27017 to the public internet — use SSH tunneling or restrict access to specific trusted IPs.
  • Keep MongoDB updated — run sudo apt-get upgrade mongodb-org regularly to receive security patches.
  • Test your backups — a backup you've never restored is a backup you can't trust.

For teams that need a reliable, high-performance foundation for MongoDB deployments, AlexHost's VPS Hosting provides SSD NVMe storage, full root access, and flexible resource scaling. If your workload grows beyond a single VPS, Dedicated Servers offer dedicated CPU and RAM resources with no noisy-neighbor effects — ideal for high-traffic MongoDB replica sets or sharded clusters.

Need a complete hosting stack? Pair your database VPS with Shared Web Hosting for your front-end or static assets, and secure your application traffic with an SSL Certificate to protect data in transit between your users and your servers.

*Last updated for MongoDB Community Edition 8.0 on Debian 12 (Bookworm) and Ubuntu 22.04/24.04 LTS.*