So I have been scratching my head on this for a while but did not find any solution anywhere. I’m running a node v18 express application on docker and I’m trying to connect to mongodb that is running on my host machine and not in the docker container. I was able to connect to redis and memcached in similar way using host.docker.internal. Redis and memcached also running on host machine and not on the container.
I thought it was issue from mondb node version, so I updated it from node 12 to node 18 after wards, but still the issue persisted.
But I could not understand why it is always trying to connect to 127.0.0.1 when I passed a different IP as well.
Chances are you configured your replica set with the hosts pointing to 127.0.0.1. As a result, once you connect using a connection string such as mongodb://buyucoinUser:Pass123@192.168.29.160:27017/buyucoin_stagin?ssl=false&replicaSet=rs0 the first thing that will happen is the driver will attempt to discover the replica set and will get a list of hosts back using those “internal” hosts/IPs - not what you passed in the connection string.
The easiest way to validate this is to connect to the replica set using the mongosh shell and run rs.status()
As an example, let’s say you have 3 members on ports 27017, 27018 and 27019. If you wanted to configure the replica set to map these nodes to those ports on IP address 192.168.29.160, from the mongosh shell you would do the following:
var c = rs.config();
c.members.host = "192.168.29.160:27017";
c.members.host = "192.168.29.160:27018";
c.members.host = "192.168.29.160:27019";
Once the replica set is reconfigured, when your application connects next it will discover the replica set members and try to connect to them on the host/port pairs that you configured above.
So I used 192.168.29.160 because this is the IP on which my macbook is available on the local wifi. So I tried the same thing without using docker and I was able to connect to the mongo without any issue, but if I try to connect to mongo of host machine from docker container, then this issue persists
@Devesh_Aggrawal you may need to update the IP Binding info for your mongod. For example, starting a node with mongod --port 27017 ... will only bind to localhost and listen on port 27017.
Using mongod --port 27017 --bind_ip_all will bind to all IPv4/v6 addresses. For local testing this may be the easiest way to get this sorted out, but if you’re managing a production cluster I’d recommend configuring your IP bindings a bit more restrictively
@Devesh_Aggrawal this is not a MongoDB question, but a question of configuring Docker networks. I’ll let someone else weigh in but it sounds like you may need to setup a bridge network to ensure you can access your local network from the docker network layer.
Not by forte, and it sounds like the default bridge should work as you expect so I’ll defer to someone else.