插件窝 干货文章 linux monit如何进行监控设置

linux monit如何进行监控设置

Monit 监控 alert then 117    来源:    2025-05-14

Linux Monit 监控设置指南

Monit 是一个开源的进程监控工具,可以监控和管理 Unix/Linux 系统上的进程、文件、目录、设备等。以下是详细的 Monit 监控设置步骤:

1. 安装 Monit

对于基于 Debian/Ubuntu 的系统:

sudo apt-get update
sudo apt-get install monit

对于基于 RHEL/CentOS 的系统:

sudo yum install monit
# 或
sudo dnf install monit

2. 基本配置

Monit 的主配置文件通常位于 /etc/monit/monitrc/etc/monitrc

全局配置示例:

set daemon 30            # 每30秒检查一次
set logfile /var/log/monit.log
set idfile /var/lib/monit/id
set statefile /var/lib/monit/state

set mailserver smtp.example.com port 587
    username "your-email@example.com" password "your-password"
    using tlsv1
    with timeout 30 seconds

set alert admin@example.com    # 设置接收警报的邮箱
set httpd port 2812 and        # 启用Web界面
    use address 0.0.0.0        # 监听所有IP
    allow 0.0.0.0/0            # 允许所有IP访问(生产环境应限制)
    allow admin:monit          # 设置Web界面用户名密码

3. 监控项目配置

监控进程示例(如Nginx):

check process nginx with pidfile /var/run/nginx.pid
    start program = "/etc/init.d/nginx start"
    stop program = "/etc/init.d/nginx stop"
    if failed host 127.0.0.1 port 80 protocol http then restart
    if cpu > 80% for 5 cycles then alert
    if memory > 200 MB for 5 cycles then restart
    if 3 restarts within 5 cycles then timeout

监控系统资源:

check system $HOST
    if loadavg (1min) > 4 then alert
    if loadavg (5min) > 2 then alert
    if memory usage > 75% then alert
    if cpu usage (user) > 70% then alert
    if cpu usage (system) > 30% then alert

监控文件系统:

check filesystem rootfs with path /
    if space usage > 80% then alert
    if inode usage > 85% then alert

监控网络连接:

check host example.com with address example.com
    if failed ping then alert
    if failed port 80 protocol http then alert

4. 启动和测试 Monit

启动 Monit 服务:

sudo systemctl start monit
sudo systemctl enable monit

检查配置语法:

sudo monit -t

重新加载配置:

sudo monit reload

查看监控状态:

sudo monit status

5. Web 界面访问

配置完成后,可以通过浏览器访问 http://your-server-ip:2812 查看监控状态(使用配置中设置的用户名密码登录)。

6. 高级功能

自定义监控脚本:

check program myscript with path "/path/to/script.sh"
    if status != 0 then alert

监控文件变化:

check file apache_conf with path /etc/apache2/apache2.conf
    if changed checksum then alert

监控目录变化:

check directory mydir with path /path/to/directory
    if changed timestamp then alert

7. 日志和故障排除

Monit 日志通常位于 /var/log/monit.log,可用于故障排除。

常见问题: - 确保配置文件权限正确(通常应为 600) - 使用 monit -t 检查配置语法 - 确保服务启动脚本路径正确

通过以上配置,Monit 可以有效地监控您的 Linux 系统和服务,并在出现问题时自动恢复或发送警报。