Ever since I remember, I have this inability to learn the most basic things, until I actually write down a couple notes or instructions somewhere. This is one of these notes blog posts — so in case it’s too basic, just skip over it. Or bear with me.

ssh tunnels — useful and powerful. They can help me with all kinds of trickery — e.g. usually for remoting through a tight firewall setup to access remote resources. So point taken there are a lot of GUIs for this, but if you spend a couple minutes with the ssh man page, you will realize how amazingly simple they are.

My example for an ssh tunnel put to good use is our production gearman setup: The gearmands runs isolated on EC2. On the upside: pretty secure, but the downside is that the service is unavailable when you need to a little live data for some local tests. When we added an interface to get more visibility into the processes we push through gearman, of course we couldn’t access it.

A tunnel to the rescue!

Consider this:

(“ctrl + a + d”, to detach from screen.)

So what does that do?

First off, we are starting a session in screen: it’s called “gearman-ssh-tunnel”. You could use tmux as well, but screen works just as nice.

The consecutive command maps port 2222 on my (local) macbook to a service running on the server production-gearmand (this is via .ssh/config) but only listens on 127.0.0.1:4730.

Your .ssh/config could look like this:

If I wanted to connect to this server in a PHP-script on my macbook, I would use the following configuration:

Run it from the terminal:

Success!

Need to stop the tunnel?

The following command lets you resume your session with screen:

Type exit twice, or hit “ctrl + d” to log off the server and “ctrl + d” again to kill the screen. Done.

Fin

Bonus points if you use this from your VM in vagrant. But otherwise, that’s all for today.