SSH tunneling is a very powerful feature of SSH. It allows us remotely access services which are usually away from our reach because of some restrictions.
One powerful use case for this is to run services privately while still being able to access them remotely i.e. the services are not exposed to any public ports.
There are essentially three flavors of ssh tunneling:
- Local SSH port forwarding
- Remote SSH port forwarding
- Dynamic SSH port forwarding
In this post let’s discuss the Local & Remote SSH port forwarding.
Local SSH port forwarding
Imagine you are self hosting postgres & pgAdmin web remotely. Now, because both our postgres & pgAdmin services are not exposed through any publicly open ports, in order to access these for DB administration tasks we can leverage SSH Local SSH port forwarding tunneling. It would allow us locally access these remote DB services.
Let’s say pgAdmin is running on port 11012
on our self hosted remote machine, to access the interface locally we can create a ssh tunnel connecting the remote port 11012
to our port 11026
(let’s say):
$ ssh -L 11026:localhost:11012 <Remote_User>@<Remote_IP/DOMAIN>
Now if we visit localhost:11026
on our local machine’s browser, we would have the pgAdmin web interface available to us.
Remote SSH port forwarding
Similar to the local ssh port forwarding, with remote SSH port forwarding you can expose your locally running service to remote machines ports i.e. remote machine will be able to access your local services.
It is the common mechanism behind services like Serveo
.
Let’s say you want to expose your local service running on port 11206
to a remote machine’s port 11201
, this is how we’d do it:
ssh -R 11206:localhost:11201 $Remote_User@$Remote_IP_Or_Domain
Parting thoughts
It is a secure way of accessing remote services given that our ssh setup is secured as well. Refer to this post for quick pointers to securing ssh access.