[需要实践]nginx php fastcgi Connection reset by peer的原因及解决办法

jackxiang 2014-9-30 23:07 | |
背景:有可能 fastcgi Connection reset by peer于502共同发生,(参看:https://jackxiang.com/post/4710/ ,http://www.jb51.net/article/50408.htm 写道:很多站长转到nginx+php-fpm后,饱受500,502问题困扰。当nginx收到如上错误码时,可以确定后端php-fpm解析php出了某种问题,比如,执行错误,执行超时。php-fpm.conf的配置文件中有一个参数request_slowlog_timeout。 )。注意nginx的notice日志及php的request_slowlog_timeout日志。
1)nginx:
在nginx的全局配置中增加 : error_log   logs/error.log notice;

nginx记录日志信息分两个级别,第一个级别的取值为如下之一:
“stderr”, “emerg”, “alert”, “crit”, “error”,”warn”, “notice”, “info”, “debug”
这些值是互斥的,也就是说只能取其中之一,如果在配置文件里加了像如下这种两条配置项:
error_log  logs/error.log  notice;
error_log  logs/error.log  info;

2)php的php-fpm.conf增加时间长度限定超过就算超时:
当PHP运行在php-fpm模式下,php.ini配置的max_execute_time是无效的,需要在php-fpm.conf中配置另外一个配置项:request_terminate_timeout;
request_terminate_timeout = 10
request_slowlog_timeout = 0
slowlog = /data/logs/php/slow.log
    当request_slowlog_timeout 设为一个具体秒时request_slowlog_timeout =5,表示如果哪个脚本执行时间大于5秒,会记录这个脚本到慢日志文件中
request_slowlog_timeout =0表示关闭慢日志输出。
摘自:http://blog.csdn.net/zhangxinrun/article/details/17002939

下面是php 5.3以上版本将TCP改成socket方式的配置方法:
修改php-fpm.conf(/usr/local/php/etc/php-fpm.conf)
;listen = 127.0.0.1:9000
listen = /dev/shm/php-cgi.sock
nginx通过unix socket和fastcgi通信,比tcp socket要高效,重负荷下可以考虑。
1、在nginx.conf中修改配置为:
fastcgi_pass unix:/tmp/php-cgi.sock;
#fastcgi_pass 127.0.0.1:9000;
2、在php-fpm.conf中修改配置为:
/tmp/php-cgi.sock
同理,在proxy_pass、upstream server 等处都能使用

言归正传:
Connection reset by peer
这个错误是在nginx的错误日志中发现的,为了更全面的掌握nginx运行的异常,强烈建议在nginx的全局配置中增加
error_log   logs/error.log notice;
这样,就可以记录nginx的详细异常信息。


nginx的错误日志中会出现Connection reset by peer) while reading response header from upstream, client: 1.1.1.1, server: 102.local, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000

后来反复检查,发现这是因为php运行较慢,并超出php-fpm.conf的request_terminate_timeout设置的秒数。

request_terminate_timeout用于设置当某个php脚本运行最长时间,若超出php-fpm进程管理器强行中止当前程序,并关闭fastcgi和nginx的网络连接,然后nginx中就会出现Connection reset by peer的错误了。

也就是说,产生这个错误的原因是:
php 程序的运行时间超出request_terminate_timeout设置的值。
在php-fpm环境下,在php的安装目录的etc/php-fpm.conf中有此值的设置项,可将其设置为0或更大的值。

提示,在php.ini中存在一项max_execution_time,也用于设置php脚本的最长执行时间。但在php-fpm环境下,我发现max_execution_time的设置是无效的,只有request_terminate_timeout产生了作用。

总结:请将request_terminate_timeout设置为较大的值或0,可减少因php脚本执行时行过长导致nginx产生Connection reset by peer错误。

转自:http://zhangxugg-163-com.iteye.com/blog/1310311

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://jackxiang.com/post/7536/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2014-10-1 00:16
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]