插件窝 干货文章 LNMP故障排查技巧

LNMP故障排查技巧

检查 排查 bash Nginx 1000    来源:    2025-05-07

LNMP故障排查技巧

LNMP(Linux+Nginx+MySQL+PHP)是常见的Web服务架构组合,以下是针对LNMP环境的系统化故障排查方法。

1. 基础检查

1.1 服务状态检查

# 检查Nginx状态
systemctl status nginx
nginx -t  # 测试配置文件语法

# 检查MySQL状态
systemctl status mysql

# 检查PHP-FPM状态
systemctl status php-fpm

1.2 端口监听检查

netstat -tulnp | grep -E '80|3306|9000'
ss -tulnp | grep -E '80|3306|9000'

1.3 进程检查

ps aux | grep -E 'nginx|mysql|php-fpm'

2. Nginx故障排查

2.1 常见问题

  • 502 Bad Gateway
  • 504 Gateway Timeout
  • 403 Forbidden
  • 404 Not Found

2.2 排查步骤

  1. 检查错误日志
tail -f /var/log/nginx/error.log
  1. 检查配置文件
nginx -t
  1. 检查权限
ls -la /var/www/html/
  1. 检查PHP-FPM连接
# 查看PHP-FPM监听地址是否与Nginx配置匹配
grep -E 'listen|listen.owner|listen.group' /etc/php-fpm.d/www.conf

3. MySQL故障排查

3.1 常见问题

  • 连接失败
  • 查询缓慢
  • 权限问题

3.2 排查步骤

  1. 检查错误日志
tail -f /var/log/mysql/error.log
  1. 检查MySQL服务
mysqladmin -u root -p ping
  1. 检查连接数
mysql -u root -p -e "SHOW STATUS LIKE 'Threads_connected';"
  1. 检查慢查询
# 查看慢查询是否开启
mysql -u root -p -e "SHOW VARIABLES LIKE 'slow_query_log';"

# 查看慢查询日志路径
mysql -u root -p -e "SHOW VARIABLES LIKE 'slow_query_log_file';"

4. PHP故障排查

4.1 常见问题

  • 脚本不执行
  • 500内部错误
  • 内存耗尽

4.2 排查步骤

  1. 检查PHP错误日志
tail -f /var/log/php-fpm/error.log
  1. 检查PHP配置
php -i | grep error_log
  1. 测试PHP脚本
# 创建测试文件
echo "<?php phpinfo(); ?>" > /var/www/html/test.php
# 访问http://your-server/test.php
  1. 检查PHP-FPM配置
# 检查进程数设置
grep -E 'pm.max_children|pm.start_servers' /etc/php-fpm.d/www.conf

5. 综合排查工具

5.1 系统资源监控

top
htop
vmstat 1
iostat -x 1

5.2 网络连接检查

# 检查TCP连接状态
ss -s
netstat -antp

5.3 数据库性能分析

# 查看当前运行查询
mysql -u root -p -e "SHOW PROCESSLIST;"

# 使用mysqltuner分析
wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl
perl mysqltuner.pl

6. 常见解决方案

6.1 502错误

  1. 检查PHP-FPM是否运行
  2. 检查Nginx与PHP-FPM的socket/端口配置是否匹配
  3. 检查PHP-FPM用户权限

6.2 数据库连接问题

  1. 检查MySQL是否监听正确IP
  2. 检查用户权限
  3. 检查最大连接数设置

6.3 性能问题

  1. 优化Nginx worker_processes
  2. 调整PHP-FPM进程管理设置
  3. 优化MySQL缓存设置

7. 日志分析技巧

7.1 实时监控多个日志

tail -f /var/log/nginx/access.log /var/log/nginx/error.log /var/log/php-fpm/error.log

7.2 使用grep过滤关键错误

grep -E 'error|fail|warning' /var/log/nginx/error.log

7.3 分析访问日志

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

# 统计访问量最高的IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

通过以上系统化的排查方法,可以快速定位和解决LNMP环境中的大多数问题。