AutoSSH for persistent tunnels

Have you ever created a docker image or other service on a remote machine but want to access that service on your local machine as it was local? Well this post is for you!

Have you ever created a docker image or other service on a remote machine but want to access that service on your local machine as it was local? Well this post is for you!

I recently bought a M1 Mac mini for use at Oracle as the provided machine was not up to par.. M1 is amazing but while ARM is not fully supported I've found having a linux box remotely to build & run services is a nice stop-gap until more ARM support is made. The big motivation for this was that I wanted to be able to keep the same "localhost" developer productivity as when running the services locally. Thankfully many great tools have been written around SSH to make this super easy!

Auto SSH

autossh is a great tool for restarting SSH sessions and tunnels for you. This is perfect for our use case so we don't have to deal with managing the tunnel or SSH connection

MacOS

brew install autossh

Just that easy.

Windows

Ummm.. Good luck? ¯\_(ツ)_/¯

Forwarding a service

Okay so lets say we have a machine running the cloud or a server locally (doesn't matter) we want to forward ports locally to. First, lets create a SSH config to make our setup a bit cleaner.

Add a SSH profile to your ssh config file (~/.ssh/config) such as the one below:

Host tangelie
	Hostname <hostname-or-ip>
	IdentityFile <path-to-keyfile>
	User <user>
	Port 22

Now we can easily connect to the server with this command!

ssh tangelie

And the configuration we wrote above will fill everything else in. Awesome!

Next lets say we have a service running on port 8080 on our remote server that we want to access locally also at port 8080. We need to create an autossh command to keep this tunnel open for us:

# -M specifies the base monitoring port to use.
# -f causes autossh to drop to the background before running ssh.
# -N Do not execute a remote command.  This is useful for just forwarding ports.
# -o ssh options
# -L Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side.
# <local-port>:<hostname>:<remote-port>
# ssh connection details
autossh -M 0 -f -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -L 8080:localhost:8080 tangelie

Great!! Now if we run this autossh command it will maintain an SSH tunnel to our machine and port forward 8080 to our localhost!

Last thing we can do to make this much easier to run is to create an bash or ZSH alias:

Now from a terminal you can simply enter tangelie_tunnel and the tunnel will be created for you!

alias tangelie_tunnel="autossh -M 0 -f -N -o \"ServerAliveInterval 60\" -o \"ServerAliveCountMax 3\" -L 8080:localhost:8080 tangelie"

Forward on startup

Stay tuned to my blog for a future article on creating these tunnels on startup!