Home > bash, mongodb > MongoDB: connect remotely

MongoDB: connect remotely

I have a Digital Ocean VPS running MongoDB. There is a web application on this machine that is on port 80. MongoDB is hidden from the outside world and can only be accessed internally. There is also an SSH port where I can log in.

How to connect to my MongoDB server from home? Say I want to use a graphical client, e.g. MongoChef. The client runs on my home machine and I want to connect to MongoDB with it on my DO VPS. How to do that?

I found the solution here. In short: we connect securely to our database through an SSH tunnel.

Make sure that:

  • you can SSH into your Mongo droplet
  • your MongoDB is bound to localhost

For connecting, I use this script:

cmd="ssh -p ${REMOTE_SSH_PORT} -L ${LOCAL_PORT}:localhost:${REMOTE_MONGO_PORT} user@your.remote.ip"
echo "#" $cmd
echo "# connect on your home machine to port ${LOCAL_PORT}"
echo "# example:    mongo --port ${LOCAL_PORT}"

The default SSH port is 22, but it’s a good idea to change it. With the command “ssh -p ${REMOTE_SSH_PORT} user@your.remote.ip” I could log in to my VPS. However, MongoDB was not accessible from outside, thus executing “mongo --host your.remote.ip --port ${REMOTE_MONGO_PORT}” failed.

The SSH tunneling above works as follows. On your home machine you open the port ${LOCAL_PORT} that is connected to your remote machine via the SSH port ${REMOTE_SSH_PORT}, and the connection is tunneled to localhost:${REMOTE_MONGO_PORT}, where localhost means the remote machine where we logged in with SSH.

So, when you execute the script above, you’ll have to log in to your remote machine via SSH. Then open a new terminal and type “mongo --port 2345” and voilá, you are connected to MongoDB on your remote machine!

If you use a Mongo client (e.g. MongoChef), then simply create a new connection and specify localhost with port 2345. Connect, and you are in.

It works as long as you are logged in in a terminal via SSH. When you log out, the local port closes that is tunneled to your remote machine.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: