安装 cloudflared
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
mv cloudflared-linux-amd64 cloudflared
chmod +x cloudflared
sudo mv cloudflared /usr/local/bin/
cloudflared --version
登录 Cloudflare
cloudflared tunnel login
执行后浏览器会打开,选择你的域名授权。
成功后会生成:
~/.cloudflared/cert.pem
创建 Tunnel
cloudflared tunnel create my-tunnel
创建成功后会输出类似:
Tunnel credentials written to ~/.cloudflared/<UUID>.json
这里要记住 Tunnel 的 UUID。
编写配置文件
mkdir -p ~/.cloudflared
nano ~/.cloudflared/config.yml
也可以先看看在 /etc/cloudflared/config.yml 里的配置,如果这个文件已经存在了,则不需要在 ~/.cloudflared/config.yml 里配置。
单站点配置
tunnel: <UUID>
credentials-file: /root/.cloudflared/<UUID>.json
ingress:
- hostname: example.com
service: http://127.0.0.1:3000
- hostname: www.example.com
service: http://127.0.0.1:3000
- service: http_status:404
单子域配置
如果你只想暴露一个子域,例如 app.example.com:
tunnel: <UUID>
credentials-file: /root/.cloudflared/<UUID>.json
ingress:
- hostname: app.example.com
service: http://127.0.0.1:3000
- service: http_status:404
绑定 DNS 到 Tunnel
推荐直接用命令创建 DNS:
cloudflared tunnel route dns my-tunnel example.com
cloudflared tunnel route dns my-tunnel www.example.com
如果手工在 Cloudflare DNS 面板添加,记录应为:
CNAME example.com -> <UUID>.cfargotunnel.com
CNAME www.example.com -> <UUID>.cfargotunnel.com
前台测试 Tunnel
正式托管前先前台运行一次:
cloudflared tunnel run my-tunnel
确认以下几点:
- 命令启动后没有报错
- 日志显示 Tunnel 已连接成功
- 访问域名可以正常返回服务内容
安装为 systemd 服务
sudo cloudflared service install
sudo systemctl enable cloudflared
sudo systemctl restart cloudflared
sudo systemctl status cloudflared
上线后验证
cloudflared tunnel list
cloudflared tunnel info my-tunnel
journalctl -u cloudflared -n 100 --no-pager
curl -I http://127.0.0.1:3000
curl -I https://example.com
curl -I https://www.example.com
上线前检查项
- 本地服务端口确实在监听
config.yml里的hostname和实际访问域名完全一致credentials-file路径和实际生成的json文件一致- 如果根域和
www都要访问,就都要配置DNS + ingress - 保底路由
- service: http_status:404必须保留
最常见问题
只配了 www,没配根域
如果你访问的是 example.com,那 DNS 和 ingress 里都必须有 example.com 这一条。
本地服务端口写错
例如服务实际跑在 8080,但配置里写成了 3000,那么 Tunnel 是通的,但请求会转发失败。
域名和 ingress 不一致
例如只配置了:
- hostname: www.example.com
那直接访问:
https://example.com
仍然会失败。
排障时建议直接提供的文件和命令输出
如果后续需要进一步定位问题,优先收集这三样:
~/.cloudflared/config.ymlsudo systemctl status cloudflaredjournalctl -u cloudflared -n 100 --no-pager
文章标签
冬眠
博主专注于技术、阅读与思考。在这里记录学习、思考与生活。
系列:Cloudflare Tunnel
第 1 篇,共 2 篇
