經驗之談:nginx php 502 bad gateway 解決方法
訪問phpMyAdmin時,出現下面錯誤。
phpMyAdmin – Error
Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.第一次開啟提示,重新整理提示:
502 bad gateway
檢視nginx error log:
[error] recv() failed (104: Connection reset by peer) while reading response header from u
檢視php session.save_path的設定,預設是/var/lib/php/session。修改該目錄nginx程序的使用者有讀寫許可權。問題解決。
其他可能:
部分PHP程式的執行時間超過了Nginx的等待時間,可以適當增加nginx.conf配置檔案中FastCGI的timeout時間,例如:
程式碼如下 | 複製程式碼 |
http { fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; } |
php.ini中memory_limit設低了會出錯,可以加大php.ini的memory_limit為64M。
附整理了一些其它可能導致502 bad gateway錯誤原因
.php-fpm程序數不夠用
使用 netstat -napo |grep "php-fpm" | wc -l 檢視一下當前fastcgi程序個數,如果個數接近conf裡配置的上限,就需要調高程序數。
但也不能無休止調高,可以根據伺服器記憶體情況,可以把php-fpm子程序數調到100或以上,在4G記憶體的伺服器上200就可以。
2. 調高調高linux核心開啟檔案數量
可以使用這些命令(必須是root帳號)
echo 'ulimit -HSn 65536' >> /etc/profile
echo 'ulimit -HSn 65536' >> /etc/rc.local
source /etc/profile
3.指令碼執行時間超時
如果指令碼因為某種原因長時間等待不返回 ,導致新來的請求不能得到處理,可以適當調小如下配置。
nginx.conf裡面主要是如下
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
php-fpm.conf裡如要是如下
request_terminate_timeout = 10s
4.快取設定比較小
修改或增加配置到nginx.conf
proxy_buffer_size 64k;
proxy_buffers 512k;
proxy_busy_buffers_size 128k;
5. recv() failed (104: Connection reset by peer) while reading response header from upstream
可能的原因機房網路丟包或者機房有硬體防火牆禁止訪問該域名
但最重要的是程式裡要設定好超時,不要使用php-fpm的request_terminate_timeout,
最好設成request_terminate_timeout=0;