Install MongoDB on Ubuntu VPS with Security Setup

Install MongoDB on Ubuntu VPS with Security Setup

June 2026 · 8 min read

MongoDB is a NoSQL database that stores data in JSON format (BSON), making it ideal for applications with flexible data structures or those requiring horizontal scaling. MongoDB instances exposed to the internet without authentication are one of the most common attack vectors found in the wild. This article will walk you through setting up comprehensive security before going into production.

Install MongoDB 7

sudo apt update
sudo apt install gnupg curl -y

# Import MongoDB GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

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

sudo apt update
sudo apt install -y mongodb-org

# Start service
sudo systemctl enable --now mongod

Set Up Authentication (Required for Production)

# Enter mongo shell
mongosh

# Create admin user
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),  // System will prompt for password
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    { role: "readWriteAnyDatabase", db: "admin" },
    "dbAdminAnyDatabase"
  ]
})

exit
# Enable authentication in config
sudo nano /etc/mongod.conf

# Modify the security section:
security:
  authorization: enabled

# Bind IP to accept only localhost or private IP
net:
  bindIp: 127.0.0.1,192.168.1.10  # Add your app server's private IP

sudo systemctl restart mongod

Create Database User for Application

mongosh -u admin -p --authenticationDatabase admin

use myapp_db
db.createUser({
  user: "appuser",
  pwd: "SecurePassword123!",
  roles: [{ role: "readWrite", db: "myapp_db" }]
})

exit

Backup with mongodump

# Backup a single database
mongodump --uri="mongodb://appuser:password@localhost/myapp_db" \
  --out=/backup/mongodb/$(date +%Y%m%d)

# Restore from backup
mongorestore --uri="mongodb://appuser:password@localhost/myapp_db" \
  --db myapp_db /backup/mongodb/20260612/myapp_db/
Tip: Set up daily cron backup: 0 2 * * * mongodump --uri="..." --out=/backup/mongodb/$(date +\%Y\%m\%d) --gzip and delete backups older than 30 days with find /backup/mongodb -mtime +30 -delete

Verify MongoDB is Working Correctly

# Check service status
systemctl status mongod

# Verify authentication is working
mongosh --eval "db.adminCommand({ connectionStatus: 1 })"

# Connect with the user you created
mongosh -u admin -p --authenticationDatabase admin --eval "show dbs"

# Check for errors in logs
sudo tail -50 /var/log/mongodb/mongod.log | grep -i error
Tip: Open mongod.conf and verify that net.bindIp is set correctly — ensure it does not bind to 0.0.0.0 in production. If your application is on a different server, bind only to the private IP between machines.

Common Issues & Troubleshooting

Error: "MongoServerError: Authentication failed"

You entered an incorrect password or the authenticationDatabase parameter is wrong. The admin user must authenticate against the admin database:

# Always specify authenticationDatabase
mongosh -u admin -p --authenticationDatabase admin

# Incorrect
mongosh -u admin -p --authenticationDatabase myapp_db  # Wrong

mongod fails to start

Check directory permissions or whether port 27017 is already in use:

# Check logs
sudo journalctl -u mongod -n 50

# Check permissions
ls -la /var/lib/mongodb /var/log/mongodb
sudo chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb

# Check port
sudo ss -tlnp | grep 27017

MongoDB consuming too much RAM

MongoDB uses the WiredTiger storage engine which caches 50% of available RAM by default. For VPS with limited RAM, lower this setting:

sudo nano /etc/mongod.conf

# Add to storage section:
storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 0.5  # Adjust based on available RAM

Connection string in application is incorrect

A correct connection string must specify the authenticationDatabase:

# Correct
mongodb://appuser:password@localhost:27017/myapp_db?authSource=myapp_db

# For admin user
mongodb://admin:password@localhost:27017/admin?authSource=admin

Frequently Asked Questions

When is MongoDB suitable to use?

MongoDB is ideal for: storing JSON with frequently changing structure (such as user preferences, product catalogs), real-time analytics, content management systems with nested data, and applications requiring schema-less design. It is not suitable for: transactions requiring full ACID compliance, relational data with complex JOINs, or rigid schema enforcement.

What is the difference between MongoDB Atlas and self-hosted on VPS?

MongoDB Atlas is a managed service offering easy maintenance, automatic backups, scaling, and monitoring — but at higher cost. Self-hosted on VPS gives you more control and lower cost, but you must handle security, backups, and updates yourself.

How do I know if my indexes are performing well?

Use explain("executionStats") to examine the query plan: db.collection.find({field: value}).explain("executionStats"). Look at the totalDocsExamined value — if it is much higher than nReturned, your index is inefficient or missing.