- Nginx + php-fpm на разных хостах — error: failed (104: Connection reset by peer) while reading response header from upstream
- Fix Nginx 104: Connection Reset By Peer While Reading Response Header From Upstream
- How to Fix Connection Reset By Peer While Reading Response Header From Upstream.
- Change Nginx keepalive_requests.
- Check PHP permission for session.save_path.
- Change FastCGI Timeouts.
- Increase opcache memory limit.
- FastCGI (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI ser
Nginx + php-fpm на разных хостах — error: failed (104: Connection reset by peer) while reading response header from upstream
Добрый день всем! Ситуация такая: необходимо настроить связку php-fpm + nginx, чтоб они работали на разных виртуалках в одной локальной сети. Собственно после установки и настройки всего в логах nginx возникает сабжевая ошибка при попытке зайти на тестовую страничку, в браузере при этом, естественно, 502 — Bad Gateway. При этом в логах php-fpm пусто, только
[12-May-2014 12:30:48] NOTICE: fpm is running, pid 11860 [12-May-2014 12:30:48] NOTICE: ready to handle connections
и все. Перекопала все, что можно, везде в основном предлагается подключать fastcgi не через unix-сокет, а через ip-адрес:порт, но у меня, собственно, так и есть. Фаерволов между машинами нет. Привожу конфиги.
user www-data; worker_processes 4; pid /var/run/nginx.pid; events < worker_connections 1024; multi_accept on; use epoll; >http < keepalive_timeout 65; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; >
[global] pid = /var/run/php5-fpm.pid error_log = /var/log/php5-fpm.log include=/etc/php5/fpm/pool.d/*.conf
[www] user = www-data group = www-data listen = 192.168.199.223:9000 listen.allowed_clients = 127.0.0.1, 192.168.199.224 pm = static pm.max_children = 100 pm.max_requests = 100 pm.status_path = /status_php-test ping.path = /ping_php-test chdir = /webdata
Ну проверьте, что порт 192.168.199.223:9000 дествительно слушается по выхлопу ″netstat″ или ″ss″. Ещё есть ″cgi-fcgi″ с помощью которого можно слать GET-запросы. Хотя бы станет понятнее, в nginx или в php-fpm проблема.
# netstat -nat|grep 9000 tcp 0 0 192.168.199.223:9000 0.0.0.0:* LISTEN
а вот про cgi-fcgi не совсем понятно, откуда его запускать и что в параметре ключа -connect указывать.
Ну, так как у вас фильтрация по src-адресу, то запускать можно только с 192.168.199.224. Потому, что, если вы запустите cgi-fcgi на машине с php-fpm (192.168.199.223), то он и пойдёт с адреса 192.168.199.223, а у вас его нету в allowed_clients.
В параметре ″-connect″ указывать это самое ″192.168.199.223:9000″.
SCRIPT_NAME=/ping_php-test \ SCRIPT_FILENAME=/ping_php-test \ REQUEST_METHOD=GET \ cgi-fcgi -bind -connect 192.168.199.223:9000
Запускаю эту команду на 192.168.199.224, в ответ ничего не выводится, в логах php-fpm.log тоже ничего нового.
Если php и nginx на одном хосте чем сокеты не устраивают?
В том-то и дело, что на разных, это ключевое требование, так как это тестовый стенд, имитирующий работу продакшена, а на продакшене они на разных хостах.
на 192.168.199.224 попробуйте telnet 192.168.199.223 9000
подключается?
Подключается и тут же сбрасывается, то есть в ответ на команду сразу выводится весь этот текст:
Trying 192.168.199.223. Connected to 192.168.199.223. Escape character is '^]'. Connection closed by foreign host.
Для примера telnet 192.168.199.223 22 коннектится и ждет дальнейшего ввода команд:
# telnet 192.168.199.223 22 Trying 192.168.199.223. Connected to 192.168.199.223. Escape character is '^]'. SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1.3
Вообще странно, ведь netstat -tapnl | grep 9000 показывает, что 192.168.199.223:9000 ждет коннекта с любого хоста и порта:
tcp 0 0 192.168.199.223:9000 0.0.0.0:* LISTEN 11860/php-fpm.conf)
Значит php-fpm дурит.
Поднять log_level и смотреть в логи, может чего скажет.
После повышения log_level до debug и рестарта php5-fpm в логах появилось:
[14-May-2014 11:39:10] NOTICE: Finishing . [14-May-2014 11:39:10] NOTICE: exiting, bye-bye! [14-May-2014 11:39:10.803079] DEBUG: pid 15124, fpm_scoreboard_init_main(), line 40: got clock tick '100' [14-May-2014 11:39:10.803862] DEBUG: pid 15124, fpm_event_init_main(), line 331: event module is epoll and 1 fds have been reserved [14-May-2014 11:39:10.803919] NOTICE: pid 15124, fpm_init(), line 80: fpm is running, pid 15124 [14-May-2014 11:39:10.804351] DEBUG: pid 15124, fpm_children_make(), line 421: [pool www] child 15125 started [14-May-2014 11:39:10.804761] DEBUG: pid 15124, fpm_children_make(), line 421: [pool www] child 15126 started [14-May-2014 11:39:10.805169] DEBUG: pid 15124, fpm_children_make(), line 421: [pool www] child 15225 started [14-May-2014 11:39:10.911376] DEBUG: pid 15124, fpm_children_make(), line 421: [pool www] child 15226 started [14-May-2014 11:39:10.911410] DEBUG: pid 15124, fpm_event_loop(), line 360: 117704 bytes have been reserved in SHM [14-May-2014 11:39:10.911420] NOTICE: pid 15124, fpm_event_loop(), line 361: ready to handle connections
Когда захожу на сайт в логах php-fpm ничего нового не появляется.
Попробуйте убрать ″listen.allowed_clients″, чтобы коннект принимался с любых адресов. Тогда можно будет попробовать ″telnet″ и ″cgi-fcgi″ с машины 192.168.199.223, чтобы исключить влияние сети.
Спасибо большое! Закоментировала ″listen.allowed_clients″ и сайт заработал.
То есть у nginx-а нифига не 192.168.199.224, так получается?
нет, у него как раз таки 192.168.199.224, так что совершенно непонятно, почему вариант со строкой «listen.allowed_clients = 127.0.0.1, 192.168.199.224» не работал. Магия какая-то.
Напишу не совсем в тему, но мне почему-то кажется, что nginx при нагрузках работает стабильнее через tcp-сокет, чем через unix.
Fix Nginx 104: Connection Reset By Peer While Reading Response Header From Upstream
Nginx 502 is an uncommon error that causes due to issue with your server Nginx and PHP-FastCGI. If you notice any Nginx 502 error it is better to check the Nginx log.
When you are investigating the Nginx error logs, you can see that the “recv() failed (104: Connection reset by peer) while reading response header from upstream,” error. This also results in a “no live upstreams while connecting to upstream” error. When I’m checking my WordPress site logs I saw that several times appeared that error log. This is an issue with the Nginx and PHP-FPM configurations. Can easily fix it in just a few steps.
- Nginx and PHP-FPM communication error.
- PHP-FPM is timing out quickly.
- PHP-FPM is not running.
In order to fix 104: Connection reset by peer while reading response header from upstream issue, you should have access to modify the PHP and Nginx configuration files. If you are on shared hosting or a managed hosting package, you can ask your hosting partner to correct that configuration file.
How to Fix Connection Reset By Peer While Reading Response Header From Upstream.
If you can see continuous connection reset by peer error your visitors may receive “502 Bad Gateway” errors. To correct this Nginx error you must set Nginx keepalive_requests and PHP-FPM pm.max_requests equal value. If these two values are not equal then the Nginx or PHP-FPM end up closing the connection. This is an issue caused by server configuration mismatch, you can fix it by like our Logrotate issue guide.
Change Nginx keepalive_requests.
- Change keepalive_requests as per your need. Don’t use too high keepalive_requests, it can cause excessive memory usage.
- Save the configuration file.
- Save the configuration file.
- Restart the Nginx and PHP-FPM by running the following command line.
Check PHP permission for session.save_path.
In some situations, your PHP is not able to write the season file. This will generate Nginx 502 connection reset by peer while reading response header from upstream.
- First check where your PHP session.save_path is. Some situations it is “/var/lib/php/sessions” or “/var/lib/php/session“
- Open your system php.ini file and search for “session.save_path“.
- Then you can see your system PHP session.save_path.
- Run the following command in your SSH terminal to fix the permission issue. In this example my LEMP stack php session.save_path is “/var/lib/php/session“
Change FastCGI Timeouts.
Another solution is to change the Nginx Fast-CGI timeouts. Default FastCGI timeout is the 60s. Your application may require higher than the 60s to run, therefore it is better to change the following timeouts to prevent Nginx 502 bad gateway error.
- Open the nginx configuration file. Generally it is “/etc/nginx/nginx.conf“.
- Change add the following timeout values to your nginx.conf.
-
- fastcgi_read_timeout 300;
- fastcgi_send_timeout 300;
- fastcgi_connect_timeout 300;
Increase opcache memory limit.
- Open the php.ini file.
- Search for “opcache.memory_consumption”.
- Change the value to a higher amount like below.
FastCGI (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI ser
[Thu Jul 29 01:56:23 2010] [warn] [client 94.24.86.28] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: http://url/
[Thu Jul 29 01:56:23 2010] [error] [client 94.24.86.28] Premature end of script headers: index.php, referer: http://url/КАк можно пофиксить? PS: 1. /php-bin/php — CHMOD 555 2. /php-bin/ — CHMOD 755 3. apache2.conf (httpd.conf) есть наличие следующего : — для блока VitrualHost :
ScriptAlias /cgi-bin/ /var/www/user/data/www/*/cgi-bin/
Alias /php-fcgi/ /var/www/user/data/php-bin/
AddType application/x-httpd-fastphp .php .php3 .php4 .php5 .phtml
AddHandler fcgid-script .php .php3 .php4 .php5 .phtmlFCGIWrapper /var/www/user/data/php-bin/php .php
FCGIWrapper /var/www/user/data/php-bin/php .php3
FCGIWrapper /var/www/user/data/php-bin/php .php4
FCGIWrapper /var/www/user/data/php-bin/php .php5
FCGIWrapper /var/www/user/data/php-bin/php .phtml
Options +ExecCGI# This is the Apache server configuration file for providing FastCGI support
# through mod_fcgid
#
# Documentation is available at
# http://httpd.apache.org/mod_fcgid/mod/mod_fcgid.htmlLoadModule fcgid_module modules/mod_fcgid.so
# Use FastCGI to process .fcg .fcgi & .fpl scripts
AddHandler fcgid-script fcg fcgi fpl# Sane place to put sockets and shared memory file
FcgidIPCDir /var/run/mod_fcgid
FcgidProcessTableFile /var/run/mod_fcgid/fcgid_shm
-