Learn how to setup a basic SSH tunnel to access remote server resources that may be blocked by a firewall or simply inaccessible over the internet.
Understanding SSH Tunnels
Let’s say there is a service on a remote server that is running on port 80. You want to access this service from your local computer, but a firewall is in the way.
To bypass the firewall restrictions, you can send the remote service over the SSH port via a tunnel.
Let’s take a look at a specific example.
SSH Tunnel Example
The command for establishing an SSH tunnel looks like this.
ssh -N -L -p 22 localhost:8888:localhost:80 root@159.223.180.93
- -N is a flag to just forward ports and not execute remote commands
- -L forwards local connections to the remote side
- -p 22 is the SSH port of the remote server. This can be a different port, but needs to be open
- localhost is the host on the local machine that will bind to the remote service
- 8888 is the port that the local machine will listen on
- localhost is the internal IP address of the remote service
- 80 is the port of the remote service
- root is the SSH user of the remote server
- 159.223.180.93 is the public IP address of the remote server
After executing the SSH tunnel command, the remote service at localhost:80 will be accessible on the local machine at localhost:8888.
Shorthand
The above example is quite explicit. Here are some ways to shorten it.
- You don’t need to include localhost of the local machine because that is the default
- The default SSH port is 22, so you don’t need to specify that either
- The -N flag is optional. Functionality will be the same whether or not you include it
ssh -L 8888:localhost:80 root@159.223.180.93
Other SSH Tunnel Types
A few different flavors of SSH tunnels exist. In addition to normal SSH tunnels, there are also reverse SSH tunnels and SSH proxy tunnels. Depending on your use case, these other types of SSH tunnels may suit your needs.