Simple SSH Port Forwarding
SSH port forwarding (also known as SSH tunneling) allows you to securely forward network traffic from one port to another through an encrypted SSH connection. This is useful when you need to access a service running on a remote server that isn’t publicly exposed.
Local port forwarding
Assuming the remote server has a web service running on port 54242, the following command forwards traffic from the remote server’s port 54242 to your local port 55000:
ssh -L 55000:localhost:54242 user@42.124.12.21
Breaking down the command:
-L— Specifies local port forwarding.55000— The local port on your machine that will receive the forwarded traffic.localhost:54242— The destination host and port as seen from the remote server. Here,localhostrefers to the remote server itself.user@42.124.12.21— The SSH credentials and address of the remote server.
After running this command, you can open http://localhost:55000 in your browser and access the service as if it were running locally.
Remote port forwarding
Remote port forwarding works in the opposite direction — it exposes a service running on your local machine to the remote server. This is useful when you want to let others access something running on your machine through the remote server.
ssh -R 8080:localhost:3000 user@42.124.12.21
This forwards port 8080 on the remote server to port 3000 on your local machine. Anyone who can reach the remote server on port 8080 will be hitting your local service on port 3000.
Running in the background
If you don’t need an interactive shell session, you can run the tunnel in the background:
ssh -f -N -L 55000:localhost:54242 user@42.124.12.21
-f— Sends the SSH process to the background after authentication.-N— Tells SSH not to execute any remote commands, since we only need the tunnel.
Forwarding to a third host
Port forwarding isn’t limited to services on the remote server itself. You can also forward traffic to a third host that the remote server can reach:
ssh -L 55000:192.168.1.50:5432 user@42.124.12.21
This forwards your local port 55000 to port 5432 on 192.168.1.50, routed through the remote server. A common use case is accessing a database server on a private network that only the remote server has access to.
Practical use cases
While more complex setups involving firewalls or VPNs are available, SSH port forwarding is often all you need for straightforward scenarios:
- Accessing a home server from work or university — Forward a service running at home through an SSH server you control.
- Connecting to a remote database — Securely access a PostgreSQL or MySQL instance that only accepts local connections.
- Bypassing restrictive networks — Tunnel web traffic through an SSH server when certain ports are blocked.
- Debugging remote services — Access a development server’s admin panel or API without exposing it publicly.