Monit 服务进程监控指南

972 阅读8分钟

Monit 服务进程监控指南

一、Monit 简介

Monit 是一款开源的系统和服务监控工具,能够实时监测服务器的各项指标,包括 CPU、内存、磁盘使用情况等,尤其擅长对服务进程进行监控。当被监控的进程出现异常(如进程停止、崩溃、占用资源过高)时,Monit 可以自动采取相应措施,如重启进程、发送警报通知管理员,有效保障服务器的稳定运行。

目前Monit暂支持Unix OS相关系统,暂不支持 Windows~

二、安装 Monit

方法 1:基于包管理工具安装

(一)基于 OS x 系统

Homebrew 是 macOS 上最常用的包管理工具,可以方便地安装 Monit。

  1. 安装 Monit:
snackpub@snackpubdeMacBook-Pro ~ % sudo brew install monit

# 验证安装
snackpub@snackpubdeMacBook-Pro ~ % monit -V 

This is Monit version 5.34.4
Built with ssl, with ipv6, with compression, with pam and with large files
Copyright (C) 2001-2025 Tildeslash Ltd. All Rights Reserve

// brew uninstall monit
(二)基于 CentOS 系统
  1. 安装 EPEL 仓库(Extra Packages for Enterprise Linux),Monit 软件包位于此仓库中:
sudo yum install epel - release

2. 安装 Monit:

sudo yum install monit

3. 基础命令


# 查看版本
sudo monit -V

# 语法检测
sudo monit -t

# -I 选项的作用是让 Monit 以守护进程的方式在后台运行。
sudo monit -I

# 启动monit
sudo monit start all

# 查看状态
sudo monit status
sudo monit status all

# 重新加载监视器
sudo monit reload
# 启动 Monit 时使用 -d 选项来指定轮询时间,设置轮询时间为 60 秒
sudo monit -d 60 -I


# 查看所有服务 
sudo monit summary

sudo lsof -i :8081

方法 2:手动编译安装

