Prerequisites & VPS Selection
What You'll Need
- Ubuntu 22.04/24.04 or Debian 11/12
- Root or sudo access
- Adequate disk space for your data
- Basic understanding of database concepts
Install MongoDB
Install MongoDB Community Edition from the official repository:
sudo apt-get install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmorecho "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💡 For Ubuntu 24.04: Replace jammy with noble in the repository URL.
sudo apt-get update
sudo apt-get install -y mongodb-orgsudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongodmongod --version
mongosh --eval 'db.runCommand({ connectionStatus: 1 })'Configure MongoDB
Configure MongoDB for your environment:
# mongod.conf
# Data storage
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 1 # Adjust based on RAM (50% of available)
# Network interfaces
net:
port: 27017
bindIp: 127.0.0.1 # Change to 0.0.0.0 for remote access
# Process Management
processManagement:
timeZoneInfo: /usr/share/zoneinfo
# Security
security:
authorization: enabled
# Operation Profiling
operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
# Logging
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log⚠️ WiredTiger Cache: Set cacheSizeGB to about 50% of your available RAM minus 1GB for optimal performance.
sudo systemctl restart mongodSecurity Setup
Create an admin user and enable authentication:
mongoshuse admin
db.createUser({
user: "admin",
pwd: passwordPrompt(), // Prompts for password
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})use myapp
db.createUser({
user: "appuser",
pwd: passwordPrompt(),
roles: [
{ role: "readWrite", db: "myapp" }
]
})✅ Best Practice: Create separate users for each application with minimal required permissions.
# Exit mongosh and reconnect with authentication
mongosh -u admin -p --authenticationDatabase adminFirewall Configuration
Configure UFW to protect MongoDB:
# Install UFW if not present
sudo apt install -y ufw
# Allow SSH first!
sudo ufw allow 22/tcp
# Allow MongoDB only from specific IPs (recommended)
sudo ufw allow from YOUR_APP_SERVER_IP to any port 27017
# Or allow from any (less secure)
# sudo ufw allow 27017/tcp
# Enable firewall
sudo ufw enable
sudo ufw status⚠️ Security Warning: Never expose MongoDB port 27017 to the public internet without authentication and IP restrictions!
Connect to MongoDB
Various ways to connect to your MongoDB instance:
MongoDB Shell
mongosh -u admin -p --authenticationDatabase adminConnection String
mongodb://admin:password@localhost:27017/admin# Show databases
show dbs
# Use a database (creates if doesn't exist)
use myapp
# Insert a document
db.users.insertOne({
name: "John Doe",
email: "john@example.com",
created: new Date()
})
# Find documents
db.users.find()
# Create an index
db.users.createIndex({ email: 1 }, { unique: true })Enable Remote Access
Configure MongoDB for secure remote connections:
# In /etc/mongod.conf, change:
net:
port: 27017
bindIp: 0.0.0.0 # Listen on all interfaces
# Or specific IPs: 127.0.0.1,192.168.1.100sudo systemctl restart mongodRemote Connection String
mongodb://appuser:password@YOUR_SERVER_IP:27017/myapp💡 TLS/SSL: For production, configure TLS encryption for connections. See MongoDB documentation for certificate setup.
Replica Set Setup (Optional)
Set up a replica set for high availability (requires multiple servers):
# Add to /etc/mongod.conf on all nodes:
replication:
replSetName: "rs0"# On the primary node, connect to mongosh:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1.example.com:27017" },
{ _id: 1, host: "mongo2.example.com:27017" },
{ _id: 2, host: "mongo3.example.com:27017" }
]
})
# Check replica set status
rs.status()Replica Set Benefits
- • High Availability: Automatic failover if primary goes down
- • Data Redundancy: Data replicated across nodes
- • Read Scaling: Distribute reads across secondaries
Backup Strategy
Implement a robust backup strategy:
# Backup all databases
mongodump --uri="mongodb://admin:password@localhost:27017" \
--authenticationDatabase=admin \
--out=/backups/mongodb/$(date +%Y%m%d_%H%M%S)
# Backup specific database
mongodump --uri="mongodb://admin:password@localhost:27017/myapp" \
--authenticationDatabase=admin \
--out=/backups/mongodb/myapp_$(date +%Y%m%d)#!/bin/bash
# /opt/mongodb/backup.sh
BACKUP_DIR="/backups/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
MONGO_USER="admin"
MONGO_PASS="your_password"
# Create backup directory
mkdir -p $BACKUP_DIR
# Run backup
mongodump --uri="mongodb://$MONGO_USER:$MONGO_PASS@localhost:27017" \
--authenticationDatabase=admin \
--out=$BACKUP_DIR/$DATE
# Compress backup
tar -czf $BACKUP_DIR/$DATE.tar.gz -C $BACKUP_DIR $DATE
rm -rf $BACKUP_DIR/$DATE
# Keep only last 7 days of backups
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete
echo "Backup completed: $DATE.tar.gz"chmod +x /opt/mongodb/backup.sh
mkdir -p /backups/mongodb
# Add to crontab (daily at 2 AM)
(crontab -l 2>/dev/null; echo "0 2 * * * /opt/mongodb/backup.sh") | crontab -# Extract backup
tar -xzf /backups/mongodb/20241217_020000.tar.gz -C /tmp
# Restore
mongorestore --uri="mongodb://admin:password@localhost:27017" \
--authenticationDatabase=admin \
/tmp/20241217_020000Performance Tuning
Optimize MongoDB for better performance:
Index Optimization
# Explain a query
db.collection.find({ field: "value" }).explain("executionStats")
# Find slow queries
db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 })
# List all indexes
db.collection.getIndexes()
# Create compound index
db.users.createIndex({ status: 1, created: -1 })System Optimizations
# Disable Transparent Huge Pages
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
# Increase file descriptors
echo "mongod soft nofile 64000" | sudo tee -a /etc/security/limits.conf
echo "mongod hard nofile 64000" | sudo tee -a /etc/security/limits.conf
# Set swappiness
echo "vm.swappiness = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -pWiredTiger Cache
Adjust cache size based on your workload:
- • 4GB RAM → 1.5GB cache
- • 8GB RAM → 3.5GB cache
- • 16GB RAM → 7GB cache
Monitoring
Monitor MongoDB health and performance:
# Server status
db.serverStatus()
# Current operations
db.currentOp()
# Database stats
db.stats()
# Collection stats
db.collection.stats()
# Replication status (replica sets)
rs.status()
# Connection pool stats
db.serverStatus().connectionsKey Metrics to Monitor
- • Connections (current/available)
- • Operations per second
- • Query execution time
- • Replication lag
- • Memory usage
- • Cache hit ratio
- • Disk I/O
- • Index usage
💡 Pro Tip: Consider using MongoDB Compass (GUI) or integrate with Prometheus + Grafana for comprehensive monitoring dashboards.
Troubleshooting
MongoDB Won't Start
sudo systemctl status mongod
sudo journalctl -u mongod -f
sudo tail -100 /var/log/mongodb/mongod.log
# Check for lock file issues
sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair --dbpath /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/lib/mongodbConnection Refused
# Check if MongoDB is listening
sudo netstat -tlnp | grep 27017
# Check bindIp in config
grep bindIp /etc/mongod.conf
# Test local connection
mongosh --eval "db.adminCommand('ping')"
# Check firewall
sudo ufw statusAuthentication Failed
# Temporarily disable auth in mongod.conf
# Comment out: authorization: enabled
sudo systemctl restart mongod
# Connect and update password
mongosh
use admin
db.changeUserPassword("admin", "newpassword")
# Re-enable auth and restart
sudo systemctl restart mongodHigh Memory Usage
# Check WiredTiger cache usage
db.serverStatus().wiredTiger.cache
# Reduce cache size in mongod.conf
# storage.wiredTiger.engineConfig.cacheSizeGB: 1MongoDB Deployed Successfully!
Your MongoDB database is now running securely. Start building your applications with flexible document storage.
