MongoDB is one of the most popular NoSQL databases, powering modern web applications from startups to Fortune 500 companies. But installing and configuring MongoDB on a VPS has traditionally required extensive terminal knowledge and Linux expertise.
Not anymore. In this comprehensive guide, I'll show you how to install MongoDB on your VPS, configure security, set up users, enable remote access, and configure backups - all without typing complex terminal commands. Whether you're a developer, business owner, or database administrator, this guide will have you running MongoDB in under 30 minutes.
What is MongoDB?
MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents. Unlike traditional relational databases (MySQL, PostgreSQL), MongoDB doesn't require a fixed schema, making it perfect for applications with evolving data requirements.
Why Use MongoDB?
- Flexible Schema: Store documents with different structures in the same collection
- Horizontal Scalability: Easily scale across multiple servers
- High Performance: Fast read/write operations, especially for large datasets
- Rich Query Language: Powerful querying capabilities with aggregation framework
- Developer-Friendly: Works naturally with JSON and modern programming languages
- Replication & High Availability: Built-in replication for data redundancy
Prerequisites
Before starting, ensure you have:
- A VPS running Ubuntu 22.04 or 24.04 (this guide focuses on Ubuntu)
- At least 1GB RAM (2GB+ recommended for production)
- Root or sudo access to your VPS
- VPS Commander installed (for terminal-free management) or SSH access
- Basic understanding of what a database is
Step 1: Prepare Your VPS
Update System Packages
First, ensure your system is up to date. Using VPS Commander's command interface, execute:
sudo apt update && sudo apt upgrade -y
What this does: Downloads the latest package information and upgrades all installed packages to their newest versions.
Check Available Disk Space
df -h
Ensure you have at least 10GB of free space. MongoDB's database files can grow quickly depending on your data volume.
Step 2: Install MongoDB Community Edition
Import MongoDB Public GPG Key
MongoDB packages are signed with a GPG key for security. Import it:
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
Add MongoDB Repository
Create a list file for MongoDB:
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
Note: "jammy" is Ubuntu 22.04's codename. For Ubuntu 24.04 (noble), replace "jammy" with "noble".
Install MongoDB
Update package list and install MongoDB:
sudo apt update
sudo apt install -y mongodb-org
This installs MongoDB Community Edition 7.0 (latest stable version as of 2025).
Verify Installation
Check the installed MongoDB version:
mongod --version
You should see output showing MongoDB version 7.0.x.
Step 3: Start and Enable MongoDB Service
Start MongoDB
sudo systemctl start mongod
Enable MongoDB to Start on Boot
sudo systemctl enable mongod
Check MongoDB Status
sudo systemctl status mongod
You should see "active (running)" in green. If not, check the troubleshooting section below.
Manage MongoDB Without Terminal
VPS Commander lets you execute these commands through a simple web interface. No need to memorize syntax or worry about typos. Just click, paste, and execute - with built-in command templates for common MongoDB operations.
Try VPS Commander FreeStep 4: Secure MongoDB with Authentication
Critical Security Note: By default, MongoDB installs without authentication enabled. This means anyone who can access your server can read, modify, or delete your data. We'll fix this now.
Connect to MongoDB Shell
mongosh
You'll see the MongoDB shell prompt: test>
Create Administrator User
Switch to the admin database and create an admin user:
use admin
db.createUser({
user: "adminUser",
pwd: "YourStrongPassword123!",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})
Important: Replace YourStrongPassword123! with a strong password. Use a password generator for production environments.
Create Application Database and User
Create a dedicated user for your application (best practice - don't use the admin user for applications):
use myAppDatabase
db.createUser({
user: "appUser",
pwd: "AnotherStrongPassword456!",
roles: [
{ role: "readWrite", db: "myAppDatabase" }
]
})
This creates a user with read/write permissions only for the myAppDatabase database.
Exit MongoDB Shell
exit
Step 5: Enable Authentication
Edit MongoDB Configuration
Open the MongoDB configuration file:
sudo nano /etc/mongod.conf
Using VPS Commander's file editor, find the security section and modify it to enable authentication:
security:
authorization: enabled
Note: YAML is whitespace-sensitive. Ensure proper indentation (2 spaces, not tabs).
Restart MongoDB
sudo systemctl restart mongod
Test Authentication
Try connecting with your admin user:
mongosh -u adminUser -p YourStrongPassword123! --authenticationDatabase admin
If you see the MongoDB shell prompt, authentication is working correctly!
Step 6: Configure Remote Access
By default, MongoDB only listens on localhost (127.0.0.1), meaning you can't connect from your local machine or other servers. To enable remote access:
Configure Bind IP
Edit /etc/mongod.conf again:
sudo nano /etc/mongod.conf
Find the net section and modify the bindIp:
net:
port: 27017
bindIp: 0.0.0.0
What this does: 0.0.0.0 allows connections from any IP address. In production, specify your application server's IP instead for better security.
Configure Firewall
Open MongoDB's port (27017) in your firewall:
sudo ufw allow 27017/tcp
sudo ufw reload
Security Best Practice: Only allow specific IP addresses:
sudo ufw allow from YOUR_APP_SERVER_IP to any port 27017
Restart MongoDB
sudo systemctl restart mongod
Test Remote Connection
From your local machine, test the connection:
mongosh "mongodb://appUser:AnotherStrongPassword456!@YOUR_VPS_IP:27017/myAppDatabase"
Replace YOUR_VPS_IP with your VPS's public IP address.
mongodb://username:password@host:port/databaseThis is what you'll use in your application code to connect to MongoDB.
Step 7: Configure MongoDB for Production
Set Resource Limits
Edit MongoDB's systemd service file to increase file descriptor limits:
sudo nano /lib/systemd/system/mongod.service
Add these lines under [Service]:
LimitNOFILE=64000
LimitNPROC=64000
Reload systemd and restart MongoDB:
sudo systemctl daemon-reload
sudo systemctl restart mongod
Configure Storage Engine (WiredTiger)
MongoDB 7.0 uses WiredTiger by default, which provides excellent performance and compression. Verify in /etc/mongod.conf:
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
Cache Size: Set to 50-60% of available RAM. For a 2GB VPS, use 1GB cache. For 4GB VPS, use 2GB cache.
Enable Logging
Ensure logging is properly configured:
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
logRotate: reopen
Step 8: Set Up Automated Backups
Database backups are critical. MongoDB provides mongodump for creating backups.
Create Backup Script
Create a backup directory and script:
sudo mkdir -p /var/backups/mongodb
sudo nano /usr/local/bin/mongodb-backup.sh
Add this content to the script:
#!/bin/bash
# MongoDB backup script
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/mongodb"
MONGO_USER="adminUser"
MONGO_PASSWORD="YourStrongPassword123!"
MONGO_HOST="localhost"
MONGO_PORT="27017"
# Create backup
mongodump --username=$MONGO_USER --password=$MONGO_PASSWORD --authenticationDatabase=admin --host=$MONGO_HOST --port=$MONGO_PORT --out=$BACKUP_DIR/$DATE
# Compress backup
tar -czf $BACKUP_DIR/mongodb_backup_$DATE.tar.gz -C $BACKUP_DIR $DATE
# Remove uncompressed backup
rm -rf $BACKUP_DIR/$DATE
# Keep only last 7 days of backups
find $BACKUP_DIR -name "mongodb_backup_*.tar.gz" -mtime +7 -delete
echo "MongoDB backup completed: mongodb_backup_$DATE.tar.gz"
Make the script executable:
sudo chmod +x /usr/local/bin/mongodb-backup.sh
Schedule Automatic Backups
Add a cron job to run backups daily at 2 AM:
sudo crontab -e
Add this line:
0 2 * * * /usr/local/bin/mongodb-backup.sh >> /var/log/mongodb-backup.log 2>&1
Test the Backup Script
sudo /usr/local/bin/mongodb-backup.sh
Check that the backup file was created:
ls -lh /var/backups/mongodb/
Step 9: Monitor MongoDB Performance
Check Server Status
Connect to MongoDB and run:
mongosh -u adminUser -p --authenticationDatabase admin
db.serverStatus()
This shows detailed metrics including connections, operations, memory usage, and more.
Monitor Active Connections
db.currentOp()
db.serverStatus().connections
Check Database Size
db.stats()
View Recent Log Entries
sudo tail -f /var/log/mongodb/mongod.log
Monitor MongoDB with VPS Commander
VPS Commander includes real-time monitoring dashboards that show MongoDB performance metrics, active connections, query performance, and resource usage - all in a visual interface without running commands manually. Set up alerts for high memory usage or connection limits.
Get VPS CommanderStep 10: Connect from Your Application
Node.js Connection Example
const { MongoClient } = require('mongodb');
const uri = "mongodb://appUser:AnotherStrongPassword456!@YOUR_VPS_IP:27017/myAppDatabase";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected to MongoDB!");
const database = client.db("myAppDatabase");
const collection = database.collection("users");
// Insert a document
await collection.insertOne({ name: "John", email: "john@example.com" });
// Query documents
const users = await collection.find({}).toArray();
console.log(users);
} finally {
await client.close();
}
}
run();
Python Connection Example
from pymongo import MongoClient
uri = "mongodb://appUser:AnotherStrongPassword456!@YOUR_VPS_IP:27017/myAppDatabase"
client = MongoClient(uri)
db = client.myAppDatabase
users = db.users
# Insert a document
users.insert_one({"name": "John", "email": "john@example.com"})
# Query documents
for user in users.find():
print(user)
PHP Connection Example
$manager = new MongoDB\Driver\Manager("mongodb://appUser:AnotherStrongPassword456!@YOUR_VPS_IP:27017/myAppDatabase");
// Insert document
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['name' => 'John', 'email' => 'john@example.com']);
$manager->executeBulkWrite('myAppDatabase.users', $bulk);
// Query documents
$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('myAppDatabase.users', $query);
foreach ($cursor as $document) {
print_r($document);
}
Troubleshooting Common Issues
MongoDB Won't Start
Issue: systemctl status mongod shows "failed" status.
Solutions:
- Check logs:
sudo tail -100 /var/log/mongodb/mongod.log - Verify configuration syntax:
mongod --config /etc/mongod.conf --configExpand rest - Check disk space:
df -h(MongoDB needs space for data and journal files) - Verify permissions:
sudo chown -R mongodb:mongodb /var/lib/mongodb - Check port availability:
sudo lsof -i :27017
Can't Connect Remotely
Issue: Remote connections timeout or are refused.
Solutions:
- Verify bindIp is set to
0.0.0.0in/etc/mongod.conf - Check firewall:
sudo ufw status- ensure port 27017 is allowed - Verify cloud provider firewall (AWS Security Groups, DigitalOcean Firewall, etc.)
- Test connectivity:
telnet YOUR_VPS_IP 27017from local machine - Check if MongoDB is listening:
sudo netstat -tulpn | grep 27017
Authentication Failed
Issue: "Authentication failed" error when connecting.
Solutions:
- Verify username and password are correct
- Ensure you're using
--authenticationDatabase adminfor admin user - Check user exists:
use admin; db.getUsers() - Verify authorization is enabled in
/etc/mongod.conf - Restart MongoDB after config changes
High Memory Usage
Issue: MongoDB consuming too much RAM.
Solutions:
- Reduce WiredTiger cache size in
/etc/mongod.conf - Ensure proper indexes are in place (missing indexes cause full collection scans)
- Monitor query performance with
db.currentOp() - Consider upgrading VPS if dataset has legitimately grown
Slow Query Performance
Issue: Database queries are slow.
Solutions:
- Create indexes:
db.collection.createIndex({ fieldName: 1 }) - Use
explain()to analyze queries:db.collection.find({}).explain("executionStats") - Enable profiling:
db.setProfilingLevel(1, { slowms: 100 }) - Review slow queries:
db.system.profile.find().sort({ ts: -1 }).limit(5) - Optimize query patterns in your application code
Security Best Practices
- Always Enable Authentication: Never run MongoDB without authentication in production
- Use Strong Passwords: Minimum 20 characters with numbers, symbols, and mixed case
- Restrict Network Access: Use firewall rules to allow only specific IPs
- Enable TLS/SSL: Encrypt connections between clients and MongoDB
- Regular Backups: Test restoration process monthly
- Keep MongoDB Updated: Apply security patches promptly
- Monitor Logs: Watch for unauthorized access attempts
- Principle of Least Privilege: Give users only the permissions they need
- Separate Admin and App Users: Never use admin credentials in application code
Performance Optimization Tips
1. Create Appropriate Indexes
Indexes dramatically improve query performance:
// Single field index
db.users.createIndex({ email: 1 })
// Compound index
db.orders.createIndex({ userId: 1, createdAt: -1 })
// Unique index
db.users.createIndex({ email: 1 }, { unique: true })
2. Use Projection to Limit Returned Fields
// Only return name and email fields
db.users.find({}, { name: 1, email: 1, _id: 0 })
3. Implement Connection Pooling
Reuse database connections instead of creating new ones for each request:
const client = new MongoClient(uri, {
maxPoolSize: 10,
minPoolSize: 2
});
4. Use Aggregation Pipeline Efficiently
Place filtering stages early to reduce document count:
db.orders.aggregate([
{ $match: { status: "completed" } }, // Filter first
{ $group: { _id: "$userId", total: { $sum: "$amount" } } }
])
5. Enable Compression
WiredTiger compression is enabled by default and can reduce storage by 60-80%:
storage:
wiredTiger:
collectionConfig:
blockCompressor: snappy
Conclusion
Congratulations! You've successfully installed MongoDB on your VPS, configured authentication, enabled remote access, set up automated backups, and learned performance optimization techniques - all without becoming a Linux expert.
MongoDB is now ready to power your applications with fast, flexible, scalable data storage. Whether you're building a web app, mobile backend, or data analytics platform, you have a production-ready database infrastructure.
Key takeaways:
- Always enable authentication before exposing MongoDB to the network
- Use separate users for administration and application access
- Implement automated backups and test restoration regularly
- Create indexes for frequently queried fields
- Monitor performance and resource usage
- Keep MongoDB updated with latest security patches
With VPS Commander, you can manage MongoDB and your entire VPS infrastructure through a simple web interface, execute commands without memorizing syntax, and monitor database performance in real-time. No terminal expertise required!