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://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-10-30T12:10:51.955+0100 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt fa iled: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection timed out :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
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.

Sources:

Leave a Comment

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