【笔记】Cloudflare内网穿透

前言

Cloudflare内网穿透

准备工作

  • 在Cloudflare已经绑定一个域名

下载cloudflared

MacOS

1
brew install cloudflared

登陆Cloudflare并为域名授权Tunnel

1
cloudflared tunnel login
  • 接下来会自动打开浏览器,如果当前操作系统没有GUI,可以将URL复制到其他系统的浏览器进行登陆
1
2
3
4
5
A browser window should have opened at the following URL:

https://dash.cloudflare.com/argotunnel?aud=&callback=https%3A%2F%2Flogin.cloudflareaccess.org%2Fxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D

If the browser failed to open, please visit the URL above directly in your browser.
  • 登陆Cloudflare账号->选择一个域名->授权

  • 等待授权完成

  • 此时本地会提示授权成功,并自动生成了证书
1
2
3
4
5
6
7
8
A browser window should have opened at the following URL:

https://dash.cloudflare.com/argotunnel?aud=&callback=https%3A%2F%2Flogin.cloudflareaccess.org%2Fxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D

If the browser failed to open, please visit the URL above directly in your browser.
You have successfully logged in.
If you wish to copy your credentials to a server, they have been saved to:
~/.cloudflared/cert.pem

创建tunnel

<tunnel_name>:自定义一个tunnel名称,用于区分不同的tunnel

1
cloudflared tunnel create <tunnel_name>
  • 创建tunnel成功后会得到一个随机的UUID作为tunnel的id,并且会自动创建以tunnel的id为文件名的证书配置文件

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:记下你的tunnel的id
~/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json:记下你的tunnel证书配置文件的路径

1
2
3
Tunnel credentials written to ~/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json. cloudflared chose this file based on where your origin certificate was found. Keep this file secret. To revoke these credentials, delete the tunnel.

Created tunnel mbp with id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

域名解析

  • 在Cloudflare控制台为这个域名创建一个CNAME类型的解析记录,记录名称任意设置,但是要与下文保持一致,记录值为xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.cfargotunnel.com

开启tunnel

  • 创建一个.yaml配置文件,配置文件名自定义

tunnel:填写刚刚记下的tunnel的id
credentials-file:填写刚刚记下的证书配置文件路径
ingress:在公网访问tunnel的域名的配置,每一条配置表示一个映射

hostname: test.example.comservice: http://localhost:80:当访问你的域名test.example.com时,自动映射到内网的http://127.0.0.1:80服务

example.com:你的域名
test:子域名,CNAME类型的记录的名称
http://localhost:80:本机地址以及端口号,如果HTTP服务不在80端口可以改为其他端口

service: http_status:404:当域名访问的资源有误时,自动跳转到Cloudflare公共的404页面

.yaml
1
2
3
4
5
6
7
tunnel: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
credentials-file: ~/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json

ingress:
- hostname: test.example.com
service: http://127.0.0.1:80
- service: http_status:404

完成

  • 截图纪念

参考文献

CSDN——运维之美