How to Configure Firewall, Whitelist and Blacklist in a self-hosted MongoDB server
This how-to guide only applies to self-managed or self-hosted MongoDB servers. If you are using a cloud “MongoDB as a service” provider (Mlab, Compose, Atlas, etc., please look for your provider in this other how-to.
Set the bind IP properly
By default, mongod binds only to the local interface ( 127.0.0.1
) and ignores remote connections. This is completely fine in case that your application’s backend is hosted in the same server as mongod. If that’s your case, don’t touch anything and sleep well at night.
How to allow connections from remote application servers
If your application’s backend happens to be hosted in a separate machine, you will need to tell mongod to bind to some external interface.
Let’s open /etc/mongod.conf
and search for the following lines:
net:
port: <port>
bindIp: 127.0.0.1
If you can’t find
mongod.conf
or it is namedmongodb.conf
instead, it means that you are using a really old and broken version of MongoDB. Please read this guide on how to upgrade to a more recent version.)
You may be tempted to put bindIp: 0.0.0.0
— NEVER, EVER DO THAT. Seriously, that means binding to your public IP and potentially exposing your server to the whole world. Even though you correctly set up Authentication, MongoDB leaks way too much information to unauthenticated connections. Once more, bindIp: 0.0.0.0
is pure evil.
As a rule of thumb, you should always bind to the address belonging to the most local or private network that connects your database and application servers.
Let’s look at this diagram:
In this case, the most reasonable bind IP will be the one belonging to the LAN ( 192.168.0.101
). This way, connections from the app servers will be allowed but the database will not be accesible from the Internet:
bindIp: 127.0.0.1, 192.168.0.101
What if my application server is in a completely different network?
Although not recommendable, it is common to host your applications in a different network than your databases. If that’s your case, you have two options:
- Configure the
iptables
firewall to only allow connections from your application server and ONLY THEN tell mongod to bind to the public IP. - Create a VPN or tunnel between your application and database servers; then tell mongod to bind to the VPN’s IP.