Total Pageviews

Sunday 1 January 2012

25 Apache Performance Tuning Tips

本篇文章介绍25个Apache性能优化的技巧,如果你能理解并掌握,将让你的Apache性能有显著的提升!

Apache部分:

1. 移除不用的模块。

2. 使用 mod_disk_cache NOT mod_mem_cache 。

3. 扁平架构配置mod_disk_cache。

4. 安装恰当的Expires, Etag, 和 Cache-Control Headers 。

5. 将缓存放在独立的磁盘
Cheap Hotel in Sao Paulo
Cheap hotels Sao Paulo
We have the best rates!    Cheap Hotel in Porto Alegre
Hotel deals in Porto Alegre
Internet Only!
OnlineHotel Ads

6. 使用管道日志替代直接记录

7. 将日志放在不同的磁盘

8. 使用 mod_gzip/mod_deflate 。

9. 将HostnameLookups关闭.

10. 避免在configs中使用主机名。

11. 使用持久连接。

12. 不要设置KeepAliveTimeout太高。

13. 禁用.htaccess。

14. 允许symlinks。

15. 关闭ExtendedStatus。

16. 避免在DirectoryIndex中通配符。

OS 部分:

17. 提高Swappiness。

18. 提高写入缓冲器( Write Buffer)大小。

19. 提高最大打开文件。

应用部分:

20. 设置图像和样式表的前端代理。

21. 使用mod_passenger for rails。

22. 关闭safe_mode for php。

23. 不要使用threaded mpm with mod_php。

24. 刷新缓冲区预渲染。

25. 频繁访问的数据设置缓存。
---------------------------------


原文:

http://blog.monitis.com/index.php/2011/07/05/25-apache-performance-tuning-tips/


We all know and love Apache.  Its great, it allows us to run websites on the Internet with minimal configuration and administration.

However, this same ease of flexibility and lack of tuning, is typically what leads Apache to becoming a memory hog.  Utilizing these easy to understand tips, you can gain a significant performance boost from Apache.
Apache Specifics



1. Remove unused modules – save memory by not loading modules that you do not need, including but not limited to mod_php, mod_ruby, mod_perl, etc.

2. Use mod_disk_cache NOT mod_mem_cache - mod_mem_cache will not share its cache amongst different apache processes, which results in high memory usage with little performance gain since on an active server, mod_mem_cache will rarely serve the same page twice in the same apache process.

Monitis Monitoring Platform

3. Configure mod_disk_cache with a flat hierarchy – ensure that you are using CacheDirLength=2 and CacheDirLevels=1 to ensure htcacheclean will not take forever when cleaning up your cache directory.

4. Setup appropriate Expires, Etag, and Cache-Control Headers – to utilize your cache, you must tell it when a file expires, otherwise your client will not experience the caching benefits.

5. Put Cache on separate disk – place your cache on a separate physical disk for fastest access without slowing down other processes.

6. Use Piped Logging instead of direct logging – directly logging to a file has issues when you want to rotate the log file.  It must restart apache to use the next log file.  This will cause significant slowness for your users during the restart.  Particularly if you are using Passenger or some other app loader.

7. Log to a different disk than disk serving pages – put your logs on physically different disks than the files you are serving.

8. Utilize mod_gzip/mod_deflate – gzip your content before sending it off and then the client will ungzip upon receipt, this will minimize the size of file transfers, it generally will help all user experience.

9. Turn HostnameLookups Off – stop doing expensive DNS lookups.  You will rarely ever need them and when you do, you can look them up after the fact.

10. Avoid using hostname in configs – if you have HostnameLookups off, this will prevent you from having to wait for the DNS resolve of the hostnames in your configs, use IP addresses instead.

11. Use Persistent Connections - Set KeepAlive On and then set KeepAliveTimeout and KeepAliveRequests.  KeepAliveTimeout is how long apache will wait for the next request, and KeepAliveRequests is the max number of requests for a client prior to resetting the connection.  This will prevent the client from having to reconnect between each request.

12. Do Not set KeepAliveTimeout too high – if you have more requests than apache children, this setting can starve your pool of available clients.

