레이블이 Lamp인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Lamp인 게시물을 표시합니다. 모든 게시물 표시

2007년 9월 17일 월요일

Tuning LAMP systems, Part 2: Optimizing Apache and PHP

[Source] IBM developerWorks Tuning LAMP systems, Part 2

Tuning LAMP systems, Part 2: Optimizing Apache and PHP

What slows Apache down, and how to get the most out of PHP

Level: Intermediate

Sean A. Walberg (sean@ertw.com), Senior Network Engineer

30 Apr 2007

Applications using the LAMP (Linux®, Apache, MySQL, PHP/Perl) architecture are constantly being developed and deployed. But often the server administrator has little control over the application itself because it's written by someone else. This series of three articles discusses many of the server configuration items that can make or break an application's performance. This second article focuses on steps you can take to optimize Apache and PHP.

Linux, Apache, MySQL, and PHP (or Perl) form the basis of the LAMP architecture for Web applications. Many open source packages based on LAMP components are available to solve a variety of problems. As the load on an application increases, the bottlenecks in the underlying infrastructure become more apparent in the form of slow response to user requests. The previous article showed you how to tune the Linux system and covered the basics of LAMP and performance measurement. This article focuses on the Web server components, Apache and PHP.

Tuning Apache

Apache is a highly configurable piece of software. It has a lot of features, but each one comes at a price. Tuning Apache is partially an exercise in proper allocation of resources, and involves stripping down the configuration to only what's needed.

Configuring the MPM

Apache is modular in that you can add and remove features easily. Multi-Processing Modules (MPMs) provide this modular functionality at the core of Apache -- managing the network connections and dispatching the requests. MPMs let you use threads or even move Apache to a different operating system.

Only one MPM can be active at one time, and it must be compiled in statically with --with-mpm=(worker|prefork|event) .

The traditional model of one process per request is called prefork. A newer, threaded, model is called worker, which uses multiple processes, each with multiple threads to get better performance with lower overhead. The final, event MPM is an experimental module that keeps separate pools of threads for different tasks. To determine which MPM you're currently using, execute httpd -l.

Choosing the MPM to use depends on many factors. Setting aside the event MPM until it leaves experimental status, it's a choice between threads or no threads. On the surface, threading sounds better than forking, if all the underlying modules are thread safe, including all the libraries used by PHP. Prefork is the safer choice; you should do careful testing if you choose worker. The performance gains also depend on the libraries that come with your distribution and your hardware.

Regardless of which MPM you choose, you must configure it appropriately. In general, configuring an MPM involves telling Apache how to control how many workers are running, whether they're threads or processes. The important configuration options for the prefork MPM are shown in Listing 1.


Listing 1. Configuration of the prefork MPM
                
StartServers 50
MinSpareServers 15
MaxSpareServers 30
MaxClients 225
MaxRequestsPerChild 4000

In the prefork model, a new process is created per request. Spare processes are kept idle to handle incoming requests, which reduces the start-up latency. The previous configuration starts 50 processes as soon as the Web server comes up and tries to keep between 10 and 20 idle servers running. The hard limit on processes is dictated by MaxClients. Even though a process can handle many consecutive requests, Apache kills off processes after 4,000 connections, which mitigates the risk of memory leaks.

Configuring the threaded MPMs is similar, except that you must determine how many threads and processes are to be used. The Apache documentation explains all the parameters and calculations necessary.

Choosing the values to use involves some trial and error. The most important value is MaxClients. The goal is to allow enough worker processes or threads to run without causing your server to swap excessively. If more requests come in than can be handled, then at least those that made it through get service; the others are blocked.

If MaxClients is too high, then all clients experience poor service because the Web server tries to swap out one process to allow another one to run. Too low a setting means you may deny services unnecessarily. Checking the number of processes running at high loads and the resulting memory footprint of all the Apache processes gives you a good idea of how to set this value. If you go over 256 MaxClients, you must also set ServerLimit to the same number; read the MPM's documentation carefully for the associated caveats.

Tuning the number of servers to start and keep spare depends on the role of the server. If the server runs only Apache, you can use modest values as shown in Listing 1, because you're able to make full use of the machine. If the system is shared with a database or other server, then you should limit the number of spare servers being run.

Compiling your own software

