How to Configure Iptables to Act as a Firewall for your MongoDB Server
Learn how to use the GNU/Linux bundled firewall — iptables — to protect your MongoDB server and only allow connections from your application servers.
First of all, you need to identify the public IP address of all your application servers.
You will also need to know which port your mongod listens at. You can log into the server where mongod is located and figure it out using the following command:
$ grep port: /etc/mongod.conf
port: <your current port>
Then, create the/etc/mongo.firewall.rules
file and make sure it contains the following lines:
*filter-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT# Repeat these following two lines for each of your app servers
-A INPUT -s <ip-address> -p tcp --destination-port <mongod-port> -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -d <ip-address> -p tcp --source-port <mongod-port> -m state --state ESTABLISHED -j ACCEPT-A INPUT -j DROP
-A FORWARD -j DROP
COMMIT
Then save to disk and run the following command to apply the rules immediately as well as for persisting them after reboot:
# f="/etc/network/if-up.d/mongo-iptables"; echo "#/bin/bash
iptables-restore < /etc/mongo.firewall.rules
" > $f && chmod +x $f && $f
If you usually run your app in your own computer for testing or development purposes, you may also want to whitelist your home or office IP.