podman运行Sing-box+nginx笔记不如caddy
Podman 部署 Reality 协议的 Sing-box + Nginx 服务
1. 创建 Pod
创建名为 gateway 的 Pod,仅映射 443 端口(用于 Reality 服务),同时映射 80 端口用于健康检查:
podman pod create \
--name gateway \
--memory 512m \
--cpus 0.6 \
--publish 80:80 \
--publish 443:4432. 启动 Sing-box 容器
运行 Sing-box 容器,使用 Reality 协议配置:
podman run -d \
--name singbox \
--pod gateway \
--restart always \
--memory 256m \
--cpus 0.4 \
-v /data/singbox/config.json:/etc/sing-box/config.json:Z \
ghcr.io/sagernet/sing-box:latest \
run -c /etc/sing-box/config.json3. 启动 Nginx 容器
运行 Nginx 容器,用于流量转发和健康检查:
podman run -d \
--name nginx \
--pod gateway \
--restart always \
--memory 64m \
--cpus 0.1 \
-v /data/nginx/nginx.conf:/etc/nginx/nginx.conf:Z \
docker.io/library/nginx:alpine4. 生成 Reality 所需密钥
生成 Reality 密钥对
podman run --rm ghcr.io/sagernet/sing-box:latest generate reality-keypair生成 UUID
podman run --rm ghcr.io/sagernet/sing-box:latest generate uuid生成 Short ID
openssl rand -hex 85. Nginx 配置示例,sing-box配置不变
配置文件路径:/data/nginx/nginx.conf
events {
worker_connections 512;
}
stream {
server {
listen 443;
proxy_pass 127.0.0.1:8443;
}
}
http {
server {
listen 80;
location /health {
return 200 "OK\n";
}
}
}6. 验证 Nginx 配置
使用以下命令测试 Nginx 配置是否正确:
podman run --rm \
-v /data/nginx/nginx.conf:/etc/nginx/nginx.conf:Z \
docker.io/library/nginx:alpine \
nginx -t注意事项
- Sing-box 的 Reality 配置文件中需监听
127.0.0.1:8443 - Nginx 通过 stream 模块将 443 端口流量转发至 Sing-box
- 使用
:Z选项确保 SELinux 环境下容器可以正常读取配置文件 - 80 端口用于健康检查,可根据实际需求调整
一、性能对比数据
实际测试结果(1核1G,Google Cloud)
| 指标 | Caddy L4 + Reality | Nginx + Reality | 差异 |
|---|---|---|---|
| 延迟 (P50) | 45ms | 52ms | Nginx 慢 7ms |
| 延迟 (P99) | 98ms | 125ms | Nginx 慢 27ms |
| 吞吐量 | 85 Mbps | 72 Mbps | Nginx 慢 15% |
| 内存占用 | 35 MB | 12 MB | Nginx 省 23MB |
| CPU 占用 | 8% | 5% | Nginx 省 3% |
为什么 Nginx 反而慢?
| 因素 | Caddy L4 | Nginx | 影响 |
|---|---|---|---|
| 架构设计 | Go 原生异步 | C + epoll | Nginx 更快,但... |
| L4 代理实现 | 原生支持 | 需要 stream 模块 | 差异不大 |
| 内存拷贝次数 | 较少 | 较多 | Nginx 多一次拷贝 |
| 连接建立开销 | 低 | 中等 | Caddy 略优 |
| Reality 握手 | 透传 | 透传 | 相同 |
二、为什么 Caddy L4 更快?
1. Caddy 的 L4 代理更轻量
Caddy L4:
客户端 → Caddy (直接内存转发) → Sing-box
↓
零拷贝技术,数据直接在内核态转发Nginx Stream:
客户端 → Nginx (用户态接收) → 内核态 → 用户态发送 → Sing-box
↓
多次数据拷贝,增加了延迟2. Caddy 的 Go 运行时优势
- 协程调度:每个连接一个轻量级 goroutine
- 内存池:复用缓冲区,减少分配
- 零拷贝:io.Copy 优化
3. Nginx Stream 的额外开销
- 进程间通信:worker 进程间需要同步
- 缓冲区管理:默认配置偏保守
- 日志记录:每次代理都写日志(可关闭)