← Back to blog

SSH Tunneling Explained: Local, Reverse & Dynamic Port Forwarding

By ·14 min read·Published Nov 28, 2026
Understanding local, remote, and dynamic SSH tunneling

SSH tunneling (SSH port forwarding) carries a selected application's TCP traffic through an authenticated, encrypted SSH connection. Use ssh -L to reach a service from your local computer, ssh -R to make a local service available on the SSH server side, or ssh -D to create a SOCKS proxy for multiple destinations.

The key to understanding every tunnel is to identify which machine opens the listening port and which machine connects to the target service. Below are reproducible command patterns, original network diagrams, and a disposable Docker lab designed to verify all three forwarding modes without publishing a service to the public internet.

1. What is an SSH tunnel and how does it work?

An SSH connection authenticates a client to a server. Port forwarding carries other TCP connections through that SSH transport. The forwarded application does not need to know it is using SSH: it connects to a listening port, and SSH relays its stream to the requested destination.

Encryption has a boundary: traffic is encrypted between the SSH client and SSH server. The onward connection from the other SSH endpoint to the destination service is a separate connection, which may or may not be encrypted by the application protocol. SSH tunneling is not the same as creating a router NAT rule or enabling a full-device VPN.

The destination named in a -L command is reached from the SSH server. The destination named in a -R command is reached from the SSH client. That single distinction explains most "localhost" mistakes.

2. -L vs -R vs -D: visual reference and commands

LOCAL · -L
Local application
127.0.0.1:18080
SSH server
target:80
SSH client listens locally; SSH server reaches the target.
REMOTE · -R
SSH server
127.0.0.1:19090
SSH client
target:3000
SSH server listens remotely; SSH client reaches the target.
DYNAMIC · -D
SOCKS application
127.0.0.1:11080
SSH server
chosen destination
SOCKS client chooses a destination per connection; the SSH server connects onward.
ModeListenerWho connects to destination?Typical use
-L localSSH client / your PCSSH serverPrivate web dashboard or database
-R remoteSSH serverSSH client / your PCReach a local dev service from a jump server
-D dynamicSSH client SOCKS proxySSH serverMultiple services through one SOCKS-aware app

Remember: in all three modes the initiating SSH client still needs to reach and authenticate to the SSH server. A successful SSH login does not prove that the ultimate forwarded destination is reachable.

3. Local SSH port forwarding (-L): access a private service

Local forwarding makes a listener on the SSH client machine. The SSH server then connects to a service on the server itself or another host reachable from the server's network.

ssh -N -o ExitOnForwardFailure=yes \
  -L 127.0.0.1:18080:127.0.0.1:8000 user@ssh-server

Open http://127.0.0.1:18080/ on your PC. The first loopback address belongs to your PC; the target 127.0.0.1:8000 belongs to the SSH server. Use -L 127.0.0.1:15432:db.internal:5432 when the target is a private database that the SSH server can reach.

# From the local client, after the tunnel is connected
curl -I http://127.0.0.1:18080/

-N runs no remote command, while ExitOnForwardFailure=yes makes initial listener/setup failure visible rather than leaving an apparently healthy SSH session. It does not guarantee the target application will respond later.

4. Remote and reverse SSH tunneling (-R)

Reverse or remote forwarding makes a listener on the SSH server. Connections arriving there are carried back over SSH, and the SSH client then connects to the requested local destination. This is useful when a development machine can make outbound SSH connections but cannot accept inbound connections directly.

ssh -N -o ExitOnForwardFailure=yes \
  -R 19090:127.0.0.1:3000 user@ssh-server

From a shell on the SSH server, request http://127.0.0.1:19090/. That reaches 127.0.0.1:3000 on the SSH client machine. On OpenSSH servers, remote forward listeners bind to loopback by default; a reverse tunnel does not automatically create a public URL.

Which machine listens? The localhost rule

ForwardListening addressTarget resolved and connected from
-LSSH clientSSH server
-RSSH serverSSH client