When I got started with UNIX®, I insisted on compiling my own software for everything I put on my systems. Maintaining updates eventually caught up with me, so I learned how to build packages to ease this task. Eventually, I realized that most of the time I was duplicating the effort the distribution was doing; now, for the most part, I stick with whatever is provided by my distribution of choice when I can, and roll my own packages when I must.

Similarly, you may find that maintainability of vendor packages outweighs the benefits of going with the latest and greatest code. Sometimes performance tuning and systems administration have conflicting goals. You may have to consider vendor support if you're using a commercial Linux or relying on third-party support.

If you strike out on your own, learn how to build packages that work with your distribution and how to integrate them into your patching system. This will ensure that the software, along with any tweaks you make, are built consistently and can be used across multiple systems. Also keep on top of software updates by subscribing to the appropriate mailing lists and Rich Site Summary (RSS) feeds.


Using options and overrides efficiently

Each request that Apache processes goes through a complicated set of rules that dictates any restrictions or special instructions the Web server must follow. Access to a folder can be restricted by IP address to a certain folder, or a username and password can be configured. These options also include the handling of certain files, such as if a directory listing is provided, how certain filetypes are to be handled, or whether the output should be compressed.

These configurations take the form of containers in httpd.conf such as <Directory> to specify that the configuration to follow refers to a location on disk, or <Location> to indicate that the reference is to a path in the URL. Listing 2 shows a Directory container in action.


Listing 2. A Directory container being applied to the root directory

                
<Directory />
AllowOverride None
Options FollowSymLinks
</Directory>

In Listing 2, the configuration enclosed in the Directory and /Directory tags is applied to the given directory and everything under it — in this case, the root directory. Here, the AllowOverride tag dictates that users aren't allowed to override any options (more on this later). The FollowSymLinks option is enabled, which lets Apache look past symlinks to serve the request, even if the file is outside the directory containing Web files. This means that if a file in your Web directory is a symlink to /etc/passwd, the Web server happily serves the file if asked. With -FollowSymLinks used instead, this feature is disabled, and the same request causes an error to be returned to the client.

This last scenario is a cause for concern on two fronts. The first is a performance matter. If FollowSymLinks is disabled, then Apache must check each component of the filename (directories and the file itself) to make sure they're not symbolic links. This incurs extra overhead in the form of disk activity. A companion option called FollowSymLinksIfOwnerMatch follows the symbolic link if the owner of the file is the same as that of the link. This has the same performance hit as disabling following of symlinks. For best performance, use the options in Listing 2.

Security-conscious readers should be alert by now. Security is always a trade-off between functionality and risk. In this case, the functionality is speed, and the risk is allowing unauthorized access to files on the system. One of the mitigations is that LAMP application servers are generally dedicated to a particular function, and users can't create the potentially dangerous symbolic links. If it's vital to have symbolic link-checking enabled, you can restrict it to a particular area of the file system, as in Listing 3.


Listing 3. Restricting FollowSymLinks to a user's directory
                
<Directory />
Options FollowSymLinks
</Directory>

<Directory /home/*/public_html>
Options -FollowSymLinks
</Directory>

In Listing 3, any public_html directory in a user's home directory has the FollowSymLinks option removed for it and any child directories.

As you've seen, options can be configured on a per-directory basis through the main server configuration. Users can override this server configuration themselves (if permitted by the administrator by the AllowOverrides statement) by dropping a file called .htaccess into a directory. This file contains additional server directives that are loaded and followed on each request to the directory where the .htaccess file resides. Despite the earlier discussion about not having users on the system, many LAMP applications use this functionality to control access and for URL rewriting, so it's wise to understand how it works.

Even though the AllowOverrides statement prevents users from doing anything you don't want them to, Apache must still look for the .htaccess file to see if there is any work to be done. A parent directory can specify directives that are to be processed by requests from child directories, which means Apache must also search each component of the directory tree leading to the requested file. Understandably, this causes a great deal of disk activity on each request.

The easiest solution is to not allow any overrides, which eliminates the need for Apache to check for .htaccess. Any special configurations are then placed directly in httpd.conf. Listing 4 shows the additions to httpd.conf to enable password checking for a user's project directory, rather than putting in a .htaccess file and relying on AllowOverrides.


Listing 4. Moving .htaccess configuration into httpd.conf

                
<Directory /home/user/public_html/project/>
AuthUserFile /home/user/.htpasswd
AuthName "uber secret project"
AuthType basic
Require valid-user
</Directory>

If the configuration is moved into httpd.conf and AllowOverrides is disabled, disk usage can be reduced. A user's project may not attract many hits, but consider how powerful this technique is when applied to a busy site.

Sometimes it's not possible to eliminate use of .htaccess files. For example, in Listing 5, where an option is restricted to a certain part of the file system, overrides can also be scoped.


Listing 5. Scoping .htaccess checking
                
<Directory />
AllowOverrides None
</Directory>

<Directory /home/*/public_html>
AllowOverrides AuthConfig
</Directory>

