MongoDB Security Best Practices for Self-Hosted Servers
In this article
Securing a self-hosted MongoDB server means protecting your data from unauthorized access, theft, and corruption by following a set of proven configuration and operational practices. You start with network isolation and authentication, then layer on encryption, access control, and ongoing monitoring. This article details the essential steps every self-hosted MongoDB administrator should implement.
Why Self-Hosted MongoDB Needs Extra Care
When you use MongoDB Atlas, the vendor handles many security tasks automatically. But with a self-hosted deployment, you are responsible for every layer: the operating system, the network, the MongoDB configuration, and the data itself. A default MongoDB installation is not secure out of the box—it listens on all interfaces, has no authentication enabled, and binds to port 27017. Attackers constantly scan for such exposed instances, and a single misstep can lead to ransomware or data theft. The core principle is defense in depth: no single control is enough, but together they make exploitation significantly harder.
Network and Binding Configuration
The first and most critical step is to ensure MongoDB only listens on trusted interfaces. By default, older versions bound to 0.0.0.0, exposing the database to the internet. Modern best practice is to bind to localhost (127.0.0.1) or a private network IP, and to place MongoDB behind a firewall or a VPN.
- Set bindIp in mongod.conf to 127.0.0.1 if the application runs on the same host, or to a private IP like 10.0.0.5 if clients are on a private network. Never use 0.0.0.0.
- Use a firewall (iptables, ufw, or cloud security groups) to restrict access to port 27017 only from known application servers.
- Avoid exposing MongoDB directly to the internet. If remote access is required, use an SSH tunnel, a VPN, or a reverse proxy with TLS termination.
- Consider running MongoDB inside a Docker container with published ports limited to specific interfaces, not 0.0.0.0.
Authentication and Authorization
MongoDB supports several authentication mechanisms. The most common for self-hosted deployments is SCRAM (Salted Challenge Response Authentication Mechanism), which is enabled by default in recent versions. You must create a user with the root role in the admin database, then restart MongoDB with --auth or set security.authorization: enabled in the config file.
After enabling authentication, create least-privilege users for each application. For example, an application only needs readWrite on its own database, not root. Use roles like read, readWrite, or custom roles. Avoid using the same credentials across environments, and rotate passwords periodically.
If you use X.509 certificates for authentication, ensure the CA and certificates are stored securely and that the certificate revocation list is maintained.
Encryption of Data
Encryption protects data both in transit and at rest. For data in transit, enable TLS/SSL on all connections. This requires a valid certificate (from a CA or self-signed for internal use) and configuring net.tls.mode: requireTLS in mongod.conf. All clients must connect using mongodb:// or mongodb+srv:// with TLS enabled.
For data at rest, MongoDB Enterprise offers native encryption, but the community edition does not. For community deployments, you can use full-disk encryption at the OS level (e.g., LUKS on Linux, BitLocker on Windows) or filesystem-level encryption. Encrypt the entire disk or the data directory to protect against physical theft of the server.
Operating System Hardening
A secure MongoDB server starts with a secure OS. Keep the operating system and MongoDB itself updated with the latest security patches. Disable unnecessary services and close unused ports. Run MongoDB under a dedicated, non-root user account with minimal privileges. The MongoDB process should only have read/write access to its data directory and log files, and nothing else.
Set strong file permissions on the MongoDB configuration file (mongod.conf) and on the data directory. The config file often contains sensitive settings like authentication keys or TLS certificate paths. Use chmod 600 on the config file and ensure the data directory is owned by the MongoDB user.
Consider using AppArmor or SELinux to confine the MongoDB process further, if your OS supports it.
Auditing and Monitoring
You cannot secure what you cannot see. Enable MongoDB's auditing facility (available in MongoDB Enterprise) to log all authentication attempts, schema changes, and data modifications. For community edition, enable verbose logging and use system-level monitoring tools like mongostat and mongotop to watch for unusual activity.
Set up log rotation and centralize logs using tools like the ELK stack or a simple syslog server. Monitor for failed login attempts, which could indicate a brute-force attack. Use the db.currentOp() command to inspect running operations and kill any suspicious queries.
Regularly review the MongoDB log file for errors or warnings that might indicate an intrusion attempt. Also, consider using a database activity monitoring (DAM) tool if your compliance requirements demand it.
Backup and Disaster Recovery
Security also includes being able to recover from a breach or data loss. Implement regular backups using mongodump or filesystem snapshots. Store backups offsite and encrypt them. Test your restore procedure periodically to ensure backups are valid.
For high availability, use a replica set with at least three members. This provides automatic failover and protects against a single server failure. Ensure that replica set members communicate over a private network and that all connections use TLS. Also, set security.keyFile to authenticate internal replica set communication.
Frequently Asked Questions
Is MongoDB secure by default?
No, MongoDB is not secure by default. Older versions had no authentication enabled and listened on all interfaces. Modern versions (4.2 and later) enable authentication by default, but you still must bind to a safe interface and create users. Always check your configuration after installation.
Should I use MongoDB Atlas instead of self-hosting?
MongoDB Atlas provides built-in security features like encryption at rest, IP whitelisting, and automated backups, which reduces the administrative burden. Self-hosting gives you full control and can be cheaper for large deployments, but requires you to implement and maintain all security measures yourself. Choose based on your team's expertise and compliance needs.
How do I enable authentication on an existing MongoDB instance?
First, create a user with the root role in the admin database. Then edit mongod.conf to add security: authorization: enabled. Restart the mongod service. After that, all connections must provide credentials. Ensure you have a valid user before enabling to avoid being locked out.
What is the difference between SCRAM and LDAP authentication?
SCRAM is MongoDB's built-in username/password authentication, storing credentials in the database itself. LDAP authentication integrates with an external directory service (like Active Directory) to validate users. LDAP is useful for centralized user management but requires additional configuration and is only available in MongoDB Enterprise.
Can I use a self-signed certificate for TLS?
Yes, you can use a self-signed certificate for internal testing, but production should use a certificate from a trusted CA. If you use self-signed, you must configure each client to trust that specific certificate, which can be cumbersome. For internal networks, a private CA is a good compromise.
What should I do if I suspect my MongoDB has been compromised?
Immediately isolate the server from the network, take a forensic snapshot of the disk, and change all credentials. Check the logs for unauthorized access, review user accounts, and restore from a clean backup. After the incident, audit your security configuration and apply missing patches.