使用 Cloudflare Tunnel 穿透内网服务暴露在外网。

原理:在内网服务器上跑一个 cloudflared 进程,它主动向 Cloudflare 边缘网络建立一条加密隧道。外部用户访问你的域名 → Cloudflare 全球网络 → 隧道 → 你的内网服务。全程只需要出站连接,不需要开放任何入站端口。

前置准备

  • Cloudflare 账号
  • 域名托管在 Cloudflare
  • 一台内网服务器

先去 Cloudflare Zero Trust 控制台 → Networks → Tunnels → Create a tunnel,选 Docker 环境,会给你一个 token。

docker run -d \
  --name cloudflared \
  --restart unless-stopped \
  cloudflare/cloudflared:latest \
  tunnel --no-autoupdate run --token YOUR_TUNNEL_TOKEN

回控制台,在 Tunnel 的 Public Hostname 里加规则:

domain.xxx.com → http://localhost:3000

YAML 配置

tunnel: YOUR_TUNNEL_UUID
credentials-file: /etc/cloudflared/credentials.json

ingress:
  # HTTP 服务
  - hostname: domain1.xxx.com
    service: http://localhost:3010
  - hostname: domain2.xxx.com
    service: http://localhost:3011
  # SSH 访问
  - hostname: ssh.xxx.com
    service: ssh://localhost:22
  # 兜底规则(必须放在最后)
  - service: http_status:404

最后一条 http_status:404 是兜底规则:匹配不到前面 hostname 的请求一律 404。不加这条 cloudflared 会报配置错误。

Docker 挂载配置文件启动:

docker run -d \
  --name cloudflared \
  --restart unless-stopped \
  -v /opt/cloudflared:/etc/cloudflared \
  cloudflare/cloudflared:latest \
  tunnel --config /etc/cloudflared/config.yml run

远程 SSH

配好 ssh.xxx.com → ssh://localhost:22 之后,在任何装了 cloudflared 的机器上:

# 安装 cloudflared
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
chmod +x cloudflared-linux-amd64
# 连接
ssh -o ProxyCommand="/mnt/c/Users/xxx/cloudflared-linux-amd64 access ssh --hostname %h" [email protected]
# 密码文件
sshpass -f /mnt/c/Users/xxx/password_home.txt \
ssh \
  -o PreferredAuthentications=password \
  -o PubkeyAuthentication=no \
  -o StrictHostKeyChecking=accept-new \
  -o ProxyCommand='/mnt/c/Users/xxx/cloudflared-linux-amd64 access ssh --hostname %h' \
  [email protected]