After you implement Listing 5, Apache still looks for .htaccess files in the parent directories, but it stops in the public_html directory because the rest of the file system has the functionality disabled. For example, if a file that maps to /home/user/public_html/project/notes.html is requested, only the public_html and project directories are searched.

One final note about per-directory configurations is in order. Any document about tuning Apache will tell you to disable DNS lookups through the HostnameLookups off directive because trying to reverse-resolve every IP address connecting to your server is a waste of resources. However, any limitations based on hostname force the Web server to perform a reverse lookup on the client's IP address and a forward lookup on the result of that to verify the authenticity of the name. Therefore, it's wise to avoid using access controls based on the client's hostname and to scope them as described when they're necessary.

Persistent connections

When a client connects to a Web server, it's allowed to issue multiple requests over the same TCP connection, which reduces the latency associated with multiple connections. This is useful when a Web page refers to several images: The client can request the page and then all the images over one connection. The downside is that the worker process on the server has to wait for the session to be closed by the client before it can move on to the next request.

Apache lets you configure how persistent connections, called keepalives, are handled. KeepAlive 5 at the global level of httpd.conf allows the server to handle 5 requests on a connection before forcing the connection closed. Setting this number to 0 disables the use of persistent connections. KeepAliveTimeout, also at the global level, determines how long Apache will wait for another request before closing the session.

Handling persistent connections isn't a one-size-fits-all configuration. Some Web sites fare better with keepalives disabled (KeepAlive 0), and some experience a tremendous benefit by having them on. The only solution is to try both and see for yourself. It's advisable, though, to use a low timeout such as 2 seconds with KeepAliveTimeout 2 if you enable keepalives. This ensures that any client wishing to make another request has ample time, and that worker processes aren't idling while waiting for another request that may never come.

Compression

The Web server can compress the output before it's sent back to the client. This results in a smaller page being sent over the Internet at the expense of CPU cycles on the Web server. For those servers that can afford the CPU overhead, this is an excellent way of making pages download faster — it isn't unheard of for pages to be a third of their size after compression.

Images are generally already compressed, so compression should be limited to text output. Apache provides compression through mod_deflate. Although mod_deflate can be simple to turn on, it includes many complexities that the manual is eager to explain. This article doesn't cover the configuration of compression except to provide a link to the appropriate documentation (see the Resources section.)


Tuning PHP

PHP is the engine that runs the application code. You should install only the modules you plan to use and have your Web server configured to use PHP only for script files (usually those ending in .php) and not all static files.

Opcode caching

When a PHP script is requested, PHP reads the script and compiles it into what's called Zend opcode, a binary representation of the code to be executed. This opcode is then executed by the PHP engine and thrown away. An opcode cache saves this compiled opcode and reuses it the next time the page is called. This saves a considerable amount of time. Several opcode caches are available; I've had a great deal of success with eAccelerator.

Installing eAccelerator requires the PHP development libraries on your computer. Because different Linux distributions place files in difference places, it's best to get the installation instructions directly from the eAccelerator Web site (see the Resources section for a link). It's also possible that your distribution has already packaged an opcode cache, and you just have to install it.

Regardless of how you get eAccelerator on your system, there are a few configuration options to look at. The configuration file is usually /etc/php.d/eaccelerator.ini. eaccelerator.shm_size defines the size of the shared memory cache, which is where the compiled scripts are stored. The value is in megabytes. Determining the proper size depends on your application. eAccelerator provides a script to show the status of the cache, which includes the memory usage; 64 megabytes is a good start (eaccelerator.shm_size="64"). You may also have to tweak your kernel's maximum shared memory size if the value you choose isn't accepted. Add kernel.shmmax=67108864 to /etc/sysctl.conf, and run sysctl -p to make the setting take effect. The value for kernel.shmmax is in bytes.

