SSH Tunnel to connect to Remote Mongodb

Problem:

I love to use RoboMongo1 as the Mongo DB Query tool. In my case the problem is that the MongoDb server is on a private network and the only way to get to the private server from my machine is via ssh. Which means logging into the box, using mongo command to connect to the database and then issue my queries. Of course manually typing in my queries on a command line isn't my favorite thing to do. Being able to use RoboMongo is a major productivity boost and I want to be able to use it to connect to remote DB.

Solution:

Enter SSH tunnel.

Issue the following command on your terminal (I am using Mac hence a UNIX based system):

ssh -fN -i ~/.ssh/YourKeyFile.pem -L 6666:localhost:27017 userId@1.2.3.4

The command above is setting up: traffic on your local machine's 6666 port to be forwarded to remote server's localhost:27017. The userId is the userId you use to login to remote box. And 1.2.3.4 is remote server's ip address. The -i parameter allows you to connect using a .pem file i.e. a password-less connection.

Please make sure not to use low port numbers (lower than 1024) as local machine's port, since you won’t be able to bind them without root privileges.

Once you have the SSH tunnel set you can connect via RoboMongo on localhost:6666.

Any traffic will be diverted to 1.2.3.4 then to localhost:27017.

Hope you found this useful. Please let me know if you have any questions/comments/feedback.

References: