502 Bad Gateway错误表示Nginx作为反向代理服务器时,无法从上游服务器(如PHP-FPM、Node.js、Apache等)获取有效的响应。以下是常见原因和解决方法:
检查上游服务状态:确保PHP-FPM、Apache、Node.js等服务正在运行
systemctl status php-fpm # 对于PHP-FPM
systemctl status apache2 # 对于Apache
重启上游服务:
systemctl restart php-fpm
systemctl restart apache2
/etc/nginx/nginx.conf
或站点配置文件中)添加:
nginx
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
检查服务器资源:
free -h # 查看内存
df -h # 查看磁盘空间
top # 查看CPU使用率
调整PHP-FPM配置:
在/etc/php-fpm.conf
或/etc/php/7.x/fpm/pool.d/www.conf
中:
pm.max_children = 50 # 根据服务器配置调整
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
bash
chown -R www-data:www-data /var/www/html # 对于Debian/Ubuntu
chown -R nginx:nginx /var/www/html # 对于CentOS/RHEL
nginx
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
查看Nginx错误日志:
tail -f /var/log/nginx/error.log
查看PHP-FPM错误日志:
tail -f /var/log/php-fpm.log
测试上游服务是否响应:
curl -I http://localhost:8080 # 替换为你的上游服务端口
检查端口和套接字:
netstat -tulnp | grep php-fpm
ss -pl | grep php-fpm
临时增加日志级别:
error_log /var/log/nginx/error.log debug;
检查防火墙设置:
iptables -L -n # 查看防火墙规则
ufw status # 对于Ubuntu
通过以上步骤,通常可以定位并解决502错误。如果问题仍然存在,可能需要更深入地检查特定应用程序的配置和日志。