Tunneling
Local port forwarding (-L)
Forward a port on your local machine to a remote destination through the SSH server.
ssh -L local_port:remote_host:remote_port user@ssh_serverExample: access a remote database on port 5432 via localhost:
ssh -L 5432:db.internal:5432 user@bastion.example.comNow localhost:5432 connects to db.internal:5432 through the bastion.
Remote port forwarding (-R)
Expose a local service to the remote server.
ssh -R remote_port:local_host:local_port user@ssh_serverExample: make your local dev server (port 3000) available on the remote machine:
ssh -R 8080:localhost:3000 user@remote.example.comNow remote.example.com:8080 connects back to your local port 3000.
Dynamic port forwarding (-D)
Create a SOCKS proxy through the SSH server.
ssh -D local_port user@ssh_serverExample: route browser traffic through the SSH server:
ssh -D 1080 user@ssh_serverConfigure your browser to use localhost:1080 as a SOCKS5 proxy.
Useful flags
| Flag | Purpose |
|---|---|
-N | No remote command, just hold the tunnel open |
-f | Fork to background after authentication |
-T | Disable pseudo-terminal allocation (useful with -N) |
-o ServerAliveInterval=60 | Keep connection alive with heartbeats |
-J jump_host | ProxyJump, tunnel through an intermediate host |
Common patterns
Background tunnel with no shell:
ssh -fNT -L 5432:db.internal:5432 user@bastion.example.comJump through a bastion host:
ssh -J user@bastion.example.com user@internal-serverMultiple port forwards in one command:
ssh -L 5432:db:5432 -L 6379:redis:6379 user@bastion.example.comMosh
Mosh (mobile shell) is a drop-in replacement for SSH built for unreliable or roaming connections. It uses SSH only for the initial login, then switches to its own UDP-based protocol that tolerates dropped packets, sleep/wake, and IP changes (such as moving between Wi-Fi and cellular).
Basic connection:
mosh user@hostThis logs in over SSH, starts mosh-server on the remote, then hands the session over to the UDP transport. mosh-server must be installed on the remote host, and UDP ports 60000-61000 must be reachable.
Use a non-default SSH port or key:
mosh --ssh="ssh -p 2222 -i ~/.ssh/id_ed25519" user@hostReferences
man sshman mosh