SSH Port Forwarding
SSH port forwarding (tunneling) is a critical technique for DevOps engineers to securely access internal services, databases, and applications across cloud and hybrid environments (AWS, Azure, GCP). This guide covers local, remote, and dynamic forwarding with actionable examples and best practices.
1. Local Port Forwarding
Forward a local port to a remote service through an SSH server. Useful for accessing internal databases, web UIs, or APIs from your workstation.
Syntax:
Example 1: Forward local port 5050 to remote 4040 via a bastion
Example 2: Access a private PostgreSQL database
Example 3: Forward VNC port and run SSH in background
-N
: Do not execute remote command-f
: Run SSH in background
Troubleshooting:
Ensure
AllowTcpForwarding yes
is set in/etc/ssh/sshd_config
on the remote server.
2. Remote Port Forwarding
Expose a local service to a remote network via the SSH server. Useful for sharing local apps or webhooks with remote/cloud systems.
Syntax:
Example: Expose local port 3000 to remote port 8000
Now, anyone on
remote.host
can access your local app atlocalhost:8000
.
3. Dynamic Port Forwarding (SOCKS Proxy)
Create a local SOCKS proxy to route traffic through the SSH server. Useful for secure browsing, testing, or accessing internal networks.
Syntax:
Example: Start a SOCKS proxy on port 9090
Configure your browser or CLI tool to use
localhost:9090
as a SOCKS5 proxy.
Real-World DevOps Examples
1. Access AWS RDS or Azure SQL via Bastion
2. Forward Kubernetes Dashboard securely
3. Share a local web app with a remote team
Best Practices
Use
-N -f
for background tunnels in automation scriptsAlways restrict forwarding to trusted users/networks
Monitor and audit SSH tunnels in production
Use SSH config (
~/.ssh/config
) to simplify complex tunnelsFor persistent tunnels, consider tools like
autossh
or systemd services
References
Tip: Kill background SSH tunnels with
pkill -f 'ssh -L'
orpkill ssh
as needed.
Last updated