[ PROMPT_NODE_24378 ]
Tunnel 设计模式
[ SKILL_DOCUMENTATION ]
# Tunnel 部署模式
## Docker 部署
### 基于令牌 (推荐)
yaml
services:
cloudflared:
image: cloudflare/cloudflared:latest
command: tunnel --no-autoupdate run --token ${TUNNEL_TOKEN}
restart: unless-stopped
### 本地配置
yaml
services:
cloudflared:
image: cloudflare/cloudflared:latest
volumes:
- ./config.yml:/etc/cloudflared/config.yml:ro
- ./credentials.json:/etc/cloudflared/credentials.json:ro
command: tunnel run
## Kubernetes 部署
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: cloudflared
spec:
replicas: 2
selector:
matchLabels:
app: cloudflared
template:
metadata:
labels:
app: cloudflared
spec:
containers:
- name: cloudflared
image: cloudflare/cloudflared:latest
args:
- tunnel
- --no-autoupdate
- run
- --token
- $(TUNNEL_TOKEN)
env:
- name: TUNNEL_TOKEN
valueFrom:
secretKeyRef:
name: tunnel-credentials
key: token
## 高可用性
yaml
# 多台服务器使用相同配置
tunnel:
credentials-file: /path/to/creds.json
ingress:
- hostname: app.example.com
service: http://localhost:8000
- service: http_status:404
在多台机器上运行相同配置。Cloudflare 会自动进行负载均衡。长连接(WebSocket, SSH)在更新期间可能会断开。
## 使用场景
### Web 应用
yaml
ingress:
- hostname: myapp.example.com
service: http://localhost:3000
- service: http_status:404
### SSH 访问
yaml
ingress:
- hostname: ssh.example.com
service: ssh://localhost:22
- service: http_status:404
客户端: `cloudflared access ssh --hostname ssh.example.com`
### gRPC 服务
yaml
ingress:
- hostname: grpc.example.com
service: http://localhost:50051
originRequest:
http2Origin: true
- service: http_status:404
## 基础设施即代码 (IaC)
### Terraform
hcl
resource "random_id" "tunnel_secret" {
byte_length = 32
}
resource "cloudflare_tunnel" "app" {
account_id = var.cloudflare_account_id
name = "app-tunnel"
secret = random_id.tunnel_secret.b64_std
}
resource "cloudflare_tunnel_config" "app" {
account_id = var.cloudflare_account_id
tunnel_id = cloudflare_tunnel.app.id
config {
ingress_rule {
hostname = "app.example.com"
service = "http://localhost:8000"
}
ing