当前位置: 代码迷 >> PowerDesigner >> AWS 下 Apache httpd 服务器性能调优
  详细解决方案

AWS 下 Apache httpd 服务器性能调优

热度:6865   发布时间:2013-02-26 00:00:00.0
AWS 上 Apache httpd 服务器性能调优

最近做了一个网站部署到AWS EC2上,启动之后访问速度奇慢无比,打开静态页面都要等好几分钟,这咋行!于是我开始研究AWS性能调优的问题。

?

开始怀疑是免费的micro instance配置太差,但想想Amazon也不至于这么不靠谱吧?于是ssh上去看了一眼top,里边的进程也没用掉多少CPU和内存,Swap也基本没有,所以基本排除服务器硬件资源不足的问题。

?

再往下就考虑优化一下httpd服务器性能,首先想到的是把所有的静态文件都缓存在内存里,这样可以减少不必要的IO,想必能提高访问速度。于是在Apache的文档里找到这篇<Apache Performance Tuning>:http://httpd.apache.org/docs/2.2/misc/perf-tuning ,还有这篇<Caching Guide>: http://httpd.apache.org/docs/2.2/caching,看了一遍之后,我认为主要有两个地方值得关注:

?

1. MMapFile 缓存

httpd可以把静态文件缓存到内存里,但是要注意每个子进程都会复制这部分内容,如果缓存的文件过大会导致频繁Swap,反而得不偿失了。所以对ServerLimit,MaxClients这些有关进程数量的参数都要仔细分析计算。具体说明如下:

?

mod_file_cache provides the MMapFile directive, which allows you to have Apache map a static file's contents into memory at start time (using the mmap system call). Apache will use the in-memory contents for all subsequent accesses to this file.

?

MMapFile /usr/local/apache2/htdocs/index

?

As with the CacheFile directive, any changes in these files will not be picked up by Apache after it has started.

?

The MMapFile directive does not keep track of how much memory it allocates, so you must ensure not to over-use the directive. Each Apache child process will replicate this memory, so it is critically important to ensure that the files mapped are not so large as to cause the system to swap memory.

?

具体做法是用ssh登陆到服务器,用如下命令生成一个配置文件,把某个静态文件目录(比如说/public/me/project/static/)下所有的文件设置为MMapFile缓存:

?

find /public/me/project/static/ -type f -print \ | sed -e 's/.*/mmapfile &/' > /www/conf/mmap.conf

?

然后用mv命令把该文件移到/etc/httpd/conf.d/ 目录下:

sudo mv /www/conf/mmap.conf /etc/httpd/conf.d/

?

在/etc/httpd/conf/httpd.conf里把这两个语句前的注释符号去掉并配置好文件名,启动时加载此配置文件:

## Load config files from the config directory "/etc/httpd/conf.d".#Include conf.d/mmap.conf.....LoadModule file_cache_module modules/mod_file_cache.so

?

至此,如果重新启动httpd服务,所有静态文件都会被缓存在内存中了。

?

2. 取消所有没用到的Modules

另外,在httpd.conf里看到,加载了一堆模块都是我用不上的,白白占用了宝贵的内存空间,还增加了请求的处理环节,岂不可恨!所以要把它们一一去掉,不过去掉的时候要小心,别为了提高性能引入了安全漏洞,得一个一个看清楚说明再改。最后我保留的模块只有这么几个:

  • LoadModule file_cache_module modules/mod_file_cache.so
  • LoadModule disk_cache_module modules/mod_disk_cache.so
  • LoadModule cache_module modules/mod_cache.so
  • LoadModule dir_module modules/mod_dir.so
  • LoadModule mime_module modules/mod_mime.so
  • LoadModule include_module modules/mod_include.so
    LoadModule log_config_module modules/mod_log_config.so

现在重新启动httpd,启动过程明显加快了:

sudo service httpd restart

可能会出一些错,说非法命令什么的,这是因为很多模块被取消了,但是配置文件里还在用它提供的配置参数,所以这些参数也不能用了。直接用vim编辑httpd.conf,把涉及非法命令的行都给他注释掉。然后重新启动httpd服务成功。

?

为了保存好这来之不易的配置,可以用scp命令通过ssh来下载这个文件:

?

scp -i /data/aws/keypair.pem ec2-user@12.34.56.78:/etc/httpd/conf/httpd.conf /data/project/conf/httpd.conf

?

再打开原先慢得像蜗牛的网站,哇!瞬间加载成功!说明这个性能调优的过程还是很成功的,而且我又学会了一招。于是今晚带老婆一起吃了顿全聚德烤鸭以示庆祝。

  相关解决方案