0

I want to connect to a remote Mongodb server. And in the process I get the error

selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: <addr>:<port>, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp <addr>:<port>: i/o timeout }, ] }

This is my code,

func Connect() {
 client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://server_addr:port").
    SetAuth(options.Credential{
        AuthSource: "db_name", Username: "user", Password: "password",
      }))

  ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  defer cancel()
  err = client.Connect(ctx)

  //ping db
  err = client.Ping(ctx, readpref.Primary())

  if err != nil {
    log.Fatal("Error while connecting db ", err)
  }

  log.Println("Connected\n")
}

In the etc/mongod.conf file, I've entered

bindIpAll: true

And to allow port through firewall

sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent

but I still can't understand what is causing the error. I'm still new so It'll be really helpful if you could help me understand. Thanks!

RandomUser
  • 93
  • 1
  • 8
  • Are you able to `telnet` your server on port 27017? Can you also check what's the output of `netstat -tulpn | grep 27017` on your server? – Jay May 06 '20 at 15:31
  • @Jay the output of `netstat -tulpn | grep 27017` is `tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN`. And no, on telnet it shows error `Could not open connection to the host, on port 27017: Connect failed` – RandomUser May 06 '20 at 15:43
  • 1
    You may want to check your iptables again... Seems like the port is still not allowed to accept incoming connections on the server. – Jay May 06 '20 at 16:26
  • @RandomUser, could you tell us more about the MongoDB server ? is it running on a separate machine? Is it a replica set ? can you connect to it using `mongo` shell ? – Wan B. May 07 '20 at 04:14
  • Turns out refreshing iptables and firewalld fixed the error. Though I did it earlier, not sure why it was to be done again. Thanks a lot for the help – RandomUser May 07 '20 at 14:46

0 Answers0