PUBLICATION_DATE: 2023.01.21

SSH Port Forwarding Examples

DOMAIN: DevOps/SSH

« BACK TO NOTES

SSH Port Forwarding or SSH Tunnel

Local and Remote forwarding connects ports on two machines over SSH connection (tunnel).

Local Forwarding

Local forwarding -L creates a listener on the local machine (current shell) and forwards traffic to the remote host.

ssh -L 8001:localhost:80 remote.example.com

Listen on LOCAL port 8001 forward to port 80 on remote.example.com.

Common use case: Access a remote database or web service locally. For example, connect to a remote MySQL server as if it were running on your local machine.

Remote Forwarding

Remote forwarding -R creates a listener on the remote machine (requested shell) and forwards traffic to the local host.

ssh -R 8004:localhost:8003 remote.example.com

Listen on REMOTE (remote.example.com) port 8004 forward to port 8003 on localhost.

Common use case: Expose your local development server to a remote machine for testing or demonstration.

Useful Flags

Tunnel without opening a shell:

ssh -N -L 8001:localhost:80 remote.example.com

The -N flag prevents executing remote commands, useful when you only need the tunnel.

Run tunnel in background:

ssh -f -N -L 8001:localhost:80 remote.example.com

The -f flag runs SSH in the background after authentication.

Note: Keep your terminal open or use -f flag to maintain an active tunnel. Closing the SSH connection terminates the port forwarding.