Introduction
SSH tunneling (also called SSH port forwarding) allows you to securely forward network traffic through an encrypted SSH connection. This is useful for accessing remote services securely, bypassing firewalls, or encrypting otherwise unencrypted connections.
Local port forwarding
Forwards a port on your local machine to a port on a remote server. Use this to access a remote service as if it were running locally.
Syntax
ssh -L local_port:destination_host:destination_port user@ssh_server
Example: Access a remote MySQL database
Your database server (10.0.0.5) only accepts connections from the application server (10.0.0.1). You have SSH access to 10.0.0.1.
ssh -L 3306:10.0.0.5:3306 user@10.0.0.1
Now connect your MySQL client to localhost:3306, and the traffic is securely tunneled to 10.0.0.5:3306 through 10.0.0.1.
Example: Access a remote web panel
ssh -L 8080:localhost:8006 user@proxmox-server
Open http://localhost:8080 in your browser to access the Proxmox web UI.
Run in the background
ssh -fNL 3306:10.0.0.5:3306 user@10.0.0.1
Flags: -f (background), -N (no remote command).
Remote port forwarding
Forwards a port on the remote server to a port on your local machine. Use this to make a local service accessible from the remote server.
Syntax
ssh -R remote_port:destination_host:destination_port user@ssh_server
Example: Expose a local web server
You have a development server running on localhost:3000 and want to access it from a remote server.
ssh -R 8080:localhost:3000 user@remote-server
On the remote server, http://localhost:8080 now reaches your local development server.
Dynamic port forwarding (SOCKS proxy)
Creates a SOCKS proxy on your local machine that tunnels all traffic through the SSH server. Useful for browsing the internet through a remote server.
Syntax
ssh -D local_port user@ssh_server
Example
ssh -D 1080 user@remote-server
Then configure your browser or application to use a SOCKS5 proxy at localhost:1080. All traffic will be routed through the SSH server.
Making tunnels persistent
SSH tunnels close when the connection drops. For persistent tunnels, use autossh:
sudo apt install autossh
autossh -M 0 -fNL 3306:10.0.0.5:3306 user@10.0.0.1
autossh automatically reconnects if the SSH session drops.
Quick reference
| Type | Flag | Direction | Use case |
|---|---|---|---|
| Local | -L |
Local → Remote | Access remote services locally |
| Remote | -R |
Remote → Local | Expose local services remotely |
| Dynamic | -D |
SOCKS proxy | Route all traffic through SSH |
Common options
| Option | Description |
|---|---|
-f |
Run SSH in the background |
-N |
Do not execute a remote command (tunnel only) |
-p 7722 |
Connect to SSH on a non-standard port |
-i ~/.ssh/key |
Use a specific private key |