SSH Tunneling Mongodb

I was taught an awesome new option for ssh the other day “-L”.

I use it to tunnel a connection to a mongodb over ssh like so.

ssh -L 27017:host_with_mongo_connection:27017 user@box_I_have_ssh_access_to

The first port number is the local port I want to listen on, and the second is the port on the remote box to connect to.

The box_i_have_ssh_access_to is a box that is publicly accessible to me via ssh. The host_with_mongo_connection is an address relative to the box I have access to, where the port should be forwarded to.

Thus, if the mongod is running on the server you have ssh access to, then the command would look like this:

ssh -L 27017:localhost:27017 user@ssh_and_mongo_box

However, if your ssh box is a front door to a local network, and for example your mongo box has an internal ip of 192.168.0.2, the command would be like so:

ssh -L 27017:192.168.0.2:27017 user@front_door

Then, all connections on port 27017 on your localhost will be mapped to port 27017 on the remote mongo box.

Awesome.

EDIT: If you don’t want to actually connect to the remote server to run commands, and just want to forward the port, add -N -f. This will not open a shell and forward the port in the background.

Comments

Make comment
Mike DeLaurentis

This is a great tip, thanks!

Required. 30 chars of fewer.

Required.

captcha image Please, enter symbols, which you see on the image