If the shared memory allocation is exceeded, eAccelerator must purge old scripts from memory. By default, this is disabled; eaccelerator.shm_ttl = "60" specifies that when eAccelerator runs out of shared memory, any script that hasn't been accessed in 60 seconds should be purged.

Another popular alternative to eAccelerator is the Alternative PHP Cache (APC). The makers of Zend also have a commercial opcode cache that includes an optimizer to further increase efficiency.

php.ini

You configure PHP in php.ini. Four important settings control how much system resources PHP can consume, as listed in Table 1.


Table 1. Resource related settings in php.ini
Setting Description Recommended value
max_execution_time 
How many CPU-seconds a script can consume 30
max_input_time How long (seconds) a script can wait for input data 60
memory_limit How much memory (bytes) a script can consume before being killed 32M
output_buffering How much data (bytes) to buffer before sending out to the client 4096

These numbers depend mostly on your application. If you accept large files from users, then max_input_time may have to be increased, either in php.ini or by overriding it in code. Similarly, a CPU- or memory-heavy program may need larger settings. The purpose is to mitigate the effect of a runaway program, so disabling these settings globally isn't recommended. Another note on max_execution_time: This refers to the CPU time of the process, not the absolute time. Thus a program that does lots of I/O and few calculations may run for much longer than max_execution_time. It's also how max_input_time can be greater than max_execution_time

The amount of logging that PHP can do is configurable. In a production environment, disabling all but the most critical logs saves disk writes. If logs are needed to troubleshoot a problem, you can turn up logging as needed. error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR turns on enough logging to spot problems but eliminates a lot of chatter from scripts.


Summary

This article focused on tuning the Web server, both Apache and PHP. With Apache, the general idea is to eliminate extra checks the Web server must do, such as processing the .htaccess file. You must also tune the Multi-Processing Module you're using to balance the system resources used with the availability of idle workers for incoming requests. The best thing you can do for PHP is to install an opcode cache. Keeping your eye on a few resource settings also ensures that scripts don't hog resources and make the system slow for everyone else.

The next and final article in this series will look at tuning the MySQL database. Stay tuned!


Resources

more..

Tuning LAMP systems, Part 1: Understanding the LAMP architecture

[Source] IBM developerWorks Tuning LAMP systems, Part 1

Tuning LAMP systems, Part 1: Understanding the LAMP architecture

How LAMP systems work, how to measure their performance, and how to tune the underlying operating system

Level: Intermediate

Sean A. Walberg (sean@ertw.com), Senior Network Engineer

31 Mar 2007

Applications using the LAMP (Linux®, Apache, MySQL, PHP/Perl) architecture are constantly being developed and deployed. But often the server administrator has little control over the application itself because it's written by someone else. This series of three articles discusses many of the server configuration items that can make or break an application's performance. This first article covers the LAMP architecture, some measurement techniques, and some basic Linux kernel, disk, and file system tweaks. Successive articles investigate tuning the Apache, MySQL, and PHP components.

Linux, Apache, MySQL, and PHP (or Perl) are the foundation of many Web applications, from to-do lists to blogs to e-commerce sites. WordPress and Pligg are but two common software packages powering high-volume Web sites. This architecture has come to be known simply as LAMP. Almost every distribution of Linux includes Apache, MySQL, PHP, and Perl, so installing the LAMP software is almost as easy as saying it.

This ease of installation gives the impression that the software runs itself, which is simply not true. Eventually the load on the application outgrows the settings that come bundled with the back-end servers and application performance suffers. LAMP installations require constant monitoring, tuning, and evaluation.

Tuning a system has different meanings to different people. This series of articles focuses on tuning the LAMP components -- Linux, Apache, MySQL, and PHP. Tuning the application itself is yet another complex matter. There is a symbiotic relationship between the application and the back-end servers: a poorly tuned server causes even the best application to fail under load, and there's only so much tuning one can do to a server before a badly written application slows to a crawl. Fortunately, proper system tuning and monitoring can point to problems in the application.

The LAMP architecture

The first step in tuning any system is understanding how it works. At the simplest level, a LAMP-based application is written in a scripting language such as PHP that runs as part of the Apache Web server that is running on a Linux host.

