Sitemap

How to connect to MongoDB via SSH tunneling

Nov 19, 2020

There are scenarios where your MongoDB is sitting behind a bastion host. ie, you may not have direct access to your MongoDB instance, but you have access to a server that can connect to your DB. In that case, you can use SSH tunneling to access your MongoDB.

It’s just a simple bash command if you are in Linux/mac,

ssh <username>@<address of your bastion host> -L <desired local MongoDB port>:<Address of MongoDB server>:<MongoDB port> -N

eg:

ssh admin@62.872.169.224 -L 27018:62.872.169.223:27017 -N

If you are not able to connect, you need to check the ssh config /etc/ssh/sshd_config. You should ensure that:

  • AllowTCPForwarding is either not present, is commented out, or is set to yes
  • PermitOpen is either not present, is commented out, or is set to any[1]

Additionally, if you are using an SSH key to connect, you should check that the entry corresponding to your SSH key in ~/.ssh/authorized_keys does not have no-port-forwarding or permitopen statements[2].

Cheers!

--

--

Alfred Francis
Alfred Francis

Written by Alfred Francis

Full Stack Dev. Python, Java, Go,Angular, React, AWS. Interested in Virtual Assistants and SaaS.

Responses (1)