Lord Grosse Jeanine
Lord Grosse Jeanine

Reputation: 1131

Allow MongoDB remote access for specific IP

I have an application server with some PHP code on it which needs to access a distant MongoDB server. In order to do this I want to allow remote access on my MongoDB server, but only for the application server IP. I understand that I need to change the bind_ip value located in /etc/mongodb.conf in order to do this. I changed it from bind_ip=127.0.0.1 to bind_ip=111.222.33.44 (where 111.222.33.44 is my application server IP), but it doesn't work (my PHP code says "Connection refused"). However, if I set the value to bind_ip=0.0.0.0, it works. Why? I don't want to let anyone try to connect on my MongoDB server.

Upvotes: 2

Views: 6085

Answers (2)

Ohad Cohen
Ohad Cohen

Reputation: 6144

As far as I see mongodb only allow you to set a single IP for connection (or 0.0.0.0 for any IP)

What you can do to secure your mongo instance is to use firewall like iptables to only allow specific IP's.

Run the following commands for every IP you want to allow:

iptables -A INPUT -s 111.222.33.44 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 111.222.33.44 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

and than to block all else (blocked some other ports used by mongodb)

iptables -A INPUT -p tcp --dport 27017 -j DROP
iptables -A INPUT -p tcp --dport 27018 -j DROP
iptables -A INPUT -p tcp --dport 27019 -j DROP

have a look at the Make iptables Rules Persistent section of the mongo guide on how to make those rules survive reboot.

Upvotes: 1

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

The bind_ip tells the mongod on which IP address to listen on for incoming connections. So if you set it to 127.0.0.1, the mongod would only listen on localhost, and – vice versa – you could only connect when on the same machine.

When setting it to a different IP address, each host able to communicate with said IP can connect to MongoDB.

In order to make sure only your application server can talk to your MongoDB instance, you need to configure a firewall either on the server running MongoDB or somewhere in front of it.

Upvotes: 2

Related Questions