apache占用内存高解决办法

我用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

posted @ 2018-01-18 08:54  追忆丶年华  阅读(5345)  评论(0编辑  收藏  举报