Secure Shell(SSH) is a versatile protocol and can be used for various purposes other than remote command execution. One such purpose is to tunnel local port or socket to a remote host’s port or socket. By making use of this feature one can securely access remote server’s internal services or connect to other hosts in the server’s internal network. This is equivalent to converting your ssh connection to a VPN tunnel.
Let’s say I have a grafana server running on host 192.168.0.20 and is in the same internal network as my externally accessible ssh server. To connect to this grafana server, I could setup local port forwarding, such that all connections on my localhost’s port 3000 will be forwarded to this remote grafana server.
Once this is set up, I can access this server in by local machine’s browser by visiting http://localhost:3000/
This way I do not have to worry about exposing this grafana server to the Internet and setting up SSL certificates, since connections are already encrypted via ssh.
ssh -p 22 -fNT -L localhost:3000:192.168.0.20:3000 myuser@remotehost
-L is the only mandatory option needed for local port forwarding and -fNT is optional sets up forwarding efficiently.
-L localhost:3000:192.168.0.20:3000 says forward all connections to local port 3000 to remote host 192.168.0.20’s 3000 port.
myuser@remotehost specifies the username and server hostname for the connection.