502错误表示Nginx作为反向代理服务器时,无法从上游服务器(如PHP-FPM、Node.js、Tomcat等)获取有效的响应。以下是常见原因和解决方案:
bash
systemctl status php-fpm # 对于PHP
systemctl status tomcat # 对于Java应用
bash
systemctl start php-fpm
systemctl restart php-fpm
nginx
location / {
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
}
bash
ps aux | grep php-fpm
netstat -tulnp | grep php-fpm
ini
; 在php-fpm.conf或pool配置中
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
bash
free -h # 内存
df -h # 磁盘空间
top # CPU使用率
bash
chown -R nginx:nginx /var/www/html
bash
telnet 127.0.0.1 9000 # 测试PHP-FPM默认端口
检查Nginx错误日志获取具体原因:
tail -f /var/log/nginx/error.log
常见日志条目示例:
connect() failed (111: Connection refused) while connecting to upstream
upstream prematurely closed connection while reading response header from upstream
测试上游服务是否独立工作
curl http://localhost:8080 # 测试应用本身
检查文件描述符限制
ulimit -n
检查SELinux状态(如适用)
sestatus
临时关闭Nginx缓存进行测试
proxy_buffering off;
通过以上步骤,通常可以定位并解决502错误问题。如果问题仍然存在,可能需要更深入地分析特定应用的日志和配置。