下载 Monit 源码
访问 Monit 官方网站 下载最新版本的源码包(如 monit-5.32.0.tar.gz

解压源码包

tar -xzf monit-5.32.0.tar.gz
cd monit-5.32.0

编译和安装

./configure
make
sudo make install

验证安装

monit -V    

可能的错误:

./configure checking for SSL support... enabled checking for SSL include 
directory... Not found Couldn't find your SSL header files. Use --with-ssl-incl-
dir option to fix this problem or disable the SSL support with --without-ssl

在编译 Monit 时,如果遇到 SSL header files not found 的错误,说明系统缺少 OpenSSL 的开发头文件(openssl-dev 或 openssl-devel)。以下是解决此问题的步骤

验证openssl安装

brew info openssl

记下 OpenSSL 的安装路径,例如 /usr/local/opt/openssl

配置 Monit 使用 OpenSSL

在编译 Monit 时,指定 OpenSSL 的头文件和库文件路径。

1. 使用 --with-ssl-incl-dir 和 --with-ssl-lib-dir

运行 ./configure 时,添加以下选项:

./configure --with-ssl-incl-dir=/usr/local/opt/openssl/include \
           --with-ssl-lib-dir=/usr/local/opt/openssl/lib

2. 禁用 SSL 支持(不推荐)

如果你不需要 SSL 支持,可以禁用 SSL

./configure --without-ssl

三、配置 Monit

(一)主配置文件

Monit 的主配置文件通常位于/etc/monitrc。打开该文件进行全局配置,如设置日志文件路径、监控周期等。

如果配置文件不存在,可以手动创建:

sudo touch /etc/monitrc
sudo chmod 600 /etc/monitrc

例如,修改日志文件路径为/var/log/monit.log:

set logfile /var/log/monit.log

设置监控周期为每 120 秒检查一次服务状态:

set daemon 120

(二)添加服务监控配置

在主配置文件末尾或单独创建一个配置文件(如/etc/monit/conf.d/目录下的文件)来定义要监控的服务。以监控 Nginx 服务为例:

check process nginx with pidfile /var/run/nginx.pid
  start program = "/usr/sbin/service nginx start"
  stop program = "/usr/sbin/service nginx stop"
  if failed host 127.0.0.1 port 80 protocol http then restart
  if 5 restarts within 5 cycles then timeout

上述配置中:

  • check process nginx with pidfile /var/run/nginx.pid:定义监控名为nginx的进程,通过/var/run/nginx.pid文件来识别进程 ID。
  • start program和stop program:指定启动和停止 Nginx 服务的命令。
  • if failed host 127.0.0.1 port 80 protocol http then restart:如果通过 HTTP 协议访问本地127.0.0.1:80失败,则重启 Nginx 服务。
  • if 5 restarts within 5 cycles then timeout:如果在 5 个监控周期内重启了 5 次,则视为超时,Monit 将不再尝试重启。

四、启动与管理 Monit

(一)启动 Monit 服务

sudo monit start

(三)检查 Monit 状态

  1. 查看 Monit 服务运行状态:
sudo  monit status

2. 查看 Monit 监控的服务状态:

monit summary

五、监控结果与警报

(一)查看监控结果

通过monit summary命令可以获取当前监控的所有服务的简要状态信息,包括服务名称、状态(运行、停止、异常等)。也可以使用monit status命令获取更详细的监控信息,如进程资源使用情况等。

(二)设置警报通知

Monit 支持通过邮件发送警报通知。在主配置文件monitrc中进行如下配置:

set mailserver smtp.example.com port 587 username "your_email@example.com" password "your_password"
set alert your_email@example.com

注意:password 是各类邮箱授权码,需要自己去相关的邮箱服务器生成。在第三方客户端登录时,密码框请输入授权码。可参考我的另一篇文章:# 配置QQ邮箱作为SMTP服务器来发送邮件

上述配置中,设置了 SMTP 邮件服务器地址、端口、用户名和密码,并指定将警报发送到your_email@example.com邮箱。当被监控的服务出现异常并触发警报条件时,管理员将收到包含详细异常信息的邮件通知。

六、Monit设置为自启服务

以下是针对 Linux (systemd)macOS (launchd) 的详细配置脚本,确保 Monit 开机自启并正确管理服务:


1. Linux (systemd) 配置

(1) 创建 systemd 服务文件
sudo vim /etc/systemd/system/monit.service

填入以下内容:

[Unit]
Description=Monit - system monitoring tool
Documentation=man:monit(1)
After=network.target

[Service]
Type=forking
ExecStart=/usr/bin/monit -c /etc/monitrc
ExecStop=/usr/bin/monit -c /etc/monitrc quit
ExecReload=/usr/bin/monit -c /etc/monitrc reload
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=multi-user.target
(2) 启用并启动 Monit
sudo systemctl daemon-reload          # 重新加载配置
sudo systemctl enable monit           # 开机自启
sudo systemctl start monit            # 立即启动
sudo systemctl status monit           # 检查状态

(3) 验证日志

journalctl -u monit -f               # 实时查看日志

2. macOS (launchd) 配置

(1) 创建 launchd plist 文件
sudo vim /Library/LaunchDaemons/com.monit.plist

填入以下内容(根据实际路径调整):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.monit</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/monit</string>
        <string>-c</string>
        <string>/usr/local/etc/monitrc</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/var/log/monit.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/monit.log</string>
</dict>
</plist>
(2) 设置权限并加载
sudo chmod 644 /Library/LaunchDaemons/com.monit.plist
sudo launchctl load /Library/LaunchDaemons/com.monit.plist
sudo launchctl start com.monit
(3) 验证日志
tail -f /var/log/monit.log

3. Monit 配置文件示例

确保 /etc/monitrc/usr/local/etc/monitrc 包含以下内容(以监控 Nginx 为例):

# 全局设置
set logfile /var/log/monit.log
set pidfile /var/run/monit.pid
set statefile /var/run/monit.state

# 监控 Nginx
check process nginx with pidfile /var/run/nginx.pid
    start program = "/usr/bin/systemctl start nginx"
    stop program = "/usr/bin/systemctl stop nginx"
    if failed host 127.0.0.1 port 80 protocol http then restart
    if does not exist then start  # 关键!确保服务不存在时自动启动

4. 关键点总结

系统配置文件路径自启命令日志查看
Linux/etc/systemd/system/monit.servicesystemctl enable monitjournalctl -u monit
macOS/Library/LaunchDaemons/com.monit.plistlaunchctl load com.monittail -f /var/log/monit.log

5. 常见问题解决

Q1: Monit 启动但服务未自动拉起?
  • 检查配置中是否有 if does not exist then start
  • 确保服务检查块的 start program 命令正确。
Q2: launchd 报权限错误?
sudo chown root:wheel /Library/LaunchDaemons/com.monit.plist
Q3: systemd 无法启动 Monit?

检查日志:

sudo journalctl -u monit --no-pager -n 50
Q4: Operation not permitted?

我发现问题了,如果配置了launchctl去启动monit,就会出现 'myapp' failed to start (exit status 126) -- '/Users/snackpub/Desktop/temp-files/jar/start.sh start': /bin/bash: /Users/snackpub/Desktop/temp-files/jar/start.sh: Operation not permitted

macOS 的安全机制阻止了脚本的执行,即使直接运行脚本是正常的。这是 macOS 的 安全沙盒(Sandbox)  和 隐私保护机制 导致的常见问题。

根本原因
  1. Gatekeeper 限制

    • macOS 会标记从网络下载的文件(包括脚本),即使你 chmod +xlaunchd 或 Monit 运行时仍可能被阻止。
  2. TCC (Transparency, Consent, and Control) 限制

    • macOS 要求后台服务(如 launchd)必须获得明确权限才能访问用户目录(如 ~/Desktop)。
  3. SIP (System Integrity Protection) 影响

    • 部分目录(如 /usr/bin)受保护,但你的脚本在 ~/Desktop,通常不受 SIP 影响。
解决方案

✅ 方案 1:移除 com.apple.quarantine 属性(关键步骤) xattr -d com.apple.quarantine /Users/snackpub/Desktop/temp-files/jar/start.sh

如果仍然不行,尝试彻底清除所有扩展属性: xattr -cr /Users/snackpub/Desktop/temp-files/jar/start.sh

✅ 方案 2:在 launchd 或 Monit 配置中声明完整权限

如果使用 launchd(推荐)

修改 /Library/LaunchDaemons/com.monit.plist,添加 EnableGlobbing 和 AbandonProcessGroup

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.monit</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Users/snackpub/Desktop/temp-files/jar/start.sh</string>
        <string>start</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>/Users/snackpub/Desktop/temp-files/jar</string>
    <key>EnableGlobbing</key>
    <true/>
    <key>AbandonProcessGroup</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/monit.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/monit.err</string>
</dict>
</plist>

通过以上配置,Monit 将在系统启动时自动运行,并监控配置的所有服务(如自动启动崩溃的进程)。

七、Monit 效果一览

完整配置案例

# 设置 Monit 的日志文件
set logfile /var/log/monit.log

# 设置 Monit 的 PID 文件
set pidfile /var/run/monit.pid

# 设置 Monit 的状态文件
set statefile /var/run/monit.state

#设置轮询时间
set daemon 20
set httpd port 2812 and
    use address 0.0.0.0  # 允许所有 IP 地址访问,若要限制访问,可改为具体的 IP >地址
    allow 0.0.0.0/0      # 允许所有 IP 地址访问,可根据需求修改为具体的 IP 地址>或 IP 段
    allow admin:monit    # 设置用户名和密码,这里用户名是 admin,密码是 monit,>可自行修改

# 设置 Monit 的邮件通知
set mailserver smtp.qq.com port 465
    username "1498851306@qq.com" password "2pbddick3qhbkanjya3ic2"
    using tls
    with timeout 30 seconds

set alert 1498851306@qq.com

# 设置邮件格式,确保 from 字段和 username 一致
set mail-format {
    from: 1498851306@qq.com
    subject: $SERVICE $EVENT at $DATE
    message: Monit $ACTION $SERVICE at $DATE on $HOST: $DESCRIPTION.
             Yours sincerely,
             monit

}

# To monitor a specific endpoint like `localhost:8081/htmlToPdf/a` with Monit, 
# you'll need to modify your check to include the full URL path in the HTTP 
# protocol check. Here's how you can update your configuration:

# 记录启动时的 PID
# PID_FILE="/var/run/${APP_NAME}.pid"          # PID文件路径
# nohup java $JAVA_OPTS -jar "$JAR_FILE" $SPRING_OPTS >> "$LOG_FILE" 2>&1 &
# echo $! > "$PID_FILE"



check process myapp with pidfile /var/run/myapp.pid
    start program = "/Users/snackpub/Desktop/temp-files/jar/start.sh start"
    stop program = "/Users/snackpub/Desktop/temp-files/jar/start.sh stop"
    if failed port 8081 protocol http
       request "/htmlToPdf/a"
       with timeout 5 seconds
    then restart
    if 5 restarts within 5 cycles then timeout
    if does not exist then restart
    group java
    

Monit 日志查看

image.png

Monit 管理页面

image.png

Monit 邮箱告警

image.png

更多内容