SSH Local Port Forwarding
Configure local port forwarding in SSH config to access remote services (databases, web apps) through an encrypted tunnel on a local port.
Detailed Explanation
Local Port Forwarding with SSH Config
Local port forwarding creates an encrypted tunnel from a port on your local machine to a port on a remote host. This lets you access remote services (databases, admin panels, internal APIs) as if they were running locally.
Example Config
Host db-tunnel
HostName db-server.internal
User tunnel-user
LocalForward 5432 localhost:5432
IdentityFile ~/.ssh/id_ed25519_work
IdentitiesOnly yes
ServerAliveInterval 60
ServerAliveCountMax 3
How It Works
When you connect with ssh db-tunnel:
- SSH opens a connection to
db-server.internal - Port 5432 on your local machine is mapped to port 5432 on the remote host
- Any connection to
localhost:5432is transparently tunneled to the remote PostgreSQL
Multiple Forwards
You can forward multiple ports in a single config entry:
Host dev-tunnel
HostName dev.example.com
User developer
LocalForward 5432 localhost:5432
LocalForward 6379 localhost:6379
LocalForward 8080 internal-api:8080
Forwarding to Third-Party Hosts
The target doesn't have to be the SSH server itself. You can forward to any host reachable from the SSH server:
LocalForward 3306 mysql-primary.internal:3306
This tunnels your local port 3306 through the SSH server to mysql-primary.internal:3306.
Background Tunnels
To run the tunnel in the background without opening a shell:
ssh -fN db-tunnel
The -f flag sends SSH to the background, and -N prevents executing any remote command.
Security Notes
Local port forwarding is safer than exposing services directly to the internet. All traffic between your machine and the SSH server is encrypted. However, the forwarded connection between the SSH server and the target service is only encrypted if the service itself uses TLS.
Use Case
Developers who need to access remote databases, internal APIs, or admin interfaces that are not exposed to the public internet, tunneling through SSH for secure access.