Quite often it’s very handy to be able to use a tunnel to access services at home or on a server.

For example: you run a MySQL instance on a server you manage through SSH. The MySQL instance is not exposed to the internet and is only listening on localhost on the server. Now you want to use your favorite SQL tool to access the database.

This can be achieved using a VPN of course, but those are not easy to set up correctly. Since you manage the server over SSH anyway, you already have an easy to use tool, to make it work. You can make a port tunnel through SSH. This is similar to port forwarding, which you might know from setting up a home-router. Our goal is to create a port on your machine, which is forwarded to a port on a remote machine.

That goes like this:

$ ssh -f user@mydomain.com -L <port>:<remote host>:<remote port> -N
Parameters:
-f                 This will execute the command in background, not 
                   blocking your terminal session.
                   Warning: The tunnel will be kept open as long as you 
                   don't disconnect your network or kill the SSH process.
                   If you leave that parameter out, you can close the connection
                   by issuing <Ctrl>+C killing the SSH tunnel.
user@mydomain.com  Username and host of your SSH server.
-L                 This parameter creates the tunnel instead of a normal SSH session.
<port>             Local port on your machine, which is forwarded to the remote system.
<remote host>      Host of the service you want to remotely connect, can be the SSH
                   host, but rather be the MySQL instance host.
<remote port>      Port on the remote host you want your tunnel to connect to. For MySQL,
                   this would be 3306.
-N                 We don't want to execute something on the remote system, just
                   create a tunnel.

For a PostgreSQL server that could look like:

$ ssh -f marcel@metawave.ch -L 5432:localhost:5432 -N

and on a MySQL server:

$ ssh -f marcel@metawave.ch -L 3306:localhost:3306 -N

After entering the password, the tunnel connection is established. Now we can access the remote service as it would run on your local machine. In your favorite SQL tool, you’d enter localhost for hostname and connect as you would on the remote system.

This is also an easy way to improve your server security by not exposing too much to the outside, but rather connect through a secure SSH tunnel and access your services from there.