How to connect to MongoDB via SSH tunneling
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:
AllowTCPForwardingis either not present, is commented out, or is set toyesPermitOpenis either not present, is commented out, or is set toany[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!
