This guide walks you through securing a MongoDB instance on a virtual private server (VPS). It covers network isolation, authentication, encryption, and file system permissions, turning a default installation into a production-ready database. You’ll need root or sudo access to your VPS and basic familiarity with the command line.
What You’ll Need
- A VPS running a modern Linux distribution (Ubuntu 22.04/24.04, Debian 12, etc.)
- Root or sudo access to the server
- MongoDB installed (Community or Enterprise edition)
- An SSH client (like OpenSSH) to connect to your server
Step-by-Step
- Enable authentication in the config file. Edit
/etc/mongod.conf(or the path used by your installation). Under thesecuritysection, add:security: authorization: enabled
If the section doesn’t exist, create it. This forces MongoDB to require credentials for all connections.
- Create an administrative user. Start MongoDB without authentication temporarily (comment out the
securitysection or start with--noauth). Then connect with themongoshshell and create a user in theadmindatabase:use admin db.createUser({ user: "admin", pwd: "a-strong-password", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })Replace the password with a strong, unique one. Exit and restart MongoDB with authentication enabled.
- Bind to localhost or a private IP. By default, MongoDB binds to
127.0.0.1, which is safe. If you need remote access, change thenet.bindIpinmongod.confto a private IP (e.g.,10.0.0.1) or a comma-separated list. Never bind to0.0.0.0unless you have a firewall that restricts access. - Configure a firewall. Use UFW (on Ubuntu) or firewalld (on CentOS/RHEL) to allow only necessary ports. By default, MongoDB uses port 27017. If you only need local access, block it entirely:
sudo ufw default deny incoming sudo ufw allow ssh sudo ufw enable
If remote access is required, allow only your specific IP:
sudo ufw allow from your-ip to any port 27017
Never open the port to the world.
- Enable TLS/SSL for network encryption. Obtain a certificate (e.g., from Let’s Encrypt or your own CA). Add to
mongod.conf:net: tls: mode: requireTLS certificateKeyFile: /etc/ssl/mongodb.pemThe PEM file must contain both the certificate and the private key. Restart MongoDB. Clients must connect with
--tlsand--tlsCAFileif using a self-signed CA. - Set strict file permissions. MongoDB stores data in
/var/lib/mongodb(or your configured dbPath). Ensure it’s owned by themongodbuser and group, and not world-readable:sudo chown -R mongodb:mongodb /var/lib/mongodb sudo chmod 750 /var/lib/mongodb
Also protect the config file and key files (e.g.,
chmod 600for the TLS private key). - Disable the REST and HTTP interfaces. These are legacy and disabled by default in modern versions, but verify in
mongod.conf:net: http: enabled: false rest: enabled: falseIf these options are not present, they are off by default.
- Run MongoDB as a non-root user. The MongoDB service should run as the
mongodbuser, which it does by default when installed from official repositories. Verify withps aux | grep mongod– the process should showmongodbas the user. - Enable auditing (optional but recommended). Add to
mongod.conf:auditLog: destination: file format: JSON path: /var/log/mongodb/audit.json
This logs authentication attempts and other security events. Restart MongoDB and check the log.
- Keep MongoDB updated. Regularly run
sudo apt update && sudo apt upgrade(or your package manager’s equivalent) to apply security patches. Subscribe to MongoDB security advisories.
Common Mistakes
- Leaving authentication disabled. Many tutorials skip this, leaving the database open. Always enable
authorization. - Binding to 0.0.0.0. This exposes MongoDB to the internet. Even with authentication, it’s a risk – brute-force attacks are common.
- Using weak passwords. A short or common password can be cracked. Use a password manager to generate a long, random one.
- Ignoring the firewall. A firewall is your first line of defense. Even if you bind to localhost, a firewall adds depth.
- Forgetting to restart after config changes. Changes to
mongod.confonly take effect after a restart. Always usesudo systemctl restart mongod.
Tips
- Use a dedicated user for each application. Instead of using the admin user for everything, create application-specific users with only the privileges they need (e.g., readWrite on a specific database).
- Implement IP-based access control. In addition to the firewall, use MongoDB’s
net.ipv4ornet.ipv6settings to restrict which interfaces MongoDB listens on. - Back up your database regularly. Use
mongodumpor a filesystem snapshot. Store backups off-site or in a different location. - Monitor logs. Check
/var/log/mongodb/mongod.logfor unusual activity, such as failed authentication attempts. - Consider using a VPN. If you need remote access, a VPN (like WireGuard or OpenVPN) is safer than exposing MongoDB directly.
Troubleshooting
Authentication fails after enabling authorization. Verify that you created the user in the admin database and that you’re connecting to the correct database. Use mongosh -u admin -p --authenticationDatabase admin.
MongoDB won’t start after config changes. Check the error log at /var/log/mongodb/mongod.log. Common issues: incorrect YAML indentation (use spaces, not tabs), missing certificate files, or permission errors. Run sudo mongod --config /etc/mongod.conf --fork to see the error directly.
TLS handshake failures. Ensure the certificate file is readable by the mongodb user and that the private key is not encrypted (or you provide the passphrase). Verify the certificate chain is complete.
Can’t connect remotely. Check that the firewall allows the port and that MongoDB is bound to the correct IP. Test with telnet your-server-ip 27017 from your local machine. If it times out, the firewall is blocking.
Audit log not being written. Ensure the auditLog path is writable by the mongodb user. Create the file if necessary and set permissions: sudo touch /var/log/mongodb/audit.json && sudo chown mongodb:mongodb /var/log/mongodb/audit.json.
Frequently Asked Questions
Do I need to enable authentication if MongoDB is only on localhost?
Yes. Any process on the server (like a compromised web app) could connect without credentials. Authentication adds a necessary layer of defense.
What’s the difference between bindIp and the firewall?
bindIp tells MongoDB which network interfaces to listen on. The firewall controls which external IPs can reach those ports. Both are complementary; use both.
Can I use a self-signed certificate for TLS?
Yes, but clients will need to trust your CA. Use a self-signed certificate only for testing; for production, get a certificate from a public CA or use an internal CA.
How often should I update MongoDB?
As soon as security patches are released. Subscribe to MongoDB’s security announcements and test updates in a staging environment before applying to production.
Is it safe to expose MongoDB to the internet if I have a strong password?
No. Strong passwords reduce but don’t eliminate risk. Brute-force attacks, zero-day vulnerabilities, and misconfiguration make exposure risky. Always keep MongoDB behind a firewall or VPN.
What should I do if I suspect a breach?
Immediately disconnect the server from the network, review logs for unauthorized access, change all passwords, and restore from a clean backup. Consider a forensic analysis.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Car Trends Making Cars Worse: 7 Downsides
- Nostalgic Classic Games Revamped on G2A?
- Nvidia RTX 4000 Super GPUs: Full Specs & Buying Guide
- Photoshop vs Lightroom AI Features Compared
- DNF vs DNF5: Which Package Manager?
- Stop iTunes Web Links From Opening iTunes