13. Disable .htaccess - i.e. AllowOverride None  This will prevent apache from having to check for a .htaccess file on each request.

14. Allow symlinks – i.e. Options +FollowSymLinks -SymLinksIfOwnerMatch.  Otherwise, apache will make a separate call on each filename to ensure it is not a symlink.

15. Set ExtendedStatus Off - Although very useful, the ExtendedStatus will produce several system calls for each request to gather statistics.  Better to utilize for a set time period in order to benchmark, then turn back off.

16. Avoid Wildcards in DirectoryIndex – use a specific DirectoryIndex, i.e. index.html or index.php, not index
OS Specifics



17. Increase Swappiness – particularly on single site hosts this will increase performance.  On linux systems increase /proc/sys/vm/swappiness to at least 60 if not greater.  This will try to load as many files as possible into the memory cache for faster access.

18. Increase Write Buffer Size – increase your write buffer size for tcp/ip buffers.  On linux systems increase /proc/sys/net/core/wmem_max and /proc/sys/net/core/wmem_default. If your pages fit within this buffer, apache will complete a process in one call to the tcp/ip buffer.

19. Increase Max Open Files – if you are handling high loads increase the number of allowed open files.  On linux, increase /proc/sys/fs/file-max and run ulimit -H -n 4096.
Application Specifics



20. Setup Frontend proxy for images and stylesheets – allow your main web servers to process the application while images and stylesheets are served from frontend webservers

21. Use mod_passenger for rails – mod_passenger is able to share memory and resources amongst several processes, allowing for faster spawning of new application instances.  It will also monitor these processes and remove them when they are unnecessary.

22. Turn off safe_mode for php – it will utilize about 50-70% of your script time checking against these safe directives.  Instead configure open_base_dir properly and utilize plugins such as mod_itk.

23. Don’t use threaded mpm with mod_php – look at using mod_itk, mod_php tends to segfault with threaded mpm.

24. Flush buffers early for pre-render - it takes a relatively long time to create a web page on the backend, flush your buffer prior to page completion to send a partial page to the client, so it can start rendering.  A good place to do this is right after the HEAD section – so that the browser can start fetching other objects.

25. Use a Cache for frequently accessed data - memcached is a great for frequently used data and sessions.  It will speed up your apache render time as databases are slow.
And one more tip.  Your Apache performance is only as good as your benchmarks measuring it.  If you can’t get numbers or a graph to show that your performance has increased or load decreased, then you don’t know if your tuning has done you any good.  A great way to ensure that you are performing better than before is to use these techniques to hook up apache monitoring to Monitis hosted monitoring.
--------------------------------------------------------------------------------

Integrate Apache Monitoring into Monitis.com


