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

Nginx 502 Bad Gateway 是由于nginx由于内存不足,PHP反应缓慢,php进程不足等引发的一类服务器错误。php

发送问题的缘由:
一、PHP FastCGI进程数不够用前端


当网站并发访问巨大时,php fastcgi的进程数不有必定的保障,由于cgi是单线程多进程工做的,也就是说cgi须要处理完一个页面后再继续下一个页面。若是进程数不够,当访问巨大的时候,cgi按排队处理以前的请求,以后的请求只有被放弃。这个时候nginx就会不时的出现502错误。linux

二、PHP FastCGI的内存不够用nginx


当nginx返回静态页面时,这个问题通常不会出现,由于nginx不须要php cgi的处理而直接返回静态页面。可是当网页须要处理大量的php复杂操做的时候,例如执行api采集,或者采集页面的时候,那对php的要求是至关高的,若是配置给他的内存太少,那很容易就会致使php崩溃。web

解决方法:
一、请检查你的FastCGI进程是否启动apache


二、FastCGI进程不够使用vim


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

三、执行超时bash


能够把 nginx.conf 这几项的值调大一些:服务器

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;四、FastCGI缓冲不够


nginx和apache同样,有前端缓冲限制,能够把 nginx.conf 这几项的值调大一些:

fastcgi_buffer_size 32k;
fastcgi_buffers 8 32k;
五、Proxy缓冲不够


若是你使用了Proxying,能够把 nginx.conf 这几项的值调大一些:

proxy_buffer_size 16k;
proxy_buffers 4 16k;
六、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;
}
七、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

相关文章
相关标签/搜索