在LNMP(Linux + Nginx + MySQL + PHP)环境下,有效的系统监控对于确保服务稳定性和性能优化至关重要。以下是一个全面的监控方案:
工具选择:
监控指标:
# 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*
# 配置prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
# 启动
./prometheus --config.file=prometheus.yml &
# 安装Node Exporter(用于系统指标)
wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz
tar xvfz node_exporter-*.tar.gz
cd node_exporter-*
./node_exporter &
# 安装Grafana
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_8.2.0_amd64.deb
sudo dpkg -i grafana_8.2.0_amd64.deb
sudo systemctl start grafana-server
server {
listen 80;
server_name status.example.com;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
使用nginx-prometheus-exporter:
docker run -p 9113:9113 nginx/nginx-prometheus-exporter -nginx.scrape-uri http://<nginx-host>:80/nginx_status
-- 创建监控专用用户
CREATE USER 'exporter'@'localhost' IDENTIFIED BY 'password' WITH MAX_USER_CONNECTIONS 3;
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost';
-- 常用监控SQL
SHOW GLOBAL STATUS;
SHOW ENGINE INNODB STATUS;
wget https://github.com/prometheus/mysqld_exporter/releases/download/v0.13.0/mysqld_exporter-0.13.0.linux-amd64.tar.gz
tar xvfz mysqld_exporter-*.tar.gz
cd mysqld_exporter-*
# 配置.my.cnf
[client]
user=exporter
password=password
# 启动
./mysqld_exporter --config.my-cnf=.my.cnf &
; php-fpm.conf
pm.status_path = /status
ping.path = /ping
location ~ ^/(status|ping)$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
allow 127.0.0.1;
deny all;
}
docker run -d -p 9253:9253 --name php-fpm-exporter hipages/php-fpm_exporter --phpfpm.scrape-uri "unix:///var/run/php-fpm.sock;/status"
# 实时监控Nginx访问日志
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html --log-format=COMBINED
# alertmanager.yml
route:
group_by: ['alertname']
receiver: 'email-notifications'
receivers:
- name: 'email-notifications'
email_configs:
- to: 'admin@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'user'
auth_password: 'password'
使用Grafana可以创建综合监控面板,包含: 1. 系统资源概览 2. Nginx请求率和响应时间 3. MySQL查询性能和连接池 4. PHP-FPM进程状态 5. 服务状态指示器
通过以上方案,您可以全面掌握LNMP环境的运行状态,及时发现并解决问题,确保系统稳定高效运行。