How Do I Tunnel Into a Remote Database Using SSH?

A common question is “How do I connect to a database running on Amazon (or Azure) from my local laptop?” The answer often is:

  • Create an SSH tunnel that will allow you to treat the remote database as if it was local.

Example

We have an instance of MySQL running on an Amazon EC2 instance and want to access it from our local network. Technically what we want to do is:

  • Pretend that there is a MySQL instance listening on port 3307 on our local network.
  • Have magic forward all communication on localhost port 3307 to a MySQL instance living on Amazon EC2.

The secret sauce requires setting up a forwarding port using ssh. Example:

ssh -L 3307:127.0.0.1:3306 myuser@myhost

This statement will open a terminal prompt on capstormlabs.com and a tunnel listening on 127.0.0.1 that forwards traffic on local port 3307 to port 3306 (e.g. MySQL) on capstormlabs.com. With any CopyStorm product the remote MySQL instance can be reference with a connection string like:

//localhost:3307/myDatabaseName

If you are hungry for more information then see this article for all the details.