SSH Local vs Remote Port Forwarding on Ubuntu

Setting up SSH tunnels on Ubuntu Linux allows you to securely route network traffic between a local client and a remote server. This article explains the fundamental differences between local port forwarding (using the -L flag) and remote port forwarding (using the -R flag), helping you understand when and how to use each configuration.

Local Port Forwarding (The -L Flag)

Local port forwarding is used when you want to access a service on a remote server (or a service accessible through that remote server) from your local machine.

When you use the -L flag, your local SSH client listens on a specified port. Any traffic sent to this local port is intercepted, encrypted, and forwarded through the SSH connection to the remote SSH server, which then delivers it to the destination host and port.

Syntax:

ssh -L [local_interface:]local_port:destination_host:destination_port user@ssh_server

Common Use Case: You want to access a database (e.g., PostgreSQL running on port 5432) that is hosted on a secure remote server. The database port is blocked by a firewall, but you have SSH access to the server.

By running ssh -L 8000:localhost:5432 user@remote-server, you can point your local database GUI to localhost:8000 to securely manage your remote database.

Remote Port Forwarding (The -R Flag)

Remote port forwarding is the exact opposite of local port forwarding. It is used when you want to make a service on your local machine (or local network) accessible to a remote server.

When you use the -R flag, the remote SSH server listens on a specified port. Any traffic sent to that port on the remote server is forwarded back through the encrypted SSH tunnel to your local machine, which then routes it to the target destination.

Syntax:

ssh -R [remote_interface:]remote_port:destination_host:destination_port user@ssh_server

Common Use Case: You are developing a web application on your local Ubuntu machine (running on port 3000) and want to show it to a client. Since your local machine is behind a NAT router/firewall and does not have a public IP, you can use a remote SSH server to bridge the gap.

By running ssh -R 8080:localhost:3000 user@remote-public-server, anyone who accesses port 8080 on the public remote server will be securely directed to the web application running on your local computer.

Key Differences Summary