Search code examples
ruby-on-railsmongodbreplicationmongodb-replica-set

MongoDB 5.0 Replication: Mongo::Error::NoServerAvailable


I would like to know how to fix the following error when enabling replication on MongoDB: <Server address=db-master:27017 UNKNOWN> It only happens when enabling replication.

Error

Mongo::Error::NoServerAvailable (No nearest server is available in cluster: #<Cluster topology=ReplicaSetNoPrimary[db-master:27017,db-node2:27017,db-node1:27017,name=rs0,v=6,e=7fffffff0000000000000017] 
servers=[#<Server address=db-master:27017 UNKNOWN>,#<Server address=db-node2:27017 UNKNOWN>,#<Server address=db-node1:27017 UNKNOWN>]> with timeout=30, LT=0.015)

Is this issue due to DNS resolution? Is there a way to specify the IP address instead of the alias (from hosts file) to the cluster topology? When ssh'ing to the primary and secondary nodes pinging seems to work.

[db-node2 server] $ ping db-master
PING db-master ([IP_IS_HERE]) 56(84) bytes of data.
64 bytes from db-master ([IP_IS_HERE]): icmp_seq=1 ttl=63 time=0.153 ms
64 bytes from db-master ([IP_IS_HERE]): icmp_seq=2 ttl=63 time=0.150 m

mongo.conf

net:
  port: 27017
  bindIp: 0.0.0.0,localhost,127.0.0.1,db-master,[IP_IS_HERE]
  bindIpAll: true
replication:
  replSetName: "rs0"

ubuntu hosts

$ cat /etc/hosts
127.0.0.1 localhost
[IP_IS_HERE] db-master
[IP_IS_HERE] db-node1
[IP_IS_HERE] db-node2

Solution

  • Did you start the mongod service on the other hosts?

    Your config does not make much sense. If you want to permit connection from any host, then use

    net:
      port: 27017
      bindIpAll: true
    

    or

    net:
      port: 27017
      bindIp: 0.0.0.0
    

    If you want to limit the connection from specific host then use

    net:
      port: 27017
      bindIp: localhost,db-master,[IP_IS_HERE]
    

    ssh uses port 22 but your MongoDB uses port 27017, so your firewall may block the connection (the same applies for ping). If you like to check whether connection is available you can use curl command:

    curl --connect-timeout 3 --silent --show-error db-node1:27017
    

    If you get as response

    It looks like you are trying to access MongoDB over HTTP on the native driver port.

    then connection is possible.

    An response of

    Connection timed out after 3000 milliseconds

    indicates that your firewall blocks the connection attempt.