zzac设置哪吒探针为系统服务
下午发现上次设置的zz.ac上的哪吒探针离线了,应该是服务器重启导致上次设置的nohp ./nezha-agent -c config.yml 停止运行了。能不能把nezha探针设置为系统服务呢?
当然可以,于是马上行动!
设置了系统服务发现nezha探针还是离线的,运行systemctl --user status nezha.service,报错:
Jan 06 07:35:47 h1.lab.zz.ac nezha-agent[14737]: NEZHA@2026-01-06 07:35:47>> 上报系统信息失败: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing: dial tcp ip:8008: connect: network is un>
Jan 06 07:35:57 h1.lab.zz.ac nezha-agent[14737]: NEZHA@2026-01-06 07:35:57>> Try to reconnect ...
Jan 06 07:35:57 h1.lab.zz.ac nezha-agent[14737]: NEZHA@2026-01-06 07:35:57>> Connection to ip:8008 established尝试在文件夹中直接运行: ./nezha-agent -c config.yml ,却是正常的:
I: 08:35:51 NEZHA@2026-01-06 08:35:51>> Connection to ip:8008 established
I: 08:35:52 NEZHA@2026-01-06 08:35:52>> 正在更新本地缓存IP信息
I: 08:35:56 NEZHA@2026-01-06 08:35:56>> 正在更新本地缓存IP信息
I: 08:35:59 NEZHA@2026-01-06 08:35:59>> 正在更新本地缓存IP信息
询问Gmini ,为什么会发生这种情况:
为什么直接运行正常,但
systemctl --user却不行?主要有三个“隐形地雷”:
- 变量被丢弃 (Specifier Collision): 你的代理地址包含
%(如%eth0或%25eth0)。在systemd配置文件中,%是特殊占位符。systemd尝试解析它发现不符合规则,于是报Invalid slot错误并直接丢弃了该变量。没有了代理环境变量,哪吒 Agent 尝试直连面板 IP,导致网络不可达。- 环境隔离性: 直接在 Shell 运行会继承当前会话的所有
export变量;而systemd --user运行在一个相对干净的“沙盒”环境中,它不会读取你的.bashrc或当前 Shell 的变量。
经过多次和gemini 沟通,终于找到解决方案,在nezha-agent中新建一个nezha.env文件。
bosh@h1:~/nezha-agent$ cat nezha.env
Environment="GODEBUG=netdns=go"
Environment="all_proxy=http://[fe80::1%%eth0]:8888"
修改~/.config/systemd/user$ 中的nezha.service为:
[Unit]
Description=nezha-agent
# 确保在网络就绪后再尝试启动
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# 设置你的程序工作目录
WorkingDirectory=/home/bosh/nezha-agent
# 指向我们之前创建的包装脚本
ExecStart=/bin/bash /home/bosh/nezha-agent/start.sh
# --- 资源限制优化 ---
# 解决你之前遇到的 256 限制问题
LimitNOFILE=65535
LimitNPROC=infinity
TasksMax=infinity
# --- 自动重启配置 ---
Restart=always
RestartSec=5
[Install]
# 这是解决你报错的关键:允许服务在用户登录(或开启 linger)时自动启动
WantedBy=default.target
运行:
systemctl --user daemon-reload
systemctl --user stop nezha.service
systemctl --user start nezha.service
systemctl --user status nezha.service
systemctl --user enable nezha.service