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_server

Example: access a remote database on port 5432 via localhost:

ssh -L 5432:db.internal:5432 user@bastion.example.com

Now 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_server

Example: make your local dev server (port 3000) available on the remote machine:

ssh -R 8080:localhost:3000 user@remote.example.com

Now 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_server

Example: route browser traffic through the SSH server:

ssh -D 1080 user@ssh_server

Configure your browser to use localhost:1080 as a SOCKS5 proxy.

Useful flags

FlagPurpose
-NNo remote command, just hold the tunnel open
-fFork to background after authentication
-TDisable pseudo-terminal allocation (useful with -N)
-o ServerAliveInterval=60Keep connection alive with heartbeats
-J jump_hostProxyJump, tunnel through an intermediate host

Common patterns

Background tunnel with no shell:

ssh -fNT -L 5432:db.internal:5432 user@bastion.example.com

Jump through a bastion host:

ssh -J user@bastion.example.com user@internal-server

Multiple port forwards in one command:

ssh -L 5432:db:5432 -L 6379:redis:6379 user@bastion.example.com

Mosh

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@host

This 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@host

References

  • man ssh
  • man mosh