+++ date = '2025-11-26T22:02:45+08:00' draft = false title = '无公网IP通过域名访问本地服务' +++ ## 实现目标: 使用域名访问直接部署在本地电脑(Linux)的服务 ## 实现条件: - 有域名(在cloudflare购买或其它服务商购买并使用cloudflare解析DNS) - 无服务器(公网IP) ## 特点: - 只需要一个域名, 快速部署访问, 可作备用 - 但是免费用户延迟较高..特别高... ## 本地部署步骤: ``` # Linux (64-bit) wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -O cloudflared chmod +x cloudflared ./cloudflared tunnel login # 登录Cloudflare账户 ``` 随后点击输出的登录链接, 在浏览器操作, 最后选择域名后, 点击认证, 成功后即可关闭浏览器. ``` # 1. 创建新隧道my-tunnel ./cloudflared tunnel create my-tunnel # 2. 检查凭证文件,应该能看到 my-tunnel.json 文件 ls ~/.cloudflared/ # 3. 将下方配置写入config.yml,注意json的名称为上方ls ~/.cloudflared/的输出 vi ~/.cloudflared/config.yml tunnel: my-tunnel credentials-file: /root/.cloudflared/1c0a168d-4b00-4911-bfb7-5dc5c063ef5f.json ingress: - hostname: yourdomain.com # 你的域名 service: http://localhost:8000 # 本地服务端口 # 默认返回 404(防止未配置的域名被访问) - service: http_status:404 # 4. 绑定需要访问的域名yourdomain.com至my-tunnel # 这会在CloudFlare增加一个CNAME的DNS解析, 与该隧道相关的一个cf子域名 ./cloudflared tunnel route dns my-tunnel yourdomain.com # 5. 运行隧道my-tunnel ./cloudflared tunnel run my-tunnel ``` ## 加入systemctl系统启动: ``` # 1. 增加一个cloudflared-tunnel.service, 配置如下 vi /etc/systemd/system/cloudflared-tunnel.service [Unit] Description=Cloudflare Tunnel for yourdomain.com # 服务描述(自定义) After=network.target # 确保在网络就绪后启动 [Service] # 替换为你的实际命令(确保使用绝对路径), 可以手动执行试验 ExecStart=/root/cloudflared tunnel run my-tunnel Restart=always # 失败时自动重启 User=root # 以root用户运行(根据需要调整) Group=root # 与上面的json配置的路径一致 Environment="TUNNEL_ORIGIN_CERT=/root/.cloudflared/1c0a168d-4b00-4911-bfb7-5dc5c063ef5f.json" [Install] WantedBy=multi-user.target # 多用户环境下启用 ``` 保存后执行后续命令: ``` # 重载 systemd 配置 systemctl daemon-reload # 启动服务 systemctl start cloudflared-tunnel # 设置开机自启 systemctl enable cloudflared-tunnel # 检查状态 systemctl status cloudflared-tunnel ```