VPS Tutorials
SSH tunnels on a VPS: local, remote and SOCKS forwarding
Use local SSH forwards for databases and dashboards, remote forwards for private previews and SOCKS for selected applications. Configure persistent tunnels, jump hosts, restricted accounts and the real encryption boundaries.

A database listening only on 127.0.0.1, a private Grafana dashboard and a temporary preview on your laptop all raise the same question: how can an authorized user reach a TCP service without publishing it unnecessarily? OpenSSH's ssh already supports port forwarding. Start with verified SSH key access and confirm that server policy permits the required forwarding.
| Option | Listener | Destination connection |
|---|---|---|
-L | Your SSH client | Made from the SSH server |
-R | The SSH server | Made from your SSH client |
-D | A local SOCKS proxy | Requested destinations reached from the server |
L means Local, R Remote and D Dynamic. Multiple forwardings can share a connection. The listener and the machine that resolves/connects to the destination are different things.
The source's notation is:
ssh -L [本地地址:]本地端口:目标主机:目标端口 用户@跳板服务器
Its 目标主机 means the destination host. Replace all descriptive placeholders with real values; destination names are resolved from the SSH server's perspective.
ssh -N -L 3306:127.0.0.1:3306 [email protected]
Here the client listens on local port 3306 and the server connects to its own 127.0.0.1 port 3306. Use a non-root account authorized for this purpose. -N requests no remote command: the connection is just for forwarding. Explicitly bind local administrative listeners to loopback when writing production commands.
Keep the database private as described in database exposure safety, often listening on 127.0.0.1.
# 本机 3307 转发到服务器的 3306(用 3307 避免和本机已有 MySQL 冲突)
ssh -N -L 3307:127.0.0.1:3306 [email protected]
In Navicat, DBeaver or TablePlus, configure:
- Host:
127.0.0.1. - Local port:
3307, avoiding an existing local MySQL listener. - Credentials: the database's own account, not the SSH account.
ssh -N -L 5433:127.0.0.1:5432 [email protected]
This maps local 5433 to remote PostgreSQL 5432.
ssh -N -L 6380:127.0.0.1:6379 [email protected]
# 另开一个终端
redis-cli -h 127.0.0.1 -p 6380
This maps local 6380 to remote Redis 6379. Redis authentication/ACLs still apply; forwarding does not authorize database operations.
Distinguish 127.0.0.1 from localhost. In some MySQL clients, localhost selects a Unix socket. Use explicit TCP and 127.0.0.1 for the tunnel instead of a localhost connection that may bypass it.
For Grafana, Portainer, Adminer, Metabase or pgAdmin bound privately, for example at 127.0.0.1:3000:
ssh -N -L 3000:127.0.0.1:3000 [email protected]
Open http://localhost:3000 locally. This reduces public exposure, but retain the dashboard's authentication, correct permissions and updates. Other processes on the client can reach the forwarded port; an SSH tunnel does not replace application security. Use ~/.ssh/config below for repeatable setup.
ssh -N -L 8888:127.0.0.1:8888 [email protected]
The same pattern works for Jupyter, Streamlit, Gradio and TensorBoard when their actual listeners and authentication are configured correctly. Keep tokens/passwords enabled and verify the application's bind address rather than assuming defaults.
-N is convenient in a dedicated terminal. Omitting -N also opens a remote session:
ssh -L 3307:127.0.0.1:3306 [email protected]
# 进去之后隧道一直有效,直到你退出这个会话
-f requests backgrounding after authentication:
ssh -f -N -L 3307:127.0.0.1:3306 [email protected]
For long-running connections, -f alone gives little visibility or automatic recovery. Use a supervised foreground process and define how to stop it.
ssh -N -R 8080:127.0.0.1:3000 [email protected]
The remote SSH server listens on 8080; the client connects to its own loopback port 3000. With default policy, curl 127.0.0.1:8080 on the server may work while external access to 203.0.113.10:8080 does not.
Check the effective sshd_config configuration:
#GatewayPorts no ← 官方默认值
GatewayPorts no normally keeps remote forwards on loopback. Publishing to other interfaces requires deliberate policy. The source illustrates clientspecified:
sudo sed -i 's/^#\?GatewayPorts.*/GatewayPorts clientspecified/' /etc/ssh/sshd_config
sudo sshd -t && sudo systemctl reload ssh
The sed only changes a matching main-file line; includes, first-value precedence and Match blocks may control the result. Back up the relevant files, use sshd -t and sshd -T for the intended user/address, and reload the actual ssh/sshd service.
ssh -N -R 0.0.0.0:8080:127.0.0.1:3000 [email protected]
Binding 0.0.0.0 can expose your laptop's service to anyone allowed to reach that server port. Review application credentials, the contents served and host/provider firewalls. Prefer retaining GatewayPorts no: use -R to publish on remote loopback, then an authorized -L connection to consume it; a colleague can establish their own restricted -L connection.
-R also allows a private machine to initiate SSH outward so the server can access its selected service. For managed, long-lived multi-service access, evaluate FRP, Cloudflare Tunnel or Pangolin with their own authentication and exposure policies.
ssh -N -D 1080 [email protected]
Local port 1080 becomes a SOCKS proxy; configure a compatible application using socks5://127.0.0.1:1080. Only applications and traffic configured to use it are proxied, not the whole computer.
Unlike -L, which specifies a destination, -L is fixed per mapping while -D lets the SOCKS client request destinations, subject to server restrictions.
Many clients using socks5:// resolve DNS locally. A supporting client can use socks5h://:
socks5h://127.0.0.1:1080
In Firefox, inspect about:config and network.proxy.socks_remote_dns set to true, plus the actual proxy configuration. DNS behavior is application-specific; test it rather than assuming the proxy covers every lookup.
-D traffic is encrypted across the SSH connection. Ordinary HTTP is still plaintext between the SSH server and the destination; HTTPS retains its end-to-end protection. The local application-to-proxy hop and endpoint security also matter. A SOCKS proxy supplies routing, not universal end-to-end encryption.
Put a host entry in the local ~/.ssh/config:
Host db-tunnel
HostName 203.0.113.10
User root
IdentityFile ~/.ssh/id_ed25519
LocalForward 3307 127.0.0.1:3306
LocalForward 5433 127.0.0.1:5432
ServerAliveInterval 30
ServerAliveCountMax 3
ExitOnForwardFailure yes
SessionType none
Then ssh db-tunnel establishes the two forwards. Replace the host/account/key and make local bind addresses explicit.
- Multiple
LocalForwardlines create multiple local forwards. RemoteForwardcorresponds to-R.SessionType nonecorresponds to-Non a supporting client.ServerAliveInterval 30sends encrypted keepalives; the count controls when missing replies close the session.ExitOnForwardFailure yesexits when a requested listener cannot be established.
ExitOnForwardFailure does not prove the ultimate service will answer: destination connections occur later. Test the application too. Put specific Host blocks before broad defaults and inspect supported options on older clients.
Network changes, idle timeouts and peer restarts can break a tunnel. A supervisor can restart the foreground process. autossh remains an alternative to evaluate; the source's cited July 2024 commit date alone does not prove abandonment and is not a current maintenance assessment.
Example unit at /etc/systemd/system/db-tunnel.service:
[Unit]
Description=SSH Tunnel for remote database access
After=network-online.target
Wants=network-online.target
[Service]
User=tunnel
ExecStart=/usr/bin/ssh -NT \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 \
-o ServerAliveCountMax=3 \
-o StrictHostKeyChecking=accept-new \
-i /home/tunnel/.ssh/id_ed25519 \
-L 127.0.0.1:3307:127.0.0.1:3306 \
[email protected]
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Before using it, create the local tunnel account/home and authorize its separate restricted key on the remote account. Ensure ownership, readable key/config and noninteractive authentication work. Verify and install the server host key through a trusted channel; prefer StrictHostKeyChecking=yes with a prepared known_hosts rather than treating accept-new as prior identity verification. Add BatchMode=yes so failed credentials exit instead of waiting for input. Personal passphrase protection and unattended service keys require different handling.
sudo systemctl daemon-reload
sudo systemctl enable --now db-tunnel
The loopback address 127.0.0.1 in -L 127.0.0.1:3307:... prevents accidental LAN publication at 0.0.0.0. The network-online.target dependencies improve startup ordering but do not guarantee that the remote peer is reachable; keep reconnects and inspect journalctl -u db-tunnel. Test systemctl stop, reboot behavior and a real database connection.
ssh -J [email protected]:22 [email protected]
-J has been supported since OpenSSH 7.3. Verify both host identities and configure both accounts:
Host internal-server
HostName 10.0.0.5
User deploy
ProxyJump [email protected]
IdentityFile ~/.ssh/id_ed25519
Forwarding can pass through the jump connection:
ssh -J [email protected] -N -L 3307:127.0.0.1:3306 [email protected]
The destination 127.0.0.1 belongs to the final server, 10.0.0.5. The jump host relays the SSH connection; it is not the database endpoint in this example.
Forwarding uses server-side network reachability and permissions. It can reach another internal host if the SSH server can reach it and policy allows it; it is not limited to that server's own ports. Application credentials still govern operations.
Avoid broad GatewayPorts yes, or clientspecified with 0.0.0.0, without an explicit publication decision. Inspect AllowTcpForwarding: the upstream default yes may be changed by your image or policy. In shared environments, restrict users/groups in sshd_config:
AllowTcpForwarding no
Match Group tunnelusers
AllowTcpForwarding yes
This broad group example is a starting point, not a complete restricted account. Existing shell access can let a user implement other forwarding methods, so an SSH option alone is not isolation.
Use a dedicated account for unattended tunnels. A nologin shell may work with -N, but PAM/account policy differs; test the installed system. The source's authorized_keys example uses command= and permitopen=:
command="/bin/false",no-pty,no-agent-forwarding,permitopen="127.0.0.1:3306" ssh-ed25519 AAAA... tunnel-key
permitopen limits local/dynamic destination connections, not remote forwarding listeners. For a tunnel intended only for this database, additionally restrict the server account, for example:
Match User tunnel
AllowTcpForwarding local
PermitOpen 127.0.0.1:3306
PermitListen none
AllowStreamLocalForwarding no
X11Forwarding no
AllowAgentForwarding no
PermitTTY no
ForceCommand /bin/false
Validate version support and effective settings before reload, retain administrative recovery and prove that forbidden destinations, reverse forwards and shell sessions fail. Replace the truncated public key with a complete verified key. A forced command does not run for a forwarding-only -N session; never remove -N from the service without reviewing this policy.
A TCP/SOCKS tunnel does not create a general network interface, though it can reach explicitly allowed internal TCP destinations. For routed multi-host networking, consider WireGuard or Tailscale/Headscale.
bind: Address already in use: choose another local port or find the listener:
# Linux / macOS
sudo ss -lntp 'sport = :3307'
# Windows
netstat -ano | findstr :3307
ss is a Linux tool; use lsof -nP -iTCP:3307 -sTCP:LISTEN on macOS. The Windows example identifies a PID. See port conflicts.
channel 2: open failed: connect failed: Connection refused: check the destination from the machine that makes that connection:
# 在服务器上执行
sudo ss -lntp 'sport = :3306'
For a local forward, inspect the SSH server's listener, address and Docker publication/network. For -R, the destination connection is client-side. Connection refused often means no listener, but explicit network rejects are also possible.
channel 3: open failed: administratively prohibited: inspect effective sshd_config / AllowTcpForwarding and key restrictions in authorized_keys, including permitopen and no-port-forwarding.
SSH connects but the application fails: check in this order:
- Enable
ExitOnForwardFailure yesto catch listener establishment failures. - Verify the destination listener with
sson the correct side. - Point the client at
127.0.0.1;localhostmay select a socket or another address. - Use the actual forwarded local port, then check application credentials and protocol.
Intermittent disconnection: ServerAliveInterval 30 can help idle handling; inspect logs and SSH connection drops. Permission denied (publickey) is SSH authentication failure before forwarding; use Permission denied diagnosis.
Is traffic encrypted? The SSH hop is encrypted. Any onward connection needs its own TLS when required; do not generalize a private same-host MySQL example to untrusted remote database traffic.
Can others share my tunnel? A listener at 0.0.0.0 may let others exercise your access. Prefer individual identities and restricted local listeners; application audit should identify users independently.
How much overhead is there? It depends on cipher, CPU, network latency and storage. The source's 10–20% example is not a measured promise. Measure your workload instead of assuming a fixed penalty.
Does it forward UDP? Ordinary -L/-R/-D forwarding carries TCP, not a general UDP tunnel. Use suitable routed networking for UDP requirements.
Does it survive reboot? A correctly configured service with enable can restart; a manual ssh -L process does not recreate itself. It must regain network and authentication successfully.
Windows support? Install/verify OpenSSH Client on a supported Windows version. Options are similar; use the correct Windows paths and quoting. Graphical clients such as MobaXterm or Termius may manage tunnels, subject to their storage and access settings.
Which tool fits?
- A few authorized temporary ports: SSH forwarding when existing policy permits it.
- Longer-lived service access: evaluate FRP or Cloudflare Tunnel.
- Network connectivity: evaluate WireGuard or Tailscale.
Each needs a deliberate identity and exposure policy; SSH may still need server configuration even if no new daemon is installed.
- SSH key authentication — establish restricted credentials.
- Keep databases off the public internet.
- SSH disconnection diagnosis.
- FRP for managed reverse access.
- WireGuard networking.