Tutorial 📅 January 20, 2025 📖 8 min read

How to Install MongoDB on VPS Without Terminal Commands (2025)

Step-by-step MongoDB installation on VPS without using terminal. Secure setup, user creation, remote access configuration made simple.

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?

Popular Use Cases: MongoDB powers mobile apps, content management systems, real-time analytics, IoT applications, e-commerce catalogs, gaming backends, and any application requiring flexible, scalable data storage.

Prerequisites

Before starting, ensure you have:

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.

Installation Complete! MongoDB is now installed on your VPS. Next, we'll configure it for secure operation.

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 Free

Step 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!

Security Milestone: Your MongoDB instance is now secured with authentication. Unauthorized users can no longer access your database.

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.

Connection String Format: mongodb://username:password@host:port/database
This 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/
Backups Configured! Your MongoDB database will now be backed up automatically every night at 2 AM, with 7 days of backup retention.

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 Commander

Step 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:

Can't Connect Remotely

Issue: Remote connections timeout or are refused.

Solutions:

Authentication Failed

Issue: "Authentication failed" error when connecting.

Solutions:

High Memory Usage

Issue: MongoDB consuming too much RAM.

Solutions:

Slow Query Performance

Issue: Database queries are slow.

Solutions:

Security Best Practices

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:

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!

Related Articles