Featured image of post 【zz.ac】设置哪吒探针为系统服务

【zz.ac】设置哪吒探针为系统服务

下午发现上次设置的zz.ac上的哪吒探针离线了,应该是服务器重启导致上次设置的nohp ./nezha-agent -c config.yml 停止运行了。能不能把nezha探针设置为系统服务呢?

当然可以,于是马上行动!

设置了系统服务发现nezha探针还是离线的,运行systemctl --user status nezha.service,报错:

1
2
3
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:ip:8008 established

尝试在文件夹中直接运行: ./nezha-agent -c config.yml ,却是正常的:

1
2
3
4
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文件。

1
2
3
bosh@h1:~/nezha-agent$ cat nezha.env 
Environment="GODEBUG=netdns=go"
Environment="all_proxy=http://[fe80::1%%eth0]:8888"

修改~/.config/systemd/user$ 中的nezha.service为:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[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

运行:

1
2
3
4
5
systemctl --user daemon-reload
systemctl --user stop nezha.service
systemctl --user start nezha.service
systemctl --user status nezha.service
systemctl --user enable nezha.service

完成任务!

😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄

热爱生活 学无止境
使用 Hugo 构建
主题 StackJimmy 设计