Connection refused for remote access of mongodb server

Hello! I’m a newcomer to MongoDB and it’s a great product. I have set up a mongo server on my local desktop machine (running Ubuntu 20.04), and I can connect to it without any issue on that machine. However, when I try to connect from my laptop, it shows this error:

connecting to: mongodb://<my ip address>:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server <my ip address>:27017, connection attempt failed: SocketException: Error connecting to <my ip address>:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:372:17
@(connect):2:6
exception: connect failed
exiting with code 1

I have followed many suggestions by others (for example here) but none of them works. I’m wondering what could have gone wrong?

Edit: I checked the connection using telnet:

nc -vz <my ip address> 27017

and it gives:

nc: connectx to <my ip address> port 27017 (tcp) failed: Connection refused

However, checking on my desktop machine reveals that the firewall on port 27017 is open:

(base) exen@jingyang:~$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
27017                      ALLOW IN    Anywhere                  
22                         ALLOW IN    Anywhere                         
27017 (v6)                 ALLOW IN    Anywhere (v6)             
22 (v6)                    ALLOW IN    Anywhere (v6)

Hey @Jingyang_Wang,

Welcome to the MongoDB Community!

By default, MongoDB binds to a localhost IP address. In the post, you mentioned <my ip address>. Could you clarify what this address is? Is this address 127.0.0.1, or some other address? Is it accessible from outside the node?

Based on the details you provided, it seems the issue is that the MongoDB server is only listening for connections on the local interface and not on your public IP address.

May I ask what steps you followed to install MongoDB?

Moreover, a few things to check:

  • In the MongoDB config file (usually /etc/mongod.conf), make sure the bindIp have the IP address of your other system or set to 0.0.0.0 to bind to all available IP addresses.
  • Restart the MongoDB service after making any config changes.
  • Verify the MongoDB process is actually listening on the public IP by running netstat -an | grep 27017 on the server. You should see it listening on 0.0.0.0:27017 or the public IP.

If the issue still persists, some other things to check would be the network/firewall configuration on the server, making sure the public IP is certainly assigned to the server, or checking for any other processes that may be blocking port 27017.

Please note 0.0.0.0 is not recommended for your production environment as it allows access from anywhere.

Hope the above helps!

Regards,
Kushagra

2 Likes