Port Forwarding
SSH is not limited to terminal sessions. It can also forward network connections, allowing you to connect to network services on the remote computer as if they were on your local computer. This is very useful for things like Jupyter notebooks, or for debugging web servers.
If you know in advance the port that you need to connect to, you can specify it on the SSH command line:
$ ssh -P 8888:localhost:8888 myhost.cci.drexel.eduThe -P option enables port forwarding, and this invocation tells it to listen for connections on the local system’s port 8888 (the first 8888), and relay those connections to port 8888 on the remote system’s localhost. It has three pieces:
- The local port (8888).
- The remote host to connect to, as seen on the remote system. To connect to the remote system itself, we use
localhost. - The remote port (8888).
The -P option can be specified multiple times to forward multiple ports.
If we do not know in advance what port(s) we will need (e.g., Jupyter might pick a different port), we have a couple of options:
- Open another terminal with a second
sshconnection to establish the port forward. It is perfectly fine to make multiple connections to the same remote machine. - Use software that allows us to add a port forward after we have made the connection. VS Code is a very good option for this.
VS Code’s remote editing support includes port forwarding capabilities. In the “Ports” pane of the lower panel (with the terminal and output), you can add forwarded ports. In some cases, it will automatically detect programs you have running that are listening for connections that can be forwarded. If you have a remote VS Code session running anyway, this is probably the easiest way to add a port forward after you have made your initial connection.
Only one program can be listening on any given network port at a time. So if you are forwarding port 8888 to one remote system, you cannot simultaneously attempt to also forward it to a different system. You will need to pick a different port.