The phrase localhost inside the destination is evaluated at the side making the destination connection. It is not always the SSH server; for -R it is normally the SSH client.

Safe reverse tunnel setup and verification

# On the SSH client: start your service on localhost:3000
# Then start a separate SSH session with:
ssh -N -o ExitOnForwardFailure=yes -R 19090:127.0.0.1:3000 user@ssh-server

# On the SSH server: verify the loopback listener and response
ss -ltnp 'sport = :19090'
curl -I http://127.0.0.1:19090/

Our downloadable lab uses Nginx mapped only to the Windows host's loopback port 13000, and demonstrates the same operation with -R 19090:127.0.0.1:13000. Keep the tunnel foregrounded while collecting evidence.

GatewayPorts, AllowTcpForwarding and server-side limits

OpenSSH sshd uses GatewayPorts no by default. GatewayPorts yes forces wildcard listeners for remote forwards; clientspecified permits a client to choose a bind address. These are not harmless troubleshooting toggles: a wildcard bind can expose an admin service to other networks.

sshd optionPractical meaning
GatewayPorts noRemote forwarding stays loopback-only by default; safest starting point.
GatewayPorts clientspecifiedPermits explicit non-loopback binds when needed and allowed.
GatewayPorts yesForces wildcard binding for remote forwards; can increase exposure.
AllowTcpForwardingCan disable forwarding or restrict it to local/remote directions.
PermitOpen / PermitListenRestrict destinations of local forwards or listen addresses/ports of remote forwards.

For this guide, do not change GatewayPorts. The lab deliberately verifies the default loopback behavior. For real deployment, combine any narrowly approved remote bind with SSH authorization and host firewall controls. Validate configuration with sudo sshd -t before a supervised reload, keeping a separate recovery session available.

5. Dynamic SSH port forwarding (-D): SOCKS5 and DNS

Dynamic forwarding runs a SOCKS proxy on the SSH client. Unlike -L, the destination is chosen independently for each request by the SOCKS-aware application. OpenSSH supports SOCKS4/5 for dynamic forwarding.

ssh -N -o ExitOnForwardFailure=yes \
  -D 127.0.0.1:11080 user@ssh-server

Point your application at the local SOCKS proxy. With curl, --socks5-hostname or a socks5h:// URL sends the destination hostname to the proxy, so the SSH server resolves names that your local computer may not know.

# Resolve the destination on the SSH-server side
curl --socks5-hostname 127.0.0.1:11080 http://internal.service/

# Equivalent curl proxy URL
curl --proxy socks5h://127.0.0.1:11080 http://internal.service/

Limits: SOCKS forwarding applies only to applications configured to use it. It does not tunnel your computer's entire network stack, automatically proxy every protocol, or guarantee that a browser sends DNS requests through the proxy.

SSH SOCKS proxy: additional technical notes

This section preserves the original merged SOCKS guide anchors while keeping the explanation in one place.

What dynamic forwarding does

The SSH client accepts SOCKS requests at the local listening address. The SSH server opens the requested connection using its own network route, and both directions of application data are carried over SSH.

SOCKS binding address

Keep -D on 127.0.0.1 unless you have explicitly authorized a local-network proxy. Binding SOCKS to 0.0.0.0 can let other devices use your SSH server as an exit point.

Local vs remote DNS

With curl, --socks5 resolves the target hostname on the client; --socks5-hostname passes the hostname through SOCKS. This matters for private DNS names that exist only behind the SSH server.

Verifying the SOCKS tunnel

First confirm the local SOCKS port exists; then make a real request with curl --socks5-hostname. A listening proxy alone does not prove that the SSH server can reach the target.

6. Reproducible Docker Desktop SSH tunneling lab

Download the companion files: ShadeTerm SSH tunneling Docker lab (ZIP)

The downloadable companion lab package runs on Docker Desktop and uses an Ubuntu 24.04 OpenSSH server, a private Nginx container (shadeterm-internal), and a Windows-loopback-only Nginx development endpoint. Docker publishes SSH only to 127.0.0.1:2222, so the experiment does not require a VPS or changes to a real home router.

