配合视频食用口感更佳【Cloudflare内网免费穿透工具使用教程【第六期上】搭建Cloudflare内网穿透服务程上-哔哩哔哩】 https://b23.tv/4hCcavg
安装 cloudflared
这里介绍两种安装 cloudflared 的方式,分别对应不同场景,建议优先采用通过软件源安装方式,建议优先采用deb包的方式安装。
通过软件源安装
以 Ubuntu 20.04 LTS 为例。
国内通过这一方式安装速度较慢,故不再推荐该方式。
1
2
3
4
5
6
7
# 添加源,<RELEASE>内填写版本代号(见下表)
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/ <RELEASE> main' |
sudo tee /etc/apt/sources.list.d/cloudflare-main.list
# 添加GPG Key
sudo curl https://pkg.cloudflare.com/cloudflare-main.gpg -o /usr/share/keyrings/cloudflare-main.gpg
# 安装
apt update&&apt install cloudflared
Ubuntu 版本代号和版本对应表:
代号 版本
Focal 20.04
Xenial 16.04
Wily 15.10
Vivid 15.04
Utopic 14.10
Trusty 14.04
Precise 12.04
通过软件包/二进制文件安装
这一方式无法自动更新 Cloudflared 服务。
现在通过deb包安装的cloudflared也能通过apt服务更新了(会自动添加Key和source到系统中)。
打开 Release 页面并选择对应架构和操作系统的deb、rpm包或二进制文件下载即可。
手动更新:cloudflared update。
配置内网穿透
登录到 Cloudflare Tunnel
1
cloudflared tunnel login
执行后若安装正确则会出现一个登录URL,将该链接复制到任何设备的任何浏览器中登录并选择你想用于内网穿透的域名即可。
成功后会生成证书,放置于~/cloudflared/cert.pem中。
创建隧道
1
cloudflared tunnel create <Tunnel-NAME>
<Tunnel-NAME>即为隧道名称,随便起就可以。
创建配置文件
配置文件的保存位置一般是~/.cloudflared/config.yml,也可以自定义随便在哪都可以。
示例配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef
credentials-file: /root/.cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json
protocol: http2
originRequest:
connectTimeout: 30s
noTLSVerify: false
ingress:
- hostname: gitlab.widgetcorp.tech
service: http://localhost:80
- hostname: gitlab-ssh.widgetcorp.tech
service: ssh://localhost:22
- service: http_status:404
其中ingress字段可以创建多个服务,支持的服务类型如下表,新建其他服务前需要到 Cloudflare 控制台对其他子域名进行解析。
服务名称 描述 service 示例值
HTTP/S 常规网页服务 https://localhost:8000
TCP TCP 连接 tcp://localhost:25565
SSH SSH 连接 ssh://localhost:22
RDP 远程桌面(RDP) rdp://localhost
上表转自 Cloudflare 官方文档,仅节选常用协议,若需要完整版请至 Ingress rules 页面查看。
将隧道解析到域名上
1
cloudflared tunnel route dns <Tunnel-NAME> <SUBDOMAIN>
<Tunnel-NAME>填写刚才创建的隧道,<SUBDOMAIN>填写你想用于内网穿透的子域名(该子域名无需提前创建),执行后会自动将隧道解析到该子域名上。
举例:在刚才的配置文件中配置了两个服务,就需要运行两次:
1
2
cloudflared tunnel route dns <Tunnel-NAME> gitlab.widgetcorp.tech
cloudflared tunnel route dns <Tunnel-NAME> gitlab-ssh.widgetcorp.tech
手动解析其他子域名
打开 Cloudflare 控制台 ,点击左侧网站,点击对应的域名,左侧DNS,找到刚才设置的子域名,将之前自动设置的子域名的解析内容复制到新子域名上就可以。
试运行
1
2
cloudflared --config <config-File> tunnel run <Tunnel-NAME>
# 例:cloudflared --config /root/.cloudflared/config.yml tunnel run mytun
随后稍等一分钟左右,在其他设备上访问刚才解析的子域名测试即可。
注册为系统服务(自动安装)
1
cloudflared service install
注册为系统服务(Systemd)
在/etc/systemd/system下创建cloudflared.service文件:
1
2
3
4
5
6
7
8
9
10
11
12
[Unit]
Description=Cloudflare Tunnel
After=network.target
[Service]
ExecStart=cloudflared --config <config-File> tunnel run <Tunnel-NAME>
Restart=always
RestartSec=5
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
保存退出后systemctl enable cloudflared加入开机启动,systemctl start cloudflared启动服务。
查询日志:journalctl -a -u cloudflared。