monit 是轻量可靠的守护进程监控工具,支持进程异常退出、资源超标或端口失联时自动重启、重载或告警;核心配置含识别进程(pidfile/进程名/端口)、启停命令、触发条件三要素。

Monit 是一个轻量、可靠、开箱即用的守护进程监控工具,它不只“发现进程挂了”,而是能在进程异常退出、资源超标或端口失联时,自动执行重启、重载或告警动作——真正实现进程“自动保活”。
核心配置三要素
让 Monit 为某个服务实现自动保活,只需在 /etc/monit.conf 或独立配置文件(如 /etc/monit/conf.d/nginx)中定义三项关键内容:
-
识别进程:通过 pidfile(推荐)、匹配进程名(如
matching "nginx")或监听端口(如if failed port 80 protocol http)准确定位目标进程 -
定义启停命令:提供绝对路径的 start/stop 脚本或系统命令,例如
start program = "/usr/sbin/service nginx start" -
设定触发条件:明确什么情况算“异常”,比如
if does not exist then restart(进程消失)、if totalmem > 80% for 3 cycles then restart(内存持续超限)
常见保活场景配置示例
不同服务可适配不同检测逻辑,以下为典型写法:
-
Nginx 保活:结合 pidfile + 端口连通性双重校验,避免假死漏判
check process nginx with pidfile /var/run/nginx.pid<br> start program = "/usr/sbin/service nginx start"<br> stop program = "/usr/sbin/service nginx stop"<br> if failed port 80 protocol http then restart<br> if 5 restarts within 5 cycles then timeout
-
ZeroTier-One 网络守护:重点验证进程存活与 UDP 端口(9993)监听状态
check process zerotier-one with pidfile /var/run/zerotier-one.pid<br> if failed port 9993 type udp then restart
-
自定义脚本服务:若无标准 pidfile,可用进程名匹配 + 自定义健康检查脚本
check process myapp matching "python.*myapp.py"<br> start program = "/bin/bash -c 'cd /opt/myapp && python3 myapp.py &'<br> if failed exec "/opt/myapp/check_health.sh" then restart
让保活更稳的关键设置
避免误重启或反复震荡,需关注几个实用细节:
-
检测周期合理化:默认 120 秒太慢,生产环境建议设为
set daemon 30(每 30 秒检查一次) -
失败判定加缓冲:用
for 2 cycles或for 3 cycles避免瞬时抖动触发动作 -
防重启风暴:加入
if 3 restarts within 5 cycles then timeout,连续失败后暂停干预,留人工介入窗口 -
日志与通知闭环:配置
set logfile /var/log/monit.log和set alert admin@company.com,确保每次动作可追溯
验证与日常维护
配置完成后别跳过验证步骤:
- 运行
sudo monit -t检查语法是否正确 - 执行
sudo systemctl restart monit加载新规则 - 手动 kill 目标进程(如
sudo kill -9 $(cat /var/run/nginx.pid)),观察是否自动拉起 - 访问
http://your-server:2812查看 Web 界面状态,绿色表示已生效