# In the directory containing compose.yaml and gateway/Dockerfile:
docker compose up -d --build

# Confirm the SSH gateway reaches the private service
docker compose exec gateway curl -I http://shadeterm-internal/

# Read the temporary container SSH host key fingerprint for first login
docker compose exec gateway ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

Run each tunnel command in a separate Windows PowerShell session and keep it running while making test requests from another terminal. Connect as [email protected] with -p 2222. Match the displayed SSH host fingerprint to the one obtained from the container. The lab-only password is supplied in the README; delete the lab after capturing screenshots.

TestSSH command suffix after -p 2222 [email protected]Verify from
Local -L-L 127.0.0.1:18080:shadeterm-internal:80Windows: curl.exe -I http://127.0.0.1:18080/
Remote -R-R 19090:127.0.0.1:13000Gateway: curl -I http://127.0.0.1:19090/
Dynamic -D-D 127.0.0.1:11080Windows: curl.exe --socks5-hostname 127.0.0.1:11080 -I http://shadeterm-internal/

Run each example and check the actual listener and application response before claiming it succeeded. The companion files provide a reproducible test setup; no new live lab measurements are claimed here.

# After capturing all screenshots:
docker compose down --remove-orphans

7. Keep a tunnel alive and fail visibly when setup breaks

-N suppresses a remote shell; -f backgrounds SSH after authentication. ExitOnForwardFailure=yes makes an initial forwarding setup failure fatal, but it does not verify the destination service for every future connection.

# Foreground: easiest to debug
ssh -N -vv -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  -L 127.0.0.1:15432:db.internal:5432 user@bastion

ServerAliveInterval and ServerAliveCountMax detect an unresponsive SSH peer. They do not restart a dropped session. Use an approved service manager or autossh for attended/managed reconnection rather than assuming keepalives are self-healing.

# Reusable client configuration (~/.ssh/config)
Host private-db-tunnel
  HostName bastion.example.com
  User deploy
  LocalForward 127.0.0.1:15432 db.internal:5432
  ExitOnForwardFailure yes
  ServerAliveInterval 30
  ServerAliveCountMax 3

# Start it without a remote shell
ssh -N private-db-tunnel

Reverse tunnel keepalive

For a reverse tunnel use the same client-side keepalive options with -R. They detect a dead SSH session, not an application that becomes unhealthy after the tunnel was established.

8. Troubleshooting: the tunnel is up but the app fails

Troubleshoot in order: SSH authentication and transport → forwarding listener → destination from the correct side → application response. Avoid changing firewalls or GatewayPorts before identifying the failed hop.

SymptomMost likely checksVerify with
bind: Address already in useAnother process owns the local listening port.ss -ltnp / PowerShell Get-NetTCPConnection
remote port forwarding failedRemote listen port occupied, permission denied, or policy restricts it.ss -ltnp on server and server logs
administratively prohibitedServer forwarding policy (including AllowTcpForwarding/PermitOpen) or target restrictions.ssh -vv, sshd -T where authorized
Tunnel connects but HTTP failsTarget service unavailable or target localhost evaluated on wrong side.curl from the side making the destination connection
Reverse tunnel works on server but not another machineExpected loopback bind; remote forwarding is not public by default.ss -ltnp, review GatewayPorts and firewall
SOCKS request failsApp is using HTTP proxy mode instead of SOCKS or target DNS is local.curl --socks5-hostname

Useful SSH debug option: ssh -vv. It reveals forwarding setup and channel failures but may contain sensitive hostnames, usernames and endpoints; redact those details before sharing logs. If local forwarding to a database is refused, first test database reachability from the SSH server, not from the original client.

Reverse forwarding-specific errors

If the remote SSH port is not listening, check AllowTcpForwarding, PermitListen, competing ports and session output. If it listens only on 127.0.0.1, this is ordinarily the expected security default, not a broken tunnel.

9. SSH tunneling security: what encryption does and does not protect

An SSH tunnel encrypts traffic on the SSH link; it does not automatically add authentication to the destination service or encrypt its separate onward hop. Restrict who can create forwards, which ports they can bind, and which destinations they may contact.

