我用512M的vps,訪問量不大,但內存占用很大,甚至宕機。
我用top,然后shitf+m發現,httpd占用內存極大。經過網上找資料設置后,用過一段時間終於沒再出現內存問題了。
首先查找配置文件的位置,可以用如下命令:
find / -name httpd.conf
找到配置文件/usr/local/apache/conf/extra/httpd-mpm.conf,修改設置Apache MPM Prefork模塊
StartServers 3
MinSpareServers 2
MaxSpareServers 5
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 40
我原來的MaxRequestsPerChild是為0,問題應該在此。
StartServers設置了服務器啟動時建立的子進程數量
MinSpareservers和MaxSpareServers分別設置空閑子進程的最小和最大數量
ServerLimit則是控制MaxClients所能使用的最大值。縮減MaxClients能讓運行動態內容(比如:WordPress)的服務器有很大的改變。如果你的VPS遭遇到流量的大幅增加,而你的MaxClients設置的太高的話,你的服務器將會無限循環工作於從物理內存交換頁面到虛擬內存中,最終導致宕機。一般計算適當的MaxClients值取決於你總共可用的系統內存除於每個Apache進程使用的內存。例如,如果你還有500MB的內存可用於Apache,每個Apache進程大約使用20MB的內存,你可以設置你的MaxClients為(512-12)/ 10 = 50(這個計算好像原文中有誤)。使用命令top可以得到你VPS實時內存的使用。
MaxRequestsPerChild這個指令設定一個獨立的子進程將能處理的請求數量。在處理“MaxRequestsPerChild 數字”個請求之后,子進程將會被父進程終止,這時候子進程佔用的內存就會釋放,如果再有訪問請求,父進程會重新產生子進程進行處理。如果 MaxRequestsPerChild預設為0(無限)或較大的數字(例如10000以上)可以使每個子進程處理更多的請求,不會因為不斷終止、啟動子進程降低訪問效率,但MaxRequestsPerChild設置為0時,如果佔用了200~300M內存,即使負載下來時佔用的內存也不會減少。內存較大的服務器可以設置為0或較大的數字。內存較小的服務器不妨設置成50、100、200,以防內存溢出。
找到配置文件/usr/local/apache/conf/extra/httpd-default.conf,修改KeepAlive設置
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 30
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to “Off” to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 120
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
Timeout是一個連接多少時間后斷開,這個參數設置在30-60是一般的php程序都是適用的,至少要運行一些要占用大量時間的php程序,那么適當調高也是可以的,但請不要太高,否則會影響apache性能,本次優化我們使用30就很足夠了。
MaxKeepAliveRequests 是一個連接最大的請求量,對於頁面有較多的圖片等元素,可以適當調高一點,對於一般的網頁設置在80-120是足夠的,我們就設置為120,如果設置太高會導致httpd長時間不能退出釋放內存的。
KeepAliveTimeout 是當用戶處理一次連接時,如果在該參數的時間內還有請求則會繼續執行,不需要重新創建新的連接,直到達到MaxKeepAliveRequests的最大值才會退出。對於perfork模式下的,有人認為是將KeepAlive Off會比較好,但是對於絕大多數的網站都會不多不少有些圖片元素,所以將該項打開,並將KeepTimeOut設置在2-5秒,不但有效提高服務器性能,也能加快頁面打開速度。
如果還需要優化可以考慮修改啟動的模塊,Wordpress主要使用以下模塊,保留這些其他的可以注釋掉
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule dir_module modules/mod_dir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule negotiation_module modules/mod_negotiation.so