用 ssh -L 做本地端口转发

通过 SSH 把远程机器上的服务转发到本地端口——不暴露公网也能访问防火墙后面的开发服务和数据库。

LinuxSSH 远程连接隧道转发低风险
执行 `ssh -L 8080:localhost:3000 user@server`,然后访问 http://localhost:8080 即可到达服务器上的 3000 端口。

01命令

命令
$ ssh -L 8080:localhost:3000 user@server

02作用说明

`ssh -L 本地端口:主机:远程端口 user@server` 的含义是:流量到达本地端口后,经 SSH 隧道送出,再由服务器去连接 主机:远程端口。因为最后一跳是在服务器上发起的,所以可以访问只监听服务器回环地址的服务——`localhost:5432` 就能连到只绑在 127.0.0.1 的 PostgreSQL。不需要 shell 时加 `-N`,想让隧道转入后台就加 `-f`。

03风险

风险低风险
使用条件ssh client and an account on the target server
!注意: 加 `-g` 或绑定 0.0.0.0 会把隧道暴露给整个局域网——除非确有需要,保持默认只监听 localhost。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • ssh(1) — -L local port forwarding
    Ubuntu manpages · technical · 2026-09-17
    依据: Documents -L [bind_address:]port:host:hostport for local forwarding through the SSH connection.

最后验证: 2026-09-17 · 分类: 网络