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.edu

The -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:

  1. The local port (8888).
  2. The remote host to connect to, as seen on the remote system. To connect to the remote system itself, we use localhost.
  3. 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:

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.

Note

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.