Sushin Pv
Sushin Pv

Reputation: 1894

Unable to connect to mongodb replicaset Google Compute Engine

I have created a 3 node replicaSet for mongodb on google compute engine, for the testing purpose i have added 0.0.0.0/0 for the firewall rule and I'm able to connect to individual node from anywhere and all the instances work without any issue! but the problem is when i tried to connect to the replicaset, using the following command

mongo "mongodb://username:password@public-ip-1:27017,public-ip-2:27017,public-ip-3:27017/production?replicaSet=rs0"
  1. When I'm trying this code another instance on the same project, it work's without any issue
  2. When I try from a different project instance or my local instance, it is throwing error as follow

2020-08-22T14:36:40.579+0530 I NETWORK [thread1] getaddrinfo("mongodb-1-servers-vm-0") failed: nodename nor servname provided, or not known 2020-08-22T14:36:40.582+0530 I NETWORK [thread1] getaddrinfo("mongodb-1-servers-vm-1") failed: nodename nor servname provided, or not known 2020-08-22T14:36:40.582+0530 W NETWORK [thread1] Unable to reach primary for set rs0

and from these instance I'm able to connect to individual nodes separately, as

mongo "mongodb://username:passsword@public-ip-1:27017/production"
mongo "mongodb://username:passsword@public-ip-2:27017/production"
mongo "mongodb://username:passsword@public-ip-3:27017/production"

What could be the problem ?

The second question is, on the firewall these is an option to add app engine service account? so if i disable the 0.0.0.0/0 public access and add this rule, can i connect from my app engine to these instance ?

Upvotes: 0

Views: 503

Answers (1)

Joe
Joe

Reputation: 28326

When connecting to a replica set, the client uses a server discovery process. The basic steps are:

  1. connect to the first host in the connection string
    • if that fails try the second
  2. once a connection is established, run commands such isMaster to:
    • discover the names of all of the replica set members
    • discover which node is currently primary
  3. close the initial connection
  4. connect to every member of the replica set using the hostname and port discovered in step 2

What this means is that the host name returned from rs.conf() or rs.status() must be resolvable by every client that you want to be able to directly connect to the replica set.

From the error message, it looks like the nodes were added to the replica set using short names. If you add the short name for each node to the hosts file on the machine you are connection from, it should work.

Alternately, rebuild the replica set using publicly resolvable hostnames in the rs.initiate and rs.add commands.

Upvotes: 2

Related Questions