Installing MongoDB on VPS: Basic Setup and Security
TL;DR
In this comprehensive guide, we will set up a secure MongoDB server step-by-step on a Virtual Private Server (VPS) running Ubuntu Server 24.04 LTS. You will learn how to install the latest version of MongoDB (7.0), configure it for secure operation with authentication and TLS, set up a firewall, and create an effective backup strategy, ensuring a reliable and high-performance database for your applications.
Installing MongoDB 7.0 on Ubuntu 24.04 LTS from the official repository.
Basic server protection: SSH keys, sudo user, UFW, Fail2Ban.
MongoDB configuration with authentication enabled and user creation.
Configuring the firewall to restrict access to the MongoDB port.
Using TLS/SSL for encrypting database connections.
Developing a backup strategy using mongodump and restic.
Troubleshooting common issues and answering frequently asked questions.
What we are setting up and why
In this guide, we will focus on installing and configuring MongoDB on your own Virtual Private Server (VPS). MongoDB is a popular document-oriented NoSQL database, ideal for modern web applications requiring a flexible schema, high performance, and scalability. Unlike traditional relational databases, MongoDB stores data in BSON (Binary JSON) format, making it very convenient for working with unstructured or semi-structured data.
Ultimately, upon completing this tutorial, you will have a fully configured and secured MongoDB instance, ready to accept connections from your applications. You will be able to manage the database, create users with various access rights, and be confident in the security of your stored data.
Why choose self-hosted MongoDB on a VPS instead of cloud solutions? Self-hosting provides complete control over server configuration, performance optimization, and costs. For many projects, especially in the initial stages or with specific security and data location requirements, your own VPS can be significantly more cost-effective than managed cloud services like MongoDB Atlas, AWS DocumentDB, or Azure Cosmos DB. It's also an excellent way to gain a deep understanding of database and infrastructure operations.
What VPS config is needed for this task
Choosing the right VPS configuration is critical for the performance and stability of your MongoDB database. Requirements can vary greatly depending on data volume, query intensity, and the number of concurrent connections. We focus on typical tasks such as deploying GitLab, Mattermost, a Minecraft server, or a cryptocurrency node, where MongoDB can be used as part of the stack.
Minimum requirements for light loads (development, test environments, personal projects):
CPU: 2 cores. For MongoDB, not only the number of cores but also their performance is important.
RAM: 4 GB. MongoDB actively uses RAM for data caching (WiredTiger Cache), which significantly increases performance. Less than 4 GB can lead to intensive disk usage and reduced performance.
Disk: 50 GB NVMe SSD. Disk subsystem speed is one of the most important factors for MongoDB. NVMe SSDs provide significantly higher IOPS (Input/Output Operations Per Second) compared to regular SSDs or HDDs.
Network: 1 Gbit/s. This is sufficient for most tasks.
Recommended VPS plan for moderate loads (small production applications, medium projects):
For more serious tasks, where active data operations and several concurrent users are expected, the following configuration is recommended:
CPU: 4 cores.
RAM: 8-16 GB. The more data cached in RAM, the faster the queries.
Disk: 160-320 GB NVMe SSD. The disk size should be sufficient for current data and its growth over several years, as well as for backups.
Very large data volumes: Hundreds of gigabytes or terabytes of data requiring maximum disk subsystem performance.
High IOPS requirements: Intensive read/write operations that may be limited on a VPS due to shared resource usage.
Maximum isolation and security: Full control over hardware, no "neighbors" on the same physical server.
Specialized hardware: Need for specific RAID controllers, high-performance network cards, or GPUs for certain tasks.
For most medium-sized projects, a VPS with good NVMe SSDs will be sufficient. If you plan to deploy a large GitLab, a high-load SaaS, or a demanding cryptocurrency node, then a suitable dedicated server might be a more justified choice.
Location: what it affects
The choice of VPS location affects:
Latency: The closer the server is to your users or to the application server that will connect to MongoDB, the lower the latency will be.
Legal compliance: In some cases, data must be stored in a specific jurisdiction (e.g., GDPR in Europe).
Cost: VPS prices can vary depending on the data center and region.
Always choose a location that minimizes the distance between the database and the main application.
Server Preparation
Before installing MongoDB, it is necessary to perform a minimal setup of a fresh VPS. This will ensure basic security and ease of management. We will use Ubuntu Server 24.04 LTS as the most common and supported operating system.
1. SSH Connection and System Update
Connect to your VPS as the root user (or the user provided by your provider) via SSH. Then update all packages to the latest versions.
This command updates the list of available packages and installs all system updates.
2. Creating a New User with Sudo Privileges
Working as the root user is insecure. Create a new user and grant them sudo privileges.
adduser your_user
Follow the prompts to set a password and fill in user information. Then add the user to the sudo group:
usermod -aG sudo your_user
Now you can exit the root session and connect as the new user:
exit
ssh your_user@YOUR_VPS_IP_ADDRESS
All subsequent commands requiring administrator privileges should be executed with the sudo prefix.
3. Setting up SSH Keys (Recommended)
To enhance security, it is recommended to use SSH keys instead of passwords. If you don't already have a key pair, create them on your local machine:
ssh-keygen -t rsa -b 4096
Then copy your public key to your VPS:
ssh-copy-id your_user@YOUR_VPS_IP_ADDRESS
After successfully copying the key, edit the SSH configuration file on the server to disable password authentication and disallow root login.
sudo nano /etc/ssh/sshd_config
Find and change (or add) the following lines:
# Disallow root login
PermitRootLogin no
# Disable password authentication (after verifying key login)
PasswordAuthentication no
# Ensure key authentication is allowed
PubkeyAuthentication yes
Save changes (Ctrl+O, Enter) and exit (Ctrl+X). Restart the SSH service:
sudo systemctl restart sshd
IMPORTANT: Before closing the current SSH session, open a new terminal window and try connecting to the server using the new user and SSH key. Make sure you can log in. If not, fix the errors before closing the current session, otherwise you might lose access to the server.
4. Configuring the Firewall (UFW)
UFW (Uncomplicated Firewall) is a convenient tool for managing the firewall. By default, it blocks all incoming connections. First, allow SSH, then enable UFW.
Currently, the MongoDB port (27017) is closed. We will open it later, after installation and basic configuration.
5. Installing Fail2Ban
Fail2Ban scans server logs for suspicious activity (e.g., multiple failed SSH login attempts) and temporarily blocks the IP addresses of attackers.
sudo apt install -y fail2ban # Install Fail2Ban
sudo systemctl enable fail2ban # Enable autostart on boot
sudo systemctl start fail2ban # Start the service
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # Create a local copy for settings
Open /etc/fail2ban/jail.local and ensure that the [sshd] section is active (enabled = true). You can also configure bantime (ban time) and findtime (period for detecting attempts).
sudo nano /etc/fail2ban/jail.local
Find the [DEFAULT] section and, if desired, change:
bantime = 1d # Block for 1 day
findtime = 10m # If within 10 minutes...
maxretry = 5 # ...there were 5 failed attempts
Restart Fail2Ban to apply changes:
sudo systemctl restart fail2ban
Now your server has basic protection, and we are ready to install MongoDB.
Software Installation — Step-by-Step
We will be installing MongoDB version 7.0, which is current and stable for 2026, on Ubuntu Server 24.04 LTS. The installation will be performed from the official MongoDB repository, which ensures the receipt of up-to-date updates and security patches.
1. Import MongoDB Public GPG Key
To verify the integrity of MongoDB packages, you need to import the public GPG key.
sudo apt install -y gnupg curl # Install gnupg and curl utilities if they are not already installed
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg # Import key and save to keyring
This command downloads the key and saves it to the /usr/share/keyrings/ directory, making it available to APT.
2. Add MongoDB Repository to APT Sources List
Now you need to add the URL of the official MongoDB repository to your system's package sources list. This will allow APT to find and install MongoDB packages.
This command adds a new line to the file /etc/apt/sources.list.d/mongodb-org-7.0.list, telling APT where to find MongoDB 7.0 packages for your architecture (amd64 or arm64) and Ubuntu version ($(lsb_release -cs) will automatically determine the codename of your Ubuntu version, e.g., noble for 24.04 LTS).
3. Update APT Package Index
After adding the new repository, you need to update the package index so that APT learns about the available MongoDB packages.
sudo apt update # Update the list of available packages
You should see information about packages from the MongoDB repository in the output of this command.
4. Install MongoDB Packages
Now that the repository is configured, you can install MongoDB and related utilities. The mongodb-org package includes the MongoDB server (mongod), the command-line client (mongosh), and database utilities (mongodump, mongorestore, mongoimport, mongoexport).
sudo apt install -y mongodb-org # Install all MongoDB components
This command will install MongoDB 7.0 and all necessary dependencies.
5. Start and Enable MongoDB Service
After installation, you need to start the mongod service and configure it to start automatically on every server boot.
sudo systemctl start mongod # Start MongoDB service
sudo systemctl enable mongod # Enable MongoDB autostart on system boot
MongoDB should now be running and ready for use.
6. Check MongoDB Service Status
Ensure that the MongoDB service is running correctly.
sudo systemctl status mongod # Check MongoDB service status
You should see output indicating that the mongod service is active (active (running)).
7. Verify Connection to MongoDB via mongosh
Connect to the local MongoDB database using the mongosh command-line client.
mongosh # Connect to the local MongoDB instance
If you see the test> or > prompt, MongoDB is successfully installed and running. Type exit to quit the client.
Configuration
After installation, MongoDB by default runs without authentication and accepts connections only from localhost (127.0.0.1). This is unacceptable for a production environment. We will configure authentication, restrict network access, and optionally enable TLS/SSL for connection encryption.
By default, bindIp is set to 127.0.0.1, meaning MongoDB accepts connections only from the local machine. If your application is on the same VPS, this is secure. However, if the application is on a different server or you want to access MongoDB remotely, you need to change bindIp. NEVER set bindIp: 0.0.0.0 without adequate firewall and authentication configuration!
If you plan to access from a specific IP address, specify it:
# /etc/mongod.conf
...
net:
port: 27017
bindIp: 127.0.0.1,YOUR_APPLICATION_IP # Add the IP of your application or another server
...
If you are confident that your UFW firewall is configured very strictly, you can temporarily specify 0.0.0.0, but this should only be done after configuring UFW as described below.
Save and Restart MongoDB
Save changes (Ctrl+O, Enter) and exit (Ctrl+X). Then restart the MongoDB service:
sudo systemctl restart mongod
MongoDB now requires authentication for all connections.
2. Create an Administrative User
After enabling authentication, you will not be able to connect to MongoDB without credentials. Therefore, you need to create an administrative user. To do this, connect to mongosh, but with authentication. Since authentication has just been enabled, you can connect as localhost without credentials once to create the first user.
mongosh --port 27017 --authenticationDatabase admin # Connect to the admin database
Inside mongosh, execute the following commands:
use admin
db.createUser(
{
user: "mongoAdmin",
pwd: passwordPrompt(), // Enter password when prompted
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
exit
Now you can connect to MongoDB using the created user:
mongosh --port 27017 --authenticationDatabase admin -u mongoAdmin -p # You will be prompted to enter the password
After successful login, you will see the admin> or > prompt.
3. Create an Application User
For each application using MongoDB, it is recommended to create a separate user with the minimum necessary privileges.
use your_app_db # Switch to your application's database (creates it if it doesn't exist)
db.createUser(
{
user: "appUser",
pwd: passwordPrompt(), // Enter password when prompted
roles: [ { role: "readWrite", db: "your_app_db" } ] // Grant read/write permissions only to a specific DB
}
)
exit
This ensures that even if application credentials are compromised, an attacker will not gain full access to all databases.
4. Configure Firewall (UFW) for MongoDB
Now that MongoDB is secured with authentication, you can open port 27017, but only for allowed IP addresses.
sudo ufw allow from YOUR_APPLICATION_IP to any port 27017 # Allow access only from your application's IP address
sudo ufw status # Check UFW status
If you want to allow access from multiple IP addresses, repeat the ufw allow command for each of them. If your application is on the same server, you do not need to open port 27017 externally; bindIp: 127.0.0.1 is sufficient.
5. Configure TLS/SSL for Connection Encryption (Optional, but Recommended)
To ensure the confidentiality and integrity of data during transmission between the client and the MongoDB server, it is recommended to use TLS/SSL. This is especially important if MongoDB is accessible from outside the local network.
To configure TLS, you will need certificates. You can use self-signed certificates for testing or internal corporate certificates. For public servers, it is recommended to use certificates from a trusted Certificate Authority (CA), such as Let's Encrypt.
Create a Self-Signed Certificate (for example)
To generate a self-signed certificate and key in a single .pem file:
When prompted for information (Common Name, Organization, etc.), enter the appropriate data.
Configure MongoDB to Use TLS
Edit /etc/mongod.conf again:
sudo nano /etc/mongod.conf
Add or modify the net.ssl section:
# /etc/mongod.conf
...
net:
port: 27017
bindIp: 127.0.0.1,YOUR_APPLICATION_IP
ssl:
mode: requireTLS # All connections must use TLS
PEMKeyFile: /etc/ssl/mongodb/mongodb.pem
CAFile: /etc/ssl/mongodb/mongodb.pem # If using self-signed, CAFile can be the same
allowConnectionsWithoutCertificates: false # Require client certificates (can be set to true if not needed)
...
Save changes and restart MongoDB:
sudo systemctl restart mongod
Now, to connect to MongoDB, you will need to specify TLS parameters in the mongosh client or in your application's driver:
mongosh --host YOUR_VPS_IP_ADDRESS --port 27017 --authenticationDatabase admin -u mongoAdmin -p --tls --tlsCAFile /etc/ssl/mongodb/mongodb.pem --tlsAllowInvalidHostnames # --tlsAllowInvalidHostnames only for self-signed
For production certificates from Let's Encrypt or other CAs, you will need to specify the path to your certificate and, if necessary, to the CA chain.
6. Verify Functionality
Ensure that MongoDB is running, accepting connections, and authentication is enabled:
Check service status:
sudo systemctl status mongod
Should be active (running).
Check open ports:
sudo netstat -tuln | grep 27017
The output should show that port 27017 is listening on the IP addresses you specified (e.g., 127.0.0.1:27017 or 0.0.0.0:27017, if configured).
Backup is a critically important aspect of any system, especially a database. Data loss can lead to catastrophic consequences. We will cover what needs to be backed up, how to do it using mongodump and restic, and where to store the backups.
1. What to Back Up
MongoDB Data: This is the most important. The databases themselves, collections, indexes.
MongoDB Configuration File:/etc/mongod.conf. Contains important server settings.
SSL/TLS Certificates and Keys: If you are using TLS, make sure that .pem, .key, .crt files are also backed up.
Backup Scripts: If you create your own scripts, they also need to be saved.
2. Simple Auto-Backup Script (mongodump + restic)
To create MongoDB backups, we will use the mongodump utility, which creates a binary data dump. For secure and efficient backup storage, we will use restic — a modern backup tool that supports deduplication, encryption, and various storage backends.
Installing restic
sudo apt install -y restic # Install restic
Creating the Backup Script
Create the file /usr/local/bin/backup_mongodb.sh:
sudo nano /usr/local/bin/backup_mongodb.sh
Insert the following code, replacing the placeholders with your values:
#!/bin/bash
# MongoDB Parameters
MONGO_USER="mongoAdmin"
MONGO_PASS="YOUR_ADMIN_PASSWORD" # In production, it's better to use .env or environment variables
MONGO_AUTH_DB="admin"
MONGO_HOST="127.0.0.1" # Or IP from which access is allowed
MONGO_PORT="27017"
# Backup Parameters
BACKUP_DIR="/var/backups/mongodb_tmp"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
LOG_FILE="/var/log/mongodb_backup.log"
# Restic Parameters
# IMPORTANT: Instead of directly specifying the password, use the RESTIC_PASSWORD environment variable
# or a password file protected by permissions.
# export RESTIC_PASSWORD="YOUR_RESTIC_PASSWORD"
RESTIC_REPO="s3:s3.amazonaws.com/YOUR_S3_BUCKET/mongodb_backups" # S3 example. Can be minio, B2, SFTP, etc.
# export AWS_ACCESS_KEY_ID="YOUR_AWS_KEY_ID"
# export AWS_SECRET_ACCESS_KEY="YOUR_AWS_SECRET_KEY"
# Create temporary directory for dump
mkdir -p $BACKUP_DIR/$TIMESTAMP || { echo "Failed to create directory $BACKUP_DIR/$TIMESTAMP" >> $LOG_FILE; exit 1; }
echo "[$TIMESTAMP] MongoDB backup started..." >> $LOG_FILE
# Create MongoDB dump
mongodump --host $MONGO_HOST --port $MONGO_PORT --authenticationDatabase $MONGO_AUTH_DB \
-u $MONGO_USER -p "$MONGO_PASS" --out $BACKUP_DIR/$TIMESTAMP >> $LOG_FILE 2>&1
if [ $? -ne 0 ]; then
echo "[$TIMESTAMP] Error creating MongoDB dump." >> $LOG_FILE
rm -rf $BACKUP_DIR/$TIMESTAMP # Delete failed dump
exit 1
fi
echo "[$TIMESTAMP] MongoDB dump successfully created. Size: $(du -sh $BACKUP_DIR/$TIMESTAMP | awk '{print $1}')" >> $LOG_FILE
# Initialize restic repository if it doesn't exist yet
# restic init --repo $RESTIC_REPO # Execute manually once
# Create backup using restic
echo "[$TIMESTAMP] Uploading backup to Restic repository..." >> $LOG_FILE
restic backup $BACKUP_DIR/$TIMESTAMP \
--repo $RESTIC_REPO \
--host $(hostname) \
--tag "mongodb-daily" \
--verbose >> $LOG_FILE 2>&1
if [ $? -ne 0 ]; then
echo "[$TIMESTAMP] Error uploading Restic backup." >> $LOG_FILE
exit 1
fi
echo "[$TIMESTAMP] Restic backup successfully completed." >> $LOG_FILE
# Clean up old snapshots (retention policy)
echo "[$TIMESTAMP] Cleaning up old backups (keep-daily 7, keep-weekly 4, keep-monthly 6)..." >> $LOG_FILE
restic forget --repo $RESTIC_REPO \
--prune \
--tag "mongodb-daily" \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6 \
--verbose >> $LOG_FILE 2>&1
if [ $? -ne 0 ]; then
echo "[$TIMESTAMP] Error cleaning up old Restic backups." >> $LOG_FILE
exit 1
fi
echo "[$TIMESTAMP] Old backups cleanup completed." >> $LOG_FILE
# Delete temporary dump files
rm -rf $BACKUP_DIR/$TIMESTAMP
echo "[$TIMESTAMP] Temporary directory $BACKUP_DIR/$TIMESTAMP deleted." >> $LOG_FILE
echo "[$TIMESTAMP] Backup completed. Checking repository:" >> $LOG_FILE
restic check --repo $RESTIC_REPO >> $LOG_FILE 2>&1
if [ $? -ne 0 ]; then
echo "[$TIMESTAMP] Error checking Restic repository." >> $LOG_FILE
exit 1
fi
echo "[$TIMESTAMP] Restic repository checked." >> $LOG_FILE
Make the script executable:
sudo chmod +x /usr/local/bin/backup_mongodb.sh
Initializing the Restic Repository
Before using the script for the first time, you need to initialize the restic repository. Make sure you have configured environment variables for S3 access (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) and the RESTIC_PASSWORD variable.
# Set environment variables for the current session
export AWS_ACCESS_KEY_ID="YOUR_AWS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="YOUR_AWS_SECRET_KEY"
export RESTIC_PASSWORD="YOUR_RESTIC_PASSWORD"
# Initialize repository (execute ONCE)
restic init --repo s3:s3.amazonaws.com/YOUR_S3_BUCKET/mongodb_backups
If you are using a different repository type (e.g., SFTP), replace s3:s3.amazonaws.com/... with the appropriate path.
3. Where to Store Backups
Never store backups on the same server as the original data. In case of server failure, you will lose both your data and your backups.
External S3-compatible service: Cloud storage services like Amazon S3, DigitalOcean Spaces, Backblaze B2, or MinIO on your own server, are excellent choices. They are reliable, scalable, and relatively inexpensive.
Separate VPS: You can set up a second, less powerful VPS exclusively for storing backups.
Remote SFTP server: If you have access to another server via SFTP, restic supports this protocol.
4. Configuring Cron for Automatic Backup Execution
To have the script run automatically, add it to the cron schedule.
sudo crontab -e
Add the following line for a daily backup at 03:00 AM. Make sure that the environment variables for restic are available in the context of the cron job. It is best to define them within the script itself or in a separate file that the script will "source".
This entry will run the script daily at 3 AM and redirect all output to the /var/log/mongodb_backup_cron.log file.
5. Updates: rolling vs maintenance window
OS Updates: Regularly run sudo apt update && sudo apt upgrade -y. For production servers, it is recommended to perform updates within a predefined maintenance window to minimize risks.
MongoDB Updates: Updating MongoDB itself (e.g., from 7.0 to 8.0) requires careful planning and testing. For a single node on a VPS, this usually means stopping the service (maintenance window). For clusters (replica sets), rolling upgrades are possible without downtime, but this is beyond the scope of this guide. Always refer to the official MongoDB documentation for updating your specific version.
Troubleshooting + FAQ
Even with careful configuration, problems can arise. This section will help you diagnose and resolve the most common ones.
MongoDB Does Not Start or Is Unavailable
Problem: After a server reboot or configuration change, MongoDB does not start, or you cannot connect to it.
What to check:
Service Status:sudo systemctl status mongod. Look for errors in the output, such as failed or exited.
MongoDB Logs:sudo tail -f /var/log/mongodb/mongod.log. This will show detailed error messages during startup or operation.
Configuration File:sudo nano /etc/mongod.conf. Check YAML syntax, especially indentation. Incorrect bindIp or errors in the security/net.ssl section are common causes.
File Access: Ensure that the mongodb user has read/write permissions for /var/lib/mongodb and /var/log/mongodb, as well as read permissions for /etc/mongod.conf and TLS certificates.
Port Occupied:sudo netstat -tuln | grep 27017. Ensure that no other process is occupying port 27017.
How to fix: Correct errors in mongod.conf, check access rights (sudo chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb), then try restarting the service: sudo systemctl restart mongod.
"Authentication failed" Error
Problem: You are trying to connect to MongoDB but receive an "Authentication failed" error.
What to check:
Username and Password: Ensure you are using the correct credentials.
Authentication Database: Ensure you specify the correct database for authentication (e.g., --authenticationDatabase admin for an administrative user).
Is Authentication Enabled: Check that security.authorization: enabled is present in /etc/mongod.conf. If not, enable it, restart MongoDB, and create a user.
How to fix: Double-check your credentials. If you forgot the administrator password, see the FAQ below.
What is the minimum VPS configuration suitable for MongoDB?
For basic tasks such as development, small personal projects, or test environments, a VPS with 2 CPU cores, 4 GB of RAM, and a 50 GB NVMe SSD will be minimally sufficient. However, for any production environment, even with a light load, it is highly recommended to have at least 4 CPU cores, 8 GB of RAM, and a 160 GB NVMe SSD. This will ensure stable operation and sufficient performance for data caching and query processing.
What to choose — VPS or dedicated for this task?
The choice between a VPS and a dedicated server depends on your project's scale, performance requirements, security needs, and budget. A VPS is excellent for most medium-sized projects requiring flexibility, scalability, and cost-effectiveness. It is ideal for startups, small SaaS applications, game servers for a small group of users, or cryptocurrency nodes that do not require extreme performance. A dedicated server is necessary for high-load systems, large data volumes (terabytes), mission-critical applications with high IOPS requirements, or if you need complete isolation and maximum control over hardware. If your project is actively growing and hitting VPS limits, transitioning to a dedicated server would be a logical step.
How to reset the MongoDB administrator password?
If you forgot the administrator password, you need to temporarily disable authentication. Edit /etc/mongod.conf, comment out or remove the line security.authorization: enabled. Restart MongoDB. Connect to mongosh without authentication, switch to the admin database, delete the old administrative user (or update their password), then create a new one. After that, restore security.authorization: enabled in the config and restart MongoDB.
Why does MongoDB consume so much RAM?
MongoDB actively uses RAM for data caching (via the WiredTiger engine). This is normal behavior, designed to improve performance, as reading data from RAM is significantly faster than from disk. If you see MongoDB consuming a lot of RAM, it is often a good sign, indicating efficient caching. However, if the system starts using swap, it is a sign of insufficient RAM, and you should consider increasing memory capacity.
Is replication necessary for a single node on a VPS?
For a single node on a VPS, replication in the classic sense (creating multiple copies of data on different servers) does not make sense, as there are no other servers. However, you can configure a "single-node replica set." This is necessary if you plan to use certain MongoDB features, such as transactions or Change Streams, which require a replica set to function. For a basic installation without these specific requirements, a single-node replica set is not mandatory but also won't hurt.
How to restrict MongoDB access to only my application?
This is achieved through two key steps:
Configure bindIp in /etc/mongod.conf: Specify the specific IP address of your application (or multiple IP addresses) from which connections are allowed. If the application is on the same server, use 127.0.0.1.
Configure Firewall (UFW): Allow incoming connections to port 27017 only from your application's IP address: sudo ufw allow from YOUR_APPLICATION_IP to any port 27017. This will provide network-level protection.
MongoDB does not start after server reboot. What to do?
Database Corruption: Sometimes, due to improper shutdown or lack of disk space, data can become corrupted. Try starting MongoDB with the --repair option (be careful, it can take a long time).
Insufficient Disk Space: Check df -h. If the disk is full, MongoDB will not be able to create new files or log entries.
Incorrect Permissions: Ensure that the mongodb user has full permissions for the /var/lib/mongodb and /var/log/mongodb directories.
Errors in mongod.conf: Incorrect syntax or invalid parameters can prevent startup.
If the problem is not resolved, recovery from the last working backup may be necessary.
Conclusion and Next Steps
Congratulations! You have successfully installed, configured, and secured a MongoDB 7.0 instance on your VPS running Ubuntu Server 24.04 LTS. You now have a reliable and performant database ready for integration with your applications. You have implemented basic but extremely important security measures, such as authentication, network access restriction via firewall, and, optionally, traffic encryption using TLS/SSL. You have also configured automatic backups, which is a cornerstone of any production system.
Further steps for optimizing and scaling your MongoDB installation may include:
Performance Monitoring: Integrate MongoDB with monitoring systems such as Prometheus and Grafana to track performance metrics, resource utilization, and database status in real-time.
Query Optimization and Indexing: Analyze slow queries and create appropriate indexes to improve the speed of read operations in your database.
Replication and Sharding: As your application grows and load increases, consider configuring replication to ensure high availability and fault tolerance, and sharding for horizontal scaling and distributing data across multiple servers.
Was this guide helpful?
Your feedback helps us improve our guides.
Share this post:
Send this guide to someone who may find it useful.