The PHP application takes information from the client through the requested URL, any form data, and whatever session information has been captured to determine what it is supposed to do. If needed, the server pulls information from a MySQL database (also running on Linux), combines the information with some Hypertext Markup Language (HTML) templates, and returns it to the client. This process repeats itself as the user navigates the application and also occurs in parallel as multiple people access the system. The flow of data is not one way, however, because the database may be updated with information from the user in the form of session data, statistics collection (including voting), and user-submitted content such as comments or site updates. In addition to the dynamic elements, there are also static elements such as images, JavaScript code, and Cascading Style Sheets (CSS).

After looking at the flow of requests through the LAMP system, you can begin to see the points where slowdowns might occur. The database provides much of the dynamic information, so the client notices any delay in responding to queries. The Web server must be able to execute the scripts quickly and also handle multiple concurrent requests. Finally, the underlying operating system must be in good health to support the applications. Other setups that share files between different servers over the network can also become a possible bottleneck.

Variations on LAMP

LAMP started out as strictly Linux, Apache, MySQL, and PHP or Perl. It is not uncommon, however, to run Apache, MySQL, and PHP on Microsoft® Windows® if Linux isn't your strength. Then again, you can always swap out Apache for something like lighttpd, and you still have a LAMP-style system, albeit one with an unpronounceable acronym. Or you may prefer a different open source database such as PostgreSQL or SQLite, a commercial database such as IBM® DB2®, or even a commercial but free engine like IBM DB2 Express-C.

This article focuses on the traditional LAMP architecture because it's the one I see most often in my travels, and its components are all open source.

Measuring performance

Constant measurement of performance helps in two ways. The first is that measurement helps you spot trends, both good and bad. As a simple example, by watching central processing unit (CPU) usage on a Web server, you can see when it is overloaded. Similarly, watching the total bandwidth used in the past and extrapolating to the future helps you determine when network upgrades are needed. These measurements are best correlated with other measurements and observations. For example, you might determine that when users complain of application slowness, the disks happen to be operating at maximum capacity.

The second use of performance measurements is to determine if tuning has helped the situation or made it worse. You do this by comparing measurements before and after the change is made. For this to be effective, though, only one item should be changed at a time, and the proper metric should be compared to determine the effect of the change. The reason for changing only one thing at a time should be obvious. After all, it is quite possible that two simultaneous changes could counteract each other. The reason for the metrics statement is more subtle.

It is crucial that the metrics you choose to watch reflect on the user of the application. If the goal of a change is to reduce the memory footprint of the database, eliminating various buffers will certainly help, at the expense of query speed and application performance. Instead, one of the metrics should be application response time, which opens up tuning possibilities other than just the database's memory usage.

You can measure application response time in many ways. Perhaps the easiest is with the curl command shown in Listing 1.


Listing 1. Using cURL to measure the response time of a Web site

                
$ curl -o /dev/null -s -w %{time_connect}:%{time_starttransfer}:%{time_total}\
http://www.canada.com
0.081:0.272:0.779

Listing 1 shows the curl command being used to look up a popular news site. The output, which would normally be the HTML code, is sent to /dev/null with the -o parameter, and -s turns off any status information. The -w parameter tells curl to write out some status information such as the timers described in Table 1:


Table 1. Timers used by curl

TimerDescription
time_connectThe time it takes to establish the TCP connection to the server
time_starttransferThe time it takes for the Web server to return the first byte of data after the request is issued
time_totalThe time it takes to complete the request

Each of these timers is relative to the start of the transaction, even before the Domain Name Service (DNS) lookup. Thus, after the request was issued, it took 0.272 - 0.081 = 0.191 seconds for the Web server to process the request and start sending back data. The client spent 0.779 - 0.272 = 0.507 seconds downloading the data from the server.

By watching curl data and trending it over time, you get a good idea of how responsive the site is to users.

Of course, a Web site is more than just a single page. It has images, JavaScript code, CSS, and cookies to deal with. curl is good at getting the response time for a single element, but sometimes you need to see how fast the whole page loads.

The Tamper Data extension for Firefox (see the Resources section for a link) logs all the requests made by the Web browser and displays the time each took to download. To use the extension, select Tools > Tamper Data to open the Ongoing requests window. Load the page in question, and you'll see the status of each request made by the browser along with the time the element took to load. Figure 1 shows the results of loading the developerWorks home page.