Everyone knows what Apache web server is and that the Internet basically runs on it, but few know how to effectively monitor and graph statistics of Apache. Most people just check whether the website is available and leave it at that.  The cross your fingers and hope it works solution is not acceptable for Enterprise level of monitoring.Apache has a great tool to allow you to monitor your web server, mod_status. You can monitor such things as Total kBytes served, Total Uptime, Requests/Second, and much more.
However, when you enable this module, it only presents the data on a local machine. This can get very frustrating and annoying for the sysadmin who has many web servers to monitor. You would have to load up each web page on each server that presents the stats.  How annoying, now you have great statistics, but no reasonable way to view them across your multiple web-servers.
Monitis (https://www.monitis.com/), a hosted statistics and monitoring provider, offers a very simple solution to add these monitors in your Custom Dashboard.  Once you have these statistics available in your Dashboard, you will be able to easily get an overview of your Apache web servers and analyze the traffic that is on your web site. Be sure to get an account for Monitis here: https://www.monitis.com/free_signup.jsp before continuing.

Apache statistics

First you need to ensure that you have mod_status enabled:
a2enmod status
Then you need to configure Extended Status in your status module configuration:
<IfModule mod_status.c>
   ExtendedStatus On
   <Location /server-status>
     SetHandler server-status
     Order deny,allow
     Deny from all
     Allow from localhost ip6-localhost
   </Location>
</IfModule>
Now you are able to access http://localhost/server-status from the same machine. The server-status page has many useful statistics about apache currently running, and has an easier to parse version at http://localhost/server-status?auto
We will setup a Custom Monitor using a script downloadable free from github open source repository.
This script can be run like this to create a monitor that will store the information found on the server-status page:
./API/monitis_create_monitor.sh -n "Apache Monitor" -m apacheMonitor -r "Accesses:Total Accesses:count:2;kBytes:Total kBytes:kBytes:2;CPULoad:CPU Load:load:2;Uptime:Uptime:secs:2;ReqPerSec:Avg Requests per Sec:requests:2;BytesPerSec:Avg Bytes Per Sec:bytes:2;BusyWorkers:Busy Workers:count:2;IdleWorkers:Idle Workers:count:2;" -a API_Key -s Secret_Key
We will not store the Scoreboard. To populate the Custom Monitor we just created, we will use another script: monitis_apache_stats.sh. This script will collect the stats from the server-status page and then send them to Monitis. Be sure to update the script with the proper locations of the server-status page. You will also need another script downloaded from:monitis_add_data.sh in order to send the data to the Custom Monitor.
Now you can place the apache stats script in a crontab and gather the statistics automatically:
*/5 * * * * /path/to/monitis_apache_stats.sh #Gather stats every 5 mins
Here is a view of our Custom Monitor that we just setup with some data populated:
Apache Monitoring
And a graph of the results:
Apache Performance Monitoring

Apache Start, Stop, Restart and Reload Statistics

Say we also want to monitor the stopping, starting and reloading of Apache web server in our Custom Dashboard also. This will allow you to see that a website has been restarted, even though the sysadmin keeps telling you that it was not restarted. It will also allow you to see if issues are being caused by automated processes restarting Apache.
In order to monitor the starting and stopping of Apache we will use the same Custom Monitor creation script:monitis_create_monitor.sh to create our Custom Monitor:
./API/monitis_create_monitor.sh -n "Apache Monitor" -m apacheMonitor -r "action:Action:action:3;action_val:Action Value:value:2" -a API_Key -s Secret_Key
Now we can use the add data script:monitis_add_data.sh to send data to the Custom Monitor. In order to do this we will modify the Start/Stop commands in the Apache init script:
case $1 in
start)
…
/path/to/monitis_add_data.sh -m apacheStartStopMonitor -r "action:$1;action_val:1" -a API_Key -s Secret_Key > /dev/null
;;
stop)
…
/path/to/monitis_add_data.sh -m apacheStartStopMonitor -r "action:$1;action_val:0" -a API_Key -s Secret_Key > /dev/null
;;
And so on and so forth, for each case statement that you want to monitor the action on. The action_val is for graphing the results or for notification rules, any value can be placed in there, it may also be omitted completely.  The most useful case for this monitor is so that you can be alerted if someone “accidentally” stops the Apache service.  You can do this by setting up Custom Monitors Notifications.  From within the monitor, you can choose the Edit Icon in the upper right corner, and a screen will popup where you choose, Notification Rules:
Apache Alerts
Here you can setup a rule based on the action_val value.  For instance, if you want an alert each time your Apache is stopped – you will create an action when action_val = 0.

Conclusion

Now you are able to easily and efficiently monitor your Apache status, something that most organizations leave up to chance. This will allow you to analyze your web servers and know if you need to add another one or not. The graphs available to you will also show you your busy times versus your downtimes, allowing better planning and implementation strategies. The benefits to monitoring your Apache statistics in one easy to view Dashboard are vast. And you have it all in one place, easily accessible and easily graphed because you signed up for a Monitis account and utilized the Custom Monitoring features: https://www.monitis.com/free_signup.jsp
Monitis Monitoring Platform
External Scripts:
https://github.com/monitisexchange/Monitis-Linux-Scripts/blob/master/API/monitis_create_monitor.sh
https://github.com/monitisexchange/Monitis-Linux-Scripts/blob/master/API/monitis_add_data.sh
https://github.com/monitisexchange/Monitis-Linux-Scripts/blob/master/apache/monitis_apache_stats.sh

External Links for further information:
http://monitis.com/api/api.html#addCustomMonitor
https://www.monitis.com/free_signup.jsp

No comments:

Post a Comment