Search code examples
mongodbkubernetesmongo-shell

Timeout while connecting to mongodb instance from kubernetes pod


I set up a Kubernetes Cluster on Hetzner following theses steps: https://github.com/kube-hetzner/terraform-hcloud-kube-hetzner

Client Version: v1.26.3
Kustomize Version: v4.5.7
Server Version: v1.26.4+k3s1
Mongosh Version: 1.8.1

I am unable to connect to either my own mongodb server (docker deployment) or a hosted one on mongodb.net:

root@trustsigner-frontend-deployment-59644b6b55-pqgmm:/usr/share/nginx/html# mongosh mongodb+srv://<removed-user>:<removed-password>@cluster0.fdofntt.mongodb.net/test
Current Mongosh Log ID: 6447807561ebcee04b00165d
Connecting to:          mongodb+srv://<credentials>@cluster0.fdofntt.mongodb.net/test?appName=mongosh+1.8.1
MongoServerSelectionError: Server selection timed out after 30000 ms

Same error when using my own one with mongodb:// instead of mongodb+srv//.

But surprisingly it is possible to use the same connection string with mongodb compass or mongosh that is installed on my machine (not in a kubernetes pod)

Ping to 8.8.8.8 or to any other side works and I can fetch via curl. But no chance to establish a mongodb connection...


Solution

  • Experiencing the same issue while using kube-hetzner as you, I looked at the configuration file and found the culprit: by default, outbound traffic is filtered, except for a few popular ports like HTTP or HTTPS.

    There are at least 2 solutions:

    1. you set the variable restrict_outbound_traffic to false: https://github.com/kube-hetzner/terraform-hcloud-kube-hetzner/blob/master/kube.tf.example#L395

    2. You add a firewall rule to allow outbound traffic on port 27017.

    Once done, the connection to a Mongo Atlas cluster is working perfectly!