Figure 1. Breakdown of requests used to load the developerWorks home page
Breakdown of requests           used to load the developerWorks home page

Each line describes the loading of one element. Various data are displayed, such as the time the request started, how long it took to load, the size, and the results. The Duration column lists the time the element itself took to load, while the Total Duration column shows how long all the sub elements took. In Figure 1, the main page took 516 milliseconds (ms) to load, but it was 5101 ms before everything was loaded and the entire page could be displayed.

Another helpful mode of the Tamper Data extension is to graph the output of the page load data. Right-click anywhere in the top half of the Ongoing requests window and select Graph all. Figure 2 shows a graphical view of the data from Figure 1.


Figure 2. A graphical view of requests used to load the developerWorks home page
A graphical view of           requests used to load the developerWorks home page

In Figure 2, the duration of each request is displayed in dark blue and is shown relative to the start of the page load. Thus, you can see which requests are slowing down the whole page load.

Despite the focus on page loading times and user experience, it is important not to lose sight of the core system metrics such as disk, memory, CPU, and network. A wealth of utilities are available to capture this information; perhaps the most helpful are sar, vmstat, and iostat. See the Resources section for more information about these tools.


Basic system tweaks

Before you tune the Apache, PHP, and MySQL components of your system, you should take some time to make sure that the underlying Linux components are operating properly. It goes without saying that you've already stripped down your list of running services to only those that you need. In addition to being a good security practice, doing so saves you both memory and CPU cycles.

Some quick kernel tuning

Most Linux distributions ship with buffers and other Transmission Control Protocol (TCP) parameters conservatively defined. You should change these parameters to allocate more memory to enhancing network performance. Kernel parameters are set through the proc interface by reading and writing to values in /proc. Fortunately, the sysctl program manages these in a somewhat easier fashion by reading values from /etc/sysctl.conf and populating /proc as necessary. Listing 2 shows some more aggressive network settings that should be used on Internet servers.


Listing 2. /etc/sysctl.conf showing more aggressive network settings
                
# Use TCP syncookies when needed
net.ipv4.tcp_syncookies = 1
# Enable TCP window scaling
net.ipv4.tcp_window_scaling = 1
# Increase TCP max buffer size
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
# Increase Linux autotuning TCP buffer limits
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
# Increase number of ports available
net.ipv4.ip_local_port_range = 1024 65000
Add this file to whatever is already in /etc/sysctl.conf. The first setting enables TCP SYN cookies. When a new TCP connection comes in from a client by means of a packet with the SYN bit set, the server creates an entry for the half-open connection and responds with a SYN-ACK packet. In normal operation, the remote client responds with an ACK packet that moves the half-open connection to fully open. An attack called the SYN flood ensures that the ACK packet never returns so that the server runs out of room to process incoming connections. The SYN cookie feature recognizes this condition and starts using an elegant method that preserves space in the queue (see the Resources section for full details). Most systems have this enabled by default, but it's worth making sure this one is configured.

Enabling TCP window scaling allows clients to download data at a higher rate. TCP allows for multiple packets to be sent without an acknowledgment from the remote side, up to 64 kilobytes (KB) by default, which can be filled when talking to higher latency peers. Window scaling enables some extra bits to be used in the header to increase this window size.

The next four configuration items increase the TCP send and receive buffers. This allows the application to get rid of its data faster so it can serve another request, and it also improves the remote client's ability to send data when the server gets busier.

The final configuration item increases the number of local ports available for use, which increases the maximum number of connections that can be served at a time.

These settings become effective at next boot or the next time sysctl -p /etc/sysctl.conf is run.

Configure disks for maximum performance

Disks play a vital role in the LAMP architecture. Static files, templates, and code are served from disk, as are the data tables and indexes that make up the database. Much of the tuning to follow, especially that pertaining to the database, focuses on avoiding disk access because of the relatively high latency it incurs. Therefore, it makes sense to spend some time optimizing the disk hardware.

The first order of business is to ensure that atime logging is disabled on file systems. The atime is the last access time of a file, and each time a file is accessed, the underlying file system must record this timestamp. Because atime is rarely used by systems administrators, disabling it frees up some disk time. This is accomplished by adding the noatime option in the fourth column of /etc/fstab. Listing 3 shows an example configuration.


Listing 3. A sample fstab showing how to enable noatime
                
