Follow up of Econnrefused ::1:27017

I post here as a follow up of Econnrefused ::1:27017 as it is no longer possible to post replies there.

When connecting to mongodb with MongoClient i get MongoServerSelectionError: connect ECONNREFUSED ::1:27017 when connecting to ‘mongodb://localhost:27017/’ but no error when connecting to ‘mongodb://’.

As @Stennie mention the problem is that MongoClient tries to connect with IPv6. It didn’t seem to me it could be that because in my /etc/hosts file localhost is configured for both IPv4 and IPv6: localhost broadcasthost
::1             localhost

But with that configuration it seems that localhost will randomly redirect to IPv4 or v6, so the solution is to remove the line for IPv6.

1 Like

in hosts file, you can assign multiple names to a single IP, but assigning multiple IPs to a single name can be chaotic. in the case of multiple IP addresses, the first occurrence will be used. And in case you have both IPv4 and IPv6 assigned to the same name, a host OS with IPv6 enabled will use the first IPv6 address while the one with only IPv4 will use the first IPv4 address.

In my case it is just the call of MongoClient inside a node instance, so not sure if that means that the host is IPv6 or IPv4, and the /etc/hosts file with multiple assignations for localhost is the one which came with my Mac.

The most disturbing part is that after I boot my Mac it will use IPv4, and after some usage it will start to use IPv6…

I saw some posts noting that Mac chooses the faster one with the network you use but fails to switch to IPv4 if it decides to go with IPv6. I guess this is what happened in your case. I don’t own a Mac so I can’t say if this is bad as it sounds or has its advantages.

This solution you have provided works for sure since you force name resolution to go for IPv4. Nice to have it. an alternative is suggested in the other discussion you started to bind mongod to both IPv4 and IPv6. have you tried to start your server that way instead of changing hosts file?

Yes configuring mongod.conf (in my case /usr/local/etc/mongod.conf) with

  ipv6: true
  bindIp: ",::1"

is an alternative solution to fix the issue.

1 Like