插件窝 干货文章 LNMP怎样监控运行

LNMP怎样监控运行

监控 status 状态 Nginx 566    来源:    2025-05-04

LNMP环境监控运行方案

LNMP(Linux + Nginx + MySQL + PHP)环境的监控需要从多个层面进行,包括系统资源、服务状态、性能指标等。以下是全面的监控方案:

一、系统层面监控

1. 基础系统监控工具

  • top/htop:实时监控CPU、内存使用情况
  • vmstat:监控系统进程、内存、I/O等
  • iostat:监控磁盘I/O使用情况
  • iftop/nethogs:监控网络流量

2. 系统日志监控

  • /var/log/messages:系统主日志文件
  • /var/log/syslog:系统日志(Ubuntu)
  • dmesg:内核日志

二、Nginx监控

1. 基本状态监控

# 检查Nginx进程
ps aux | grep nginx

# 检查Nginx监听端口
netstat -tulnp | grep nginx

2. Nginx状态模块

在nginx.conf中启用状态模块:

server {
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

访问 http://your-server/nginx_status 获取状态信息

3. 日志监控

  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log

使用工具分析:

# 实时监控日志
tail -f /var/log/nginx/access.log

# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn

三、MySQL监控

1. 基本状态检查

# 检查MySQL进程
ps aux | grep mysql

# 检查MySQL运行状态
systemctl status mysql

2. MySQL内置监控

-- 查看服务器状态变量
SHOW STATUS;

-- 查看服务器系统变量
SHOW VARIABLES;

-- 查看当前连接数
SHOW STATUS LIKE 'Threads_connected';

-- 查看进程列表
SHOW PROCESSLIST;

3. 性能监控工具

  • mysqladmin:命令行管理工具

    mysqladmin -u root -p status
    mysqladmin -u root -p extended-status
    
  • mytop:类似top的MySQL监控工具

    mytop -u root -p password
    

4. 慢查询监控

在my.cnf中启用慢查询日志:

slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 2

使用mysqldumpslow分析慢查询:

mysqldumpslow -s t /var/log/mysql/mysql-slow.log

四、PHP监控

1. PHP-FPM状态监控

在php-fpm.conf中启用状态页:

pm.status_path = /status

Nginx配置示例:

location ~ ^/(status|ping)$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

访问 http://your-server/status 查看PHP-FPM状态

2. PHP错误日志

  • PHP错误日志:/var/log/php_errors.log
  • PHP-FPM日志:/var/log/php-fpm.log

五、综合监控方案

1. 使用Prometheus + Grafana

  1. 安装Prometheus
  2. 配置各服务的exporter:
    • node_exporter(系统监控)
    • nginx_exporter
    • mysqld_exporter
    • php-fpm_exporter
  3. 使用Grafana展示数据

2. 使用ELK Stack

  • Elasticsearch: 存储日志数据
  • Logstash: 收集和处理日志
  • Kibana: 可视化展示

3. 其他工具

  • Zabbix: 企业级监控解决方案
  • Nagios: 经典监控工具
  • Netdata: 实时性能监控工具

六、自动化监控脚本示例

#!/bin/bash

# 监控LNMP状态的简单脚本

# 系统状态
echo "===== System Status ====="
uptime
free -m

# Nginx状态
echo -e "\n===== Nginx Status ====="
systemctl status nginx | grep Active
echo "Nginx Connections:"
netstat -nat | grep :80 | wc -l

# MySQL状态
echo -e "\n===== MySQL Status ====="
systemctl status mysql | grep Active
echo "MySQL Connections:"
mysqladmin -u root -p'password' status | awk '{print $4}'

# PHP-FPM状态
echo -e "\n===== PHP-FPM Status ====="
systemctl status php-fpm | grep Active
echo "PHP-FPM Processes:"
ps aux | grep php-fpm | wc -l

七、告警设置

  1. 设置关键指标的阈值(CPU、内存、磁盘、连接数等)
  2. 配置邮件/SMS/Webhook通知
  3. 使用工具如Prometheus Alertmanager或Zabbix告警功能

通过以上方案,您可以全面监控LNMP环境的运行状态,及时发现并解决问题。