/dev/VolGroup00/LogVol00 / ext3 defaults,noatime 1 1
LABEL=/boot /boot ext3 defaults,noatime 1 2
devpts /dev/pts devpts gid=5,mode=620 0 0
tmpfs /dev/shm tmpfs defaults 0 0
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
LABEL=SWAP-hdb2 swap swap defaults 0 0
LABEL=SWAP-hda3 swap swap defaults 0 0

Only the ext3 file systems have been modified in Listing 3 because noatime is helpful only for file systems that reside on a disk. A reboot is not necessary to effect this change; you only need to remount each file system. For example, to remount the root file system, run mount / -o remount.

A variety of disk hardware combinations are possible, and Linux doesn't always reliably detect the optimal way to access the disks. The hdparm command is used to get and set the methods used to access IDE disks. hdparm -t /path/to/device performs a speed test that you can use as a benchmark. For the most reliable results, the system should be idle when you run this command. Listing 4 shows a speed test being performed on hda.


Listing 4. A speed test being performed on /dev/hda
                
# hdparm -t /dev/hda

/dev/hda:
Timing buffered disk reads: 182 MB in 3.02 seconds = 60.31 MB/sec

As the test shows, the disks are reading data at around 60 megabytes (MB) per second.

Before delving into some of the disk tuning options, a warning is in order. The wrong setting can corrupt the file system. Sometimes you get a warning that the option isn't compatible with your hardware; sometimes you don't. For this reason, test settings thoroughly before putting a system into production. Having standard hardware across all your servers helps here too.

Table 2 lists some of the more common options.


Table 2. Common options for hdparm
OptionDescription
-viQuery the drive to determine which settings it supports and which settings it is using.
-cQuery/enable (E)IDE 32-bit I/O support. hdparm -c 1 /dev/hda enables this.
-mQuery/set multiple sectors per interrupt mode. If the setting is greater than zero, up to that number of sectors can be transferred per interrupt.
-d 1 -XEnable direct memory access (DMA) transfers and set the IDE transfer mode. The hdparm man page details the numbers that may go after the -X. You should need to do this only if -vi shows you're not using the fastest mode.

Unfortunately for Fiber Channel and Small Computer Systems Interface (SCSI) systems, tuning is dependent on the particular driver.

You must add whichever settings you find useful to your startup scripts, such as rc.local.

Network file system tuning

The network file system (NFS) is a way to share disk volumes across the network. NFS is helpful to ensure that every host has a copy of the same data and that changes are reflected across all nodes. By default, though, NFS is not configured for high-volume use.

Each client should mount the remote file system with rsize=32768,wsize=32768,intr,noatime to ensure the following:

  • Large read/write block sizes are used (up to the specified figure, in this case 32KB).
  • NFS operations can be interrupted in case of a hang.
  • The atime won't be constantly updated.

You can put these settings in /etc/fstab, as shown in Listing 3. If you use the automounter, these go in the appropriate /etc/auto.* file.

On the server side, it is important to make sure there are enough NFS kernel threads available to handle all your clients. By default, only one thread is started, though Red Hat and Fedora systems start at 8. For a busy NFS server, you should push this number higher, such as 32 or 64, to start. You can evaluate your clients to see if there was blockage with the nfsstat -rc command, which shows client Remote Procedure Call (RPC) statistics. Listing 5 shows the client statistics for a Web server.


Listing 5. Showing a NFS client's RPC statistics
                 
# nfsstat -rc
Client rpc stats:
calls retrans authrefrsh
1465903813 0 0
The second column, retrans, is zero, showing that no retransmissions were necessary since the last reboot. If this number is climbing, then you should consider adding more NFS kernel threads. This is done by passing the number of threads desired to rpc.nfsd, such as rpc.nfsd 128 to start 128 threads. You can do this at any time. Threads are started or destroyed as necessary. Again, this should go in your startup scripts, preferably in the script that starts NFS on your system.

A final note on NFS: Avoid NFSv2 if you can because performance is much less than in v3 and v4. This is not an issue in modern Linux distributions, but check the output of nfsstat on the server to see if any NFSv2 calls are being made.


Resources

more..


2007년 8월 29일 수요일

[OpenSuSE 10.2] LAMP Server Setup 2. Apache/PHP5

출처 : The Perfect Setup - OpenSuSE 10.2 (32-bit) 에서 발췌 & 번역.

