Skip to content

Cloudflare Tunnel

什么时候用

  • 服务跑在非标端口,橙云不支持
  • 不想开任何入站端口
  • 需要隐藏真实 IP
  • 入站链路不稳定

原理:服务器上跑一个 cloudflared主动向外连到 CF,公网请求从 CF 通过这条隧道回来。服务器防火墙可以一个入站端口都不开。

安装

bash
# Debian / Ubuntu
curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb -o /tmp/cloudflared.deb
dpkg -i /tmp/cloudflared.deb

# RHEL 系
curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm -o /tmp/cloudflared.rpm
dnf install -y /tmp/cloudflared.rpm

创建隧道

bash
cloudflared tunnel login          # 输出 URL,浏览器打开授权
cloudflared tunnel create mgmt    # 起个名

配置

/etc/cloudflared/config.yml

yaml
tunnel: <UUID>
credentials-file: /root/.cloudflared/<UUID>.json

ingress:
  - hostname: panel.example.com
    service: https://127.0.0.1:12753
    originRequest:
      noTLSVerify: true             # 后端是自签证书
  - hostname: ssh.example.com
    service: ssh://127.0.0.1:22
  - service: http_status:404        # 兜底,必须有

后端到底是 HTTP 还是 HTTPS,不确定就试:

bash
curl -sI http://127.0.0.1:端口 | head -1
# 返回 400 Bad Request 多半是 HTTPS 端口,service 用 https://

DNS

bash
cloudflared tunnel route dns mgmt panel.example.com
cloudflared tunnel route dns mgmt ssh.example.com

会自动建 CNAME 指向 <UUID>.cfargotunnel.com默认橙云,也必须是橙云。域名已有 A 记录的话加 --overwrite-dns

先手动跑一遍

bash
nohup cloudflared tunnel run mgmt > /tmp/cf.log 2>&1 &
tail -f /tmp/cf.log      # 看到 Registered tunnel connection 就通了

装成服务

bash
cloudflared service install
systemctl enable --now cloudflared

注意:如果当前 SSH 就是走隧道进来的,pkill cloudflared 会把自己踢下线。先 systemctl start 让新进程接管(一个隧道可以多副本),再杀旧的。

健康自愈

cloudflared 偶尔进程活着但连接卡死,systemd 不会重启。加个 cron 检查:

bash
cat > /usr/local/bin/tunnel-check.sh <<'EOF2'
#!/bin/bash
if ! curl -sf --max-time 10 http://127.0.0.1:20241/ready > /dev/null; then
    systemctl restart cloudflared
    logger "cloudflared unhealthy, restarted"
fi
EOF2
chmod +x /usr/local/bin/tunnel-check.sh
# crontab -e 加:*/5 * * * * /usr/local/bin/tunnel-check.sh

/ready 没响应的话在 config.yml 顶部加 metrics: 127.0.0.1:20241

SSH 走隧道

客户端 ~/.ssh/config

Host server
    HostName ssh.example.com
    User root
    ProxyCommand cloudflared access ssh --hostname %h

Windows 上 ProxyCommand 要写 cloudflared.exe 完整路径。

一个原则

改任何管理通道之前,先保证有两条独立的路能进服务器。只有一条路时做加固,是坐在树枝上锯树枝。新通道测通、老通道并存一周,再收。

个人笔记,写给未来忘事的自己。