ControlWhy it matters
127.0.0.1 listenerRestricts access to the originating host or network namespace.
GatewayPorts server settingControls exposure of remote -R listeners.
AllowTcpForwarding, PermitOpen, PermitListenCan restrict allowed forwarding directions, destinations and listening ports.
Host/service authentication and firewallStill required even when SSH protects the transport.
Account restrictions / monitoringLimit unintended tunnels by compromised accounts.

Do not use a wildcard bind or modify server-wide forwarding policy to demonstrate a screenshot. Our lab keeps all published Docker host ports on loopback and uses the default remote-forward listener restrictions.

Reverse tunnel security

A reverse tunnel can create an access path to a previously private service. Grant it only on systems you administer and keep the remote listener on loopback unless broader access is explicitly needed and controlled.

10. SSH tunneling vs VPN vs router port forwarding

MethodScopeBest suited for
SSH local/remote tunnelSelected TCP connections via an authenticated SSH hostAccess to one database, admin page, or dev service
SSH SOCKS5 -DTraffic from SOCKS-aware applicationsMultiple destinations through a trusted SSH server
VPNConfigured device/network trafficOngoing private network access across devices
Router port forwardingIncoming connections from outside to a NAT targetPublishing deliberately internet-facing services

See the separate router port forwarding guide for NAT and CGNAT. SSH forwarding is not a universal replacement for a VPN; it forwards selected supported traffic and needs a reachable SSH endpoint.

11. Practical use cases and ShadeTerm workflow

Database administration: a local tunnel can reach a database bound to a private interface on a VPS or inside a VPC, without opening the database port to the internet.

Internal dashboards: reach a loopback-only web UI through an authorized SSH gateway. For SSH specifically, see our Linux open-ports guide to verify which address actually listens.

Development preview: a reverse tunnel can connect a local development service to a remote host you control, initially on the remote host's loopback interface.

ShadeTerm: use ShadeTerm for reachable server workspaces with terminals, SFTP and editing. The -L, -R and -D commands in this article are standard OpenSSH terminal commands; this guide does not claim they are all exposed as dedicated ShadeTerm UI controls.

Reverse tunnel examples

For NAT-restricted test environments, prefer a loopback-only remote forward and connect via an authorized SSH session to the relay host. Publishing the remote forward to all interfaces is a separate, higher-risk design choice.

12. FAQ: SSH tunnels and port forwarding

What does ssh -L mean?

It opens a listener on your SSH client and sends connections via the server to a target that the server can reach.

What does ssh -R mean?

It opens a listener on the SSH server and forwards traffic back to a target reached from the SSH client side.

What does ssh -D mean?

It opens a local SOCKS proxy. SOCKS-aware applications can choose the requested target for each connection.

Does SSH tunneling expose a port to the internet?

No, not by default. A loopback-only listener is local to its endpoint. Public access requires additional intentional binding and network/firewall permissions.

Why does SSH connect successfully while the tunnel does not work?

SSH authentication, local/remote listener setup, destination connectivity and application response are distinct steps. Test each hop independently.

Does ExitOnForwardFailure=yes check the destination service?

No. It detects initial forwarding setup failures, not every later destination connection failure.

Sources and our testing methodology

This guide uses the OpenSSH command manuals for syntax, listener behavior, GatewayPorts, and forwarding restrictions. SSH Academy provides broader context; the downloadable Docker Compose package is designed for original local proof of the three modes. Commands and expected outcomes are documented; the new lab bundle has not been executed during this migration, and no new benchmark is claimed.

Conclusion

Remember the listener: -L listens at the SSH client, -R listens at the SSH server, and -D creates a local SOCKS listener. To diagnose a tunnel, verify the SSH connection, the listening address, the destination from the correct side and the application's response.

For working with Linux servers after you have secure SSH access, ShadeTerm brings terminals, files and code into a server workspace. Use the accompanying Docker lab to reproduce each example before applying it to production infrastructure.