解決php-cgi假死導致頁面出現502 Bad gateway問題

來源:互聯網
上載者:User

php-cgi進程數不夠用、php執行時間長、或者是php-cgi進程死掉,都會出現502錯誤。

1) .  php執行時間長

如果伺服器效能足夠好,且寬頻資源足夠充足,PHP指令碼沒有系迴圈或BUG的話你可以直接將”request_terminate_timeout”設定 成0s。
php-fpm.conf  103行左右

 代碼如下 複製代碼

<value name=”request_terminate_timeout”>0s</value>

0s的含義是讓PHP-CGI一直執行下去而沒有時間限制。
而如果做不到這一點,也就是說你的PHP-CGI可能出現某個BUG,或者你的寬頻不 夠充足或者其他的原因導致你的PHP-CGI能夠假死那麼就建議你給”request_terminate_timeout”賦一個值,這個值可以根據你 伺服器的效能進行設定。一般來說效能越好你可以設定越高,20分鐘-30分鐘都可以。由於我的伺服器PHP指令碼需要長時間運行,有的可能會超過10分鐘因 此我設定了900秒,
<value name=”request_terminate_timeout”>900s</value>
這樣不會導致PHP-CGI死掉而出現502 Bad gateway這個錯誤

2)  php-cgi進程數不夠用

預設的php-cgi串連數如果在串連數很大的時候,預設的串連數配置限制會導致502的結果。
php-fpm.conf  79行左右

 代碼如下 複製代碼
<value name=”max_children”>256</value>


如果您高負載網站使用PHP-FPM管理FastCGI,這些技巧也許對您有用:)

1. Compile PHP’s modules as less as possible, the simple the best (fast);
1.盡量少安裝PHP模組,最簡單是最好(快)的

2. Increas PHP FastCGI child number to 100 and even more. Sometime, 200 is OK! ( On 4GB memory server);
2.把您的PHP FastCGI子進程數調到100或以上,在4G記憶體的伺服器上200就可以
註:我的1g測試機,開64個是最好的,建議使用壓力測試擷取最佳值

3. Using SOCKET PHP FastCGI, and put into /dev/shm on Linux;
3.使用socket串連FastCGI,linux作業系統可以放在 /dev/shm中
註:在php-fpm.cnf裡設定<value name=”listen_address”>/tmp/nginx.socket</value>就可以通過socket串連FastCGI了,/dev/shm是記憶體檔案系統,放在記憶體中肯定會快了

4. Increase Linux “max open files”, using the following command (must be root):
# echo ‘ulimit -HSn 65536′ >> /etc/profile
# echo ‘ulimit -HSn 65536 >> /etc/rc.local
# source /etc/profile
4.調高linux核心開啟檔案數量,可以使用這些命令(必須是root帳號)
echo ‘ulimit -HSn 65536′ >> /etc/profile
echo ‘ulimit -HSn 65536′ >> /etc/rc.local
source /etc/profile
註:我是修改/etc/rc.local,加入ulimit -SHn 51200的

5. Increase PHP-FPM open file description rlimit:
# vi /path/to/php-fpm.conf
Find “<value name=”rlimit_files”>1024</value>”
Change 1024 to 4096 or higher number.
Restart PHP-FPM.
5. 增加 PHP-FPM 開啟檔案描述符的限制:
# vi /path/to/php-fpm.conf
找到“<value name=”rlimit_files”>1024</value>”
把1024 更改為 4096 或者更高.
重啟 PHP-FPM.

6. Using PHP code accelerator, e.g eAccelerator, XCache. And set “cache_dir” to /dev/shm on Linux.
6.使用php代碼加速器,例如 eAccelerator, XCache.在linux平台上可以把`cache_dir`指向 /dev/shm

補充個nginx+php-cgi的記憶體開銷情況:

Nginx進程  每個進程數15M左右 有參數 worker_processes 來決定開啟個數 一般8個就可以
php-cgi進程  每個消耗20M左右記憶體,看情況,一般128或者256,大記憶體機器512或者更高
這個數值根據機子的效能和php的執行消耗的系統效能來配置。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.