Local port forwarding allows you to connect from your local computer to another server.
Imagine you have a server
blue.example.com listening on port
4000 that you
want to connect to but the server only accepts connections from its local
network / VPN. You’re trying to connect from the wider internet.
Forwarding a local port
You have a user account
blue.example.com. You can then set up a local
SSH port forward using the following command:
ssh -L 1234:localhost:4000 firstname.lastname@example.org
Now you can connect to
blue.example.com:4000 by pointing your browser or
localhost:1234. What does the
-L flag mean? It just specifies
that we are doing local port forwarding.
Generally the form for local port forwarding is:
ssh -L $localport:localhost:$remoteport $server
$localport is the local port on your machine,
$remoteport is the port on the
remote machine you want to forward too (to access) and
$server is the address
of the remote machine.
Some other tips
I like to pass the
-N flag to SSH. Just add this flag to the end like this:
ssh -L $localport:localhost:$remoteport $server -N
This tells SSH not to execute a remote command, which is normally to start a shell session. When port forwarding that’s normally the only thing we want to do and starting a shell is unnecessary.
As a script
I now just have this basic command committed as a shell script in my bin path.
#!/bin/bash ssh -L $3:localhost:$2 $1 -N
Name the file something like
ssh-portforward. It takes three arguments, the
remote host, the remote port and then the local port. I read it as “forward
$local-port”. Execute as
ssh-portforward email@example.com 1234 4000.