您的位置:首页 > 运维架构 > Nginx

Nginx 502 Bad Gateway 错误、解决方案和监控

2014-11-05 10:51 453 查看
Nginx 502 Bad Gateway 是因为nginx因为内存不足,PHP反应缓慢,php进程不足等引起的一类服务器错误。
发送问题的原因:
1、PHP FastCGI进程数不够用

当网站并发访问巨大时,php fastcgi的进程数不有一定的保障,因为cgi是单线程多进程工作的,也就是说cgi需要处理完一个页面后再继续下一个页面。如果进程数不够,当访问巨大的时候,cgi按排队处理之前的请求,之后的请求只有被放弃。这个时候nginx就会不时的出现502错误。
2、PHP FastCGI的内存不够用

当nginx返回静态页面时,这个问题一般不会出现,因为nginx不需要php cgi的处理而直接返回静态页面。但是当网页需要处理大量的php复杂操作的时候,例如执行api采集,或者采集页面的时候,那对php的要求是相当高的,如果配置给他的内存太少,那很容易就会导致php崩溃。
解决方法:
1、请检查你的FastCGI进程是否启动

2、FastCGI进程不够使用

请通过执行 netstat -anpo | grep "php-cgi" | wc -l 判断,是否接近你启动的FastCGI进程,接近你的设置,表示进程不够。
3、执行超时

可以把 nginx.conf 这几项的值调大一些:
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;4、FastCGI缓冲不够

nginx和apache一样,有前端缓冲限制,可以把 nginx.conf 这几项的值调大一些:
fastcgi_buffer_size 32k;
fastcgi_buffers 8 32k;
5、Proxy缓冲不够

如果你使用了Proxying,可以把 nginx.conf 这几项的值调大一些:
proxy_buffer_size 16k;
proxy_buffers 4 16k;
6、https转发配置错误

正确的配置方法
server_name www.mydomain.com;
location /myproj/repos {
set $fixed_destination $http_destination;
if ( $http_destination ~* ^https(.*)$ )
{
set $fixed_destination http$1;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Destination $fixed_destination;
proxy_pass http://subversion_hosts; }
7、php脚本执行时间过长

将 php-fpm.conf 的 <value name="request_terminate_timeout">0s</value> 的 0s 改成一个时间。
监控脚本
当发生 Nginx 502 Bad Gateway 错误问题时候重启 PHP-FPM进程,并发送邮件通知管理员:
#!/bin/bash
STATE=`curl --head http://www.linuxde.net | awk 'NR==1' | awk '{print $2}'`
if [ "$STATE" -eq "502" ]; then
/bin/bash /usr/local/webserver/php/sbin/php-fpm reload
/bin/bash /usr/local/webserver/nginx/sbin/nginx -s reload
echo "[报警]" "http error 502" $(date +"%y-%m-%d %H:%M:%S") "Reload php-fpm And Nginx" | mail -s "ERROR" 123@gmail.com
elif [ "$STATE" -ne "502" ] && [ "$STATE" -ne "200" ]; then
echo "[报警]" "Web Server Stop Working" $(date +"%y-%m-%d %H:%M:%S") | mail -s "ERROR" 123@gmail.com
fi
定时执行脚本,这里是30分钟执行一次,可以根据情况而定
vim /etc/crontab
*/30 * * * * root /root/satools/reload_php-fpm_error.sh
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网页 监控 502