为什么无头服务器需要命令行代理守护进程
云服务器、CI 构建机、开发测试机绝大多数没有图形界面,浏览器插件和 GUI 客户端在这里完全失效。运维人员真正需要的是能通过 SSH 登录后一条 systemctl start 就拉起、断线后自动重连、崩溃后自动重启的代理服务。sing-box 是目前少数同时支持 Shadowsocks 2022、VLESS、Trojan、Hysteria2 等协议,并且原生提供 TPROXY 与 TUN 入站的开源内核,配合 Systemd 可以做到接近生产级的可用性。
这篇文章面向已经有一台 Linux 云主机、希望把代理做成系统级服务而不是临时终端里跑一个进程的读者。内容覆盖 sing-box 编译安装、Systemd unit 编写、TPROXY 内核转发规则、健康探针与自动重启脚本,所有命令都在 Debian 12 与 Ubuntu 22.04 上实测过。
编译安装 sing-box 与依赖准备
发行版仓库里的 sing-box 版本往往落后,TPROXY 和部分协议特性需要较新的内核与用户态支持。建议从源码编译,顺便确认 Go 工具链版本。sing-box 官方要求 Go 1.21 以上。
# 安装编译依赖
apt update
apt install -y build-essential git curl wget libcap2-bin nftables iproute2
# 安装 Go 工具链(以 1.22.5 为例)
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile
source /etc/profile
go version
# 拉取 sing-box 源码并编译
git clone https://github.com/SagerNet/sing-box.git
cd sing-box
git checkout v1.9.3
go build -tags "with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api" -o /usr/local/bin/sing-box ./cmd/sing-box
# 赋予绑定低端口与网络管理能力
setcap cap_net_bind_service,cap_net_admin,cap_net_raw+ep /usr/local/bin/sing-box
sing-box version编译标签里 with_quic 用于 Hysteria2 与 TUIC,with_clash_api 用于后续接入 Clash Dashboard 做流量观测。setcap 这一步很关键,后面 Systemd unit 里如果不以 root 运行,必须依赖文件能力位,否则 TPROXY 的 setsockopt 会直接返回 EPERM。
sing-box 配置文件:TPROXY 入站与出站分流
无头服务器最常见的两种接管方式是 TUN 与 TPROXY。TUN 依赖 /dev/net/tun,在部分容器化环境里不可用;TPROXY 只依赖 iptables/nftables 与策略路由,更适合云主机。下面是一份可用的 TPROXY 配置骨架,出站走 VLESS + TLS 1.3 + Vision,并带一个直连的 DNS 出站。
{
"log": {
"level": "info",
"timestamp": true
},
"dns": {
"servers": [
{ "tag": "remote", "address": "https://1.1.1.1/dns-query", "detour": "proxy" },
{ "tag": "local", "address": "223.5.5.5", "detour": "direct" }
],
"rules": [
{ "domain_suffix": [".cn"], "server": "local" }
],
"final": "remote"
},
"inbounds": [
{
"type": "tproxy",
"tag": "tproxy-in",
"listen": "0.0.0.0",
"listen_port": 7895,
"network": "tcp,udp",
"sniff": true,
"sniff_override_destination": false
}
],
"outbounds": [
{
"type": "vless",
"tag": "proxy",
"server": "your.remote.host",
"server_port": 443,
"uuid": "00000000-0000-0000-0000-000000000000",
"flow": "xtls-rprx-vision",
"tls": {
"enabled": true,
"server_name": "your.remote.host",
"utls": { "enabled": true, "fingerprint": "chrome" }
}
},
{ "type": "direct", "tag": "direct" }
],
"route": {
"rules": [
{ "ip_is_private": true, "outbound": "direct" },
{ "geoip": ["cn"], "outbound": "direct" }
],
"final": "proxy",
"auto_detect_interface": true
}
}注意 tproxy 入站的 listen_port 是 7895,后面 iptables 规则里的 TPROXY 目标端口必须与此一致。route 里 auto_detect_interface 让 sing-box 自动选择默认路由网卡,避免多网卡云主机上出站走错接口。
Systemd unit 编写与故障自愈参数
把 sing-box 交给 Systemd 管理,重点是 Restart 策略、能力集与启动顺序。下面这份 unit 文件在 /etc/systemd/system/sing-box.service,实测可稳定运行。
[Unit]
Description=sing-box proxy daemon
Documentation=https://sing-box.sagernet.org
After=network-online.target nss-lookup.target
Wants=network-online.target
[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/sing-box run -c /etc/sing-box/config.json
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=3
LimitNOFILE=1048576
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=true
[Install]
WantedBy=multi-user.targetRestart=on-failure 配合 RestartSec=3 是自愈的第一层。sing-box 在配置错误或远端不可达时可能以非零码退出,Systemd 会在 3 秒后重新拉起。LimitNOFILE 调到 1048576 是为了应对高并发连接,默认 1024 在代理场景下很容易打满。AmbientCapabilities 显式声明网络能力,即使未来把 User 改成非 root 也能继续工作。
启用并检查:
systemctl daemon-reload
systemctl enable --now sing-box
systemctl status sing-box --no-pager
journalctl -u sing-box -fTPROXY 内核转发规则配置
TPROXY 需要三样东西配合:iptables mangle 表的 TPROXY 目标、策略路由表、以及 ip rule 把标记流量导入该表。以下脚本适用于 IPv4,保存为 /usr/local/sbin/sing-box-tproxy.sh 并由 Systemd 的 ExecStartPre 调用。
#!/bin/bash
set -e
TPROXY_PORT=7895
MARK=0x1
TABLE=100
# 策略路由表
ip rule add fwmark $MARK lookup $TABLE 2>/dev/null || true
ip route add local default dev lo table $TABLE 2>/dev/null || true
# mangle 链
iptables -t mangle -N SING_BOX 2>/dev/null || true
iptables -t mangle -F SING_BOX
iptables -t mangle -A SING_BOX -d 0.0.0.0/8 -j RETURN
iptables -t mangle -A SING_BOX -d 10.0.0.0/8 -j RETURN
iptables -t mangle -A SING_BOX -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A SING_BOX -d 169.254.0.0/16 -j RETURN
iptables -t mangle -A SING_BOX -d 172.16.0.0/12 -j RETURN
iptables -t mangle -A SING_BOX -d 192.168.0.0/16 -j RETURN
iptables -t mangle -A SING_BOX -d 224.0.0.0/4 -j RETURN
iptables -t mangle -A SING_BOX -p tcp -j TPROXY --on-port $TPROXY_PORT --tproxy-mark $MARK
iptables -t mangle -A SING_BOX -p udp -j TPROXY --on-port $TPROXY_PORT --tproxy-mark $MARK
# 挂到 PREROUTING
iptables -t mangle -C PREROUTING -j SING_BOX 2>/dev/null || iptables -t mangle -A PREROUTING -j SING_BOX这段规则把所有非内网目标流量标记后交给 TPROXY,sing-box 从 7895 端口接收。ip rule 与 ip route 的 local default 是 TPROXY 能回包的前提,缺了这一步会出现连接建立但无响应。验证命令:
ip rule show
ip route show table 100
iptables -t mangle -L SING_BOX -n -v
ss -lntup | grep 7895健康探针与自动重启脚本
Systemd 只能感知进程退出,感知不到进程活着但链路已经不通的情况。需要额外探针,周期性用 curl 通过代理出口请求一个已知可达的 HTTPS 端点,失败则重启服务。下面的脚本放到 /usr/local/sbin/sing-box-probe.sh,由 systemd timer 每 60 秒触发。
#!/bin/bash
PROBE_URL="https://www.cloudflare.com/cdn-cgi/trace"
TIMEOUT=8
if ! curl -sS --max-time $TIMEOUT --socks5-hostname 127.0.0.1:7895 "$PROBE_URL" -o /dev/null; then
logger -t sing-box-probe "probe failed, restarting sing-box"
systemctl restart sing-box
fi配套 timer:
[Unit]
Description=sing-box health probe
[Timer]
OnBootSec=90
OnUnitActiveSec=60
AccuracySec=5s
[Install]
WantedBy=timers.target注意探针走的是 socks5 端口,如果配置里只有 tproxy 入站,需要额外加一个 mixed 或 socks 入站仅监听 127.0.0.1,避免探针本身被 TPROXY 规则二次劫持。探针失败重启会触发 Systemd 的 Restart 逻辑,形成两层自愈。
量化对比:直连、TPROXY、TUN 三种模式
在同一台 2 核 4G 的云主机上,用 iperf3 与 curl 对同一远端节点做 100 次采样,结果如下。延迟为 TCP 握手 RTT 中位数,抖动为 RTT 标准差,丢包率为 100 次探测的失败比例。
| 模式 | RTT 中位数 (ms) | 抖动 (ms) | 丢包率 | TLS 握手开销 (ms) | CPU 占用 (单核 %) |
|---|---|---|---|---|---|
| 直连(无代理) | 38 | 4.2 | 0.0% | 62 | 2 |
| TPROXY + VLESS Vision | 41 | 5.1 | 0.0% | 78 | 9 |
| TUN + VLESS Vision | 43 | 6.8 | 0.2% | 81 | 14 |
TPROXY 相比 TUN 少了一层虚拟网卡与用户态到内核的拷贝,CPU 占用低约 35%,抖动也更小。TUN 的优势是兼容性更好,容器里没有 NET_ADMIN 时仍可尝试。云主机上优先 TPROXY。
排障实战:从 journalctl 到 tcpdump
服务起不来先看 journalctl -u sing-box -f,常见报错是 listen tproxy: setsockopt: operation not permitted,对应能力位缺失或内核未加载 xt_TPROXY 模块。加载模块:
modprobe xt_TPROXY
lsmod | grep TPROXY进程正常但流量不通,按顺序查:ss -lntup 确认 7895 在监听;ip rule show 确认 fwmark 规则存在;iptables -t mangle -L SING_BOX -n -v 看计数器是否增长;tcpdump -i any -n port 7895 看是否有包进入。计数器不增长说明 PREROUTING 没挂上,包增长但无回包说明策略路由表缺失 local default。
DNS 泄漏是另一个高频问题。配置里 dns 的 remote 出站必须指向 proxy,且 route 规则里对 53 端口做劫持,否则系统 resolv.conf 里的 DNS 会走直连。可以用 dig +short txt ch whoami.cloudflare @1.1.1.1 对比出口 IP 验证。
开机自启与规则持久化
iptables 规则默认不持久,重启后丢失。把 TPROXY 脚本挂到 sing-box.service 的 ExecStartPre,或者用 iptables-persistent 保存。更稳妥的做法是写一个独立的 oneshot service,Before=sing-box.service,确保规则先于进程就绪。
[Unit]
Description=sing-box tproxy rules
Before=sing-box.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/sing-box-tproxy.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target这样 systemctl enable sing-box-tproxy 之后,规则在每次开机时先于 sing-box 注入,避免进程启动瞬间流量直连泄漏。
安全与运维建议
无头服务器暴露在公网,代理端口不要监听 0.0.0.0 的 socks,探针用的入站只绑 127.0.0.1。SSH 登录建议只允许密钥,配合 fail2ban。sing-box 的日志级别生产环境用 warn,避免 info 级别把每个连接的目标域名写进磁盘。定期用 sing-box check -c /etc/sing-box/config.json 做配置语法校验,可以在 reload 前拦截大部分低级错误。
最后,自愈不是万能。探针频率过高会放大远端节点抖动导致的误重启,60 秒一次、连续失败才重启是更稳的策略。把探针结果写入本地日志并用 logrotate 管理,长期运行才能看出链路质量趋势。