SSH Port forward
SSH tunneling (also referred to as SSH port forwarding) is simply routing the local network traffic through SSH to remote hosts. This implies that all your connections are secured using encryption. It provides an easy way of setting up a basic VPN (Virtual Private Network), useful for connecting to private networks over unsecure public networks like the Internet.
Local SSH Port Forwarding
This type of port forwarding lets you connect from your local computer to a remote server. Assuming you are behind a restrictive firewall or blocked by an outgoing firewall from accessing an application running on port 3000 on your remote server.
You can forward a local port (e.g 8080) which you can then use to access the application locally as follows. The
-L flag defines the port forwarded to the remote host and remote port.
ssh email@example.com -L 8080:server1.example.com:3000
-N flag means do not execute a remote command, you will not get a shell in this case.
ssh -N firstname.lastname@example.org -L 8080:server1.example.com:3000
-f switch instructs ssh to run in the background.
ssh -f -N email@example.com -L 8080:server1.example.com:3000
Now, on your local machine, open a browser, instead of accessing the remote application using the address server1.example.com:3000, you can simply use
192.168.43.31:8080, as shown in the screenshot below.
Remote SSH Port Forwarding
Remote port forwarding allows you to connect from your remote machine to the local computer. By default, SSH does not permit remote port forwarding. You can enable this using the GatewayPorts directive in your SSHD main configuration file /etc/ssh/sshd_config on the remote host.
Open the file for editing using your favorite command-line editor.
sudo vim /etc/ssh/sshd_config
Look for the required directive, uncomment it, and set its value to
yes, as shown in the screenshot.
Save the changes and exit. Next, you need to restart sshd to apply the recent change you made.
sudo systemctl restart sshd OR sudo service sshd restart
Next run the following command to forward port 5000 on the remote machine to port 3000 on the local machine.
ssh -f -N firstname.lastname@example.org -R 5000:localhost:3000
Once you understand this method of tunneling, you can easily and securely expose a local development server, especially behind NATs and firewalls to the Internet over secure tunnels. Tunnels such as Ngrok, pagekite, localtunnel, and many others work in a similar way.