Apache/PHP5

이제 우리는 Apache를 PHP5와 함께 설치한다:
# yast2 -i apache2 apache2-devel apache2-mod_perl apache2-mod_php5 apache2-prefork perl-HTML-Parser perl-HTML-Tagset perl-Tie-IxHash perl-URI perl-libwww-perl php5 php5-devel zlib zlib-devel
그리고 나서 필요한 PHP5의 module들을 설치한다:
# yast2 -i php5-bcmath php5-bz2 php5-calendar php5-ctype php5-curl php5-dbase php5-dom php5-ftp php5-gd php5-gettext php5-gmp php5-iconv php5-imap php5-ldap php5-mbstring php5-mcrypt php5-mhash php5-mysql php5-ncurses php5-odbc php5-openssl php5-pcntl php5-pgsql php5-posix php5-shmop php5-snmp php5-soap php5-sockets php5-sqlite php5-sysvsem php5-tokenizer php5-wddx php5-xmlrpc php5-xsl php5-zlib php5-exif php5-fastcgi php5-pear php5-sysvmsg php5-sysvshm ImageMagick curl
다음으로 /etc/apache2/httpd.conf를 수정한다:
# vi /etc/apache2/httpd.conf
DirectoryIndex를 다음과 같이 바꿔준다:
[...]
DirectoryIndex index.html index.htm index.shtml index.cgi index.php index.php5 index.php4 index.php3 index.pl index.html.var index.aspx default.aspx
[...]
/etc/sysconfig/apache2를 수정한다.
rewrite를 APACHE_MODULES line에 추가해준다:
# vi /etc/sysconfig/apache2
[...]
APACHE_MODULES="actions alias auth_basic authn_file
[...] setenvif ssl suexec userdir php5 rewrite"
[...]
또한 SSL을 APACHE_SERVER_FLAGS line에 추가해준다:
[...]
APACHE_SERVER_FLAGS="SSL"
[...]
이제 Apache가 boot 시 시작되도록 System을 설정한다:
# chkconfig --add apache2
그리고 나서 SuSEconfig를 실행하고 Apache를 시작한다.
# SuSEconfig
# /etc/init.d/apache2 start

/////////////////////////////////////////////////////////////////////////////////////////////////
Tattertools의 사용을 위해서는

1. 다음의 내용을 httpd.conf에 삽입한다.
<Directory "/srv/www/htdocs/tt">
    Options FollowSymLinks
    AllowOverride FileInfo
</Directory>
2. /srv/www/htdocs/tt와 /srv/www/htdocs/tt/skin의 소유권을 777로 변경한다.

[OpenSuSE 10.2] LAMP Server Setup 1. MySQL

출처 : The Perfect Setup - OpenSuSE 10.2 (32-bit) 에서 발췌 & 번역.

MySQL

MySQL을 설치하기 위해, 다음 명령을 실행한다.
# yast2 -i mysql mysql-client mysql-shared perl-DBD-mysql perl-DBI perl-Data-ShowTable mysql-devel
그리고 나서 MySQL을 위한 System Startup Link를 추가해주고 이것을 시작시킨다:
# chkconfig --add mysql
# /etc/init.d/mysql start

more..

이제 Networking이 사용가능하게 되어 있는 지 확인하기 위해 다음 명령을 실행한다.
# netstat -tap
출력에서 다음과 같은 내용을 볼 수 있어야만 한다:
     [...]
     tcp     0     0     *:mysql     *:*     LISTEN     4298/mysqld
     [...]

more..

이와 같은 내용이 보여지지 않는다면, /etc/my.cnf를 수정해야한다.
skip-networking option항목을 comment out한다:
# vi /etc/my.cnf
[...]
#skip-networking
[...]
그리고 MySQL Server를 재시작한다:
# /etc/init.d/mysql restart
Root user를 위한 Password를 지정해준다.(이렇게 하지 않으면 누구라도 당신의 MySQL Database에 접근할 수 있다.)
# mysqladmin -u root password rootsqlpassword
# mysqladmin -h server1.example.com -u root password rootsqlpassword

/////////////////////////////////////////////////////////////////////////////////////////////////
Tattertools의 사용을 위해서는
MySQL에 새로운 사용자를 생성하고 DB사용권한 설정을 해주어야한다.