How to fix connection timeout problem with MongoDB

Some of us have encountered a problem problem right after installing MongoDB, turns out we can’t connect. I personally get this:

root@ghost:~# mongo
MongoDB shell version v4.2.8
connecting to: mongodb://
2020-10-30T12:10:51.955+0100 E QUERY [js] Error: couldn't connect to server, connection attempt fa iled: SocketException: Error connecting to :: caused by :: Connection timed out :
2020-10-30T12:10:51.958+0100 F - [main] exception: connect failed
2020-10-30T12:10:51.958+0100 E - [main] exiting with code 1

There are several reasons for that but here is one solution that might work if you are sure that you have started the service and you still can’t connect. The problem comes from the “firewall” which is blocking the connections, these two commands configure the firewall via IP tables to accept MongoDB traffic.

iptables -A INPUT -p tcp --dport 27017 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 27017 -m conntrack --ctstate ESTABLISHED -j ACCEPT

Hope it helps.


Leave a Comment

Your email address will not be published. Required fields are marked *