Tuning php_php Tutorials

Source: Internet
Author: User
Tags disk usage zend
Apache is a highly configurable software. It has a lot of features, but each one is expensive. To some extent, tuning Apache is the proper way to allocate resources, and it involves simplifying the configuration to include only the necessary content.
Configuring MPM
Apache is modular because features can be easily added and removed. At the core of Apache, the multi-processing module (multi-processing MODULE,MPM) provides this modular functionality-management of network connectivity, scheduling requests. MPM enables you to use threads and even to migrate Apache to another operating system.
Only one MPM can be active at a time and must be statically compiled with--with-mpm= (worker|prefork|event).
The traditional model of using one process per request is called Prefork. The newer threading model, called worker, uses multiple processes, each with multiple threads, to achieve better performance at a lower cost. The latest event MPM is an experimental model that uses a separate thread pool for different tasks. To determine what type of MPM is currently in use, execute the httpd-l.
Choosing which MPM to use depends on many factors. You should not consider this model until the event MPM is out of the experimental state, but instead choose between using the thread and not using the thread. On the surface, if all the underlying modules (including all libraries used by PHP) are thread-safe, the thread is better than the fork (forking). Prefork is a safer option and should be tested carefully if a worker is selected. Performance benefits also depend on the libraries and hardware that came with your release.
Regardless of which MPM you choose, you must properly configure it. Typically, configuring MPM includes telling Apache how to control how many workers are running, whether they are threads or processes. The important configuration options for Prefork MPM are shown in Listing 1.

Listing 1. Configuration of the Prefork MPM

Startservers 50
Minspareservers 15
Maxspareservers 30
MaxClients 225
Maxrequestsperchild 4000

Compiling your own software
When I first used UNIX®, I insisted on compiling software for all the systems I joined. Eventually, maintenance updates brought me trouble, so I learned how to build packages to simplify this task. Then I realized that most of the time I was doing things that I had done in the release version. Now, to a large extent, I will try my best to stick with everything I've chosen for the release, and use my own packages only when necessary.
Similarly, you might find that using vendor-provided packages is better than using the latest, best-in-the-way code for maintainability. There are times when performance tuning and system management goals are conflicting. If you use a commercial version of Linux or rely on third-party support, you may have to consider vendor support.
If you do, learn how to build a package that works with your release, learn how to integrate it into a patch system. This will ensure that the software, as well as any changes you make, are built consistently and can be used across multiple systems. You should also subscribe to the appropriate mailing lists and RSS feeds to get software updates in a timely manner.
The Prefork model creates a new process for each request. Redundant processes remain idle to handle incoming requests, which shortens the startup delay. As long as the Web server appears, the pre-completed configuration starts 50 processes immediately and tries to keep 10 to 20 idle servers running. The hard limit for the number of processes is specified by maxclients. Although a process can handle many successive requests, Apache cancels the process after the number of connections exceeds 4,000, which reduces the risk of memory leaks.
Configuring a threaded MPM is similar, except that you must determine how many threads and processes are used. The Apache documentation explains all the necessary parameters and calculations.
You can choose the value you want to use after several attempts and errors. The most important value is maxclients. The goal is to allow enough workder processes or threads to run without causing the server to be over-exchanged. If the incoming request exceeds the processing power, then those requests that satisfy at least this value are serviced and other requests are blocked.
If the maxclients is too high, then all clients will experience a bad service because the WEB server will attempt to swap out a process to enable another process to run. Being too low means that services may be denied unnecessarily. Viewing the number of processes running under high load and the memory consumption caused by all Apache processes can be helpful in setting this value. If the value of MaxClients exceeds 256, the Serverlimit must also be set to the same value, please read the MPM documentation carefully for relevant information.
Tune the number of servers you want to start and keep idle based on the role of the server. If the server only runs Apache, you can use a modest value, as shown in Listing 1, because you can take advantage of the machine. If there are other databases or servers in the system, you should limit the number of idle servers that are running.
Efficient use of options and overrides
Each request processed by Apache fulfills a complex set of rules that indicate the constraints or special instructions that the WEB server must follow. Access to a folder may be constrained to a specific folder by IP address, or it can be configured with a user name and password. These options also include processing a specific file, for example, if a directory listing is provided, what to do with the file, or whether the output should be compressed.
These configurations occur in the form of containers in httpd.conf, such as so that the specified configuration refers to a location on the disk, and , again, the reference is a path in the URL. Listing 2 shows an actual Directory container.

Listing 2. A directory container that is applied to the root directory


AllowOverride None
Options FollowSymLinks

In Listing 2, the configuration between a pair of directory and/directory tags is applied to the given directory and everything in that directory-in this case, the given directory is the root directory. Here, the allowoverride tag indicates that the user is not allowed to override any of the options (further described later). The FollowSymLinks option is enabled, which allows Apache to view the previous symbolic connection to serve the request, even if the file is located outside the directory containing the Web file. This means that if a file in the Web directory is a symbolic connection to/etc/passwd, the Web server will service the file successfully when requested. If-followsymlinks is used, the feature is disabled and the same request causes an error to be returned to the client.
Finally, this scenario is the cause of both concerns. The first aspect is related to performance. If you disable Followsymlinks,apache, you must check all components that use the file name (the directory and the file itself) to ensure that they are not symbolic connections. This can result in additional overhead (disk operations). Another option, called Followsymlinksifownermatch, uses symbolic connections between the file owner and the connection owner. For best performance, use the options in Listing 2.
At this point, a safe-minded reader should have a sense of vigilance. Security is always the tradeoff between functionality and risk. In our case, the functionality is speed, and the risk is that unauthorized access to the files on the system is allowed. One of the measures to mitigate risk is that the LAMP application server typically focuses on a specific function, and users cannot create dangerous symbolic connections. If you need to enable symbolic connections, you can constrain them to specific areas of the file system, as shown in Listing 3.

Listing 3. Constrain followsymlinks to a user's directory


Options FollowSymLinks


Options-followsymlinks

In Listing 3, the FollowSymLinks option is removed from any public_html directory and all subdirectories in one user's home directory.
As you can see, the options are configured individually for each directory through the master server configuration. Users can override this server configuration themselves (if the administrator allows this through the Allowoverrides statement), simply put a. htaccess file in the directory. The file contains additional server directives that are loaded and applied each time a directory containing the. htaccess file is requested. Although it has been discussed that the system does not have a user problem, many LAMP applications use this functionality to control access and implement URL rewriting, so it is necessary to understand how it works.
Even if the Allowoverrides statement prevents users from doing what you do not want them to do, Apache must also check the. htaccess file to see if there is work to be done. The parent directory can specify instructions that are processed by requests from subdirectories, which means that Apache must search all components of the directory tree for the requested file. It is conceivable that this causes a large number of disk operations per request.
The simplest solution is not to allow rewriting, which eliminates the need for Apache inspection. htaccess. Any subsequent special configuration will be placed directly in the httpd.conf. Listing 4 shows the code added to httpd.conf for password checking of a user's project directory instead of putting it into a. htaccess file and relying on Allowoverrides.

Listing 4. Move the. htaccess configuration into the httpd.conf


authuserfile/home/user/.htpasswd
AuthName "Uber secret project"
AuthType Basic
Require Valid-user

If the configuration is transferred to httpd.conf and Allowoverrides is disabled, the disk usage can be reduced. A user's project may not attract many people to click on, but imagine how powerful it can be to apply this technology to a busy site.
It is sometimes impossible to completely eliminate the use of. htaccess files. For example, in Listing 5, an option is constrained to a specific part of the file system, and overrides can also be scoped.

Listing 5. Limit the scope of the. htaccess check


Allowoverrides None


Allowoverrides authconfig

After implementing listing 5, Apache looks for the. htaccess file in the parent directory, but stops at the public_html directory because the rest of the file system disables this feature. For example, if you are requesting a file that is mapped to/home/user/public_html/project/notes.html, then only the public_html and project directories are searched.
The last hint about the individual configuration of each directory is that it should be done sequentially. Any article introducing Apache tuning will tell you that DNS lookups should be disabled through the hostnamelookups off directive because attempting to reverse resolve all IP addresses connected to your server is a waste of resources. However, any constraint based on the hostname will force the WEB server to perform a reverse lookup of the client's IP address and a forward lookup of its results to verify the authenticity of the name. Therefore, it is advisable to avoid using access control based on the client hostname, to qualify its scope when it must be used.
Persistent connections
When a client connects to a WEB server, it allows the client to make multiple requests over the same TCP connection, which reduces the latency associated with multiple connections. This is useful when multiple images are referenced in a Web page: A client can request a page first and then request all of the pictures through a connection. The disadvantage is that the worker process on the server must wait for the session that the client is shutting down before it can go to the next request.
Apache enables you to configure how persistent connections (known as keepalives) are handled. HTTPD.CONF Global KeepAlive 5 allows the server to process 5 requests on a connection before the connection is forced to close. Setting this value to 0 disables persistent connections. KeepAliveTimeout, also at the global level, determines how long Apache will wait for another connection before the session is closed.
The processing of persistent connections is not a "one-size-fits-all" configuration. For some Web sites, disabling keepalives is more appropriate (KeepAlive 0), while for some other sites, enabling it can be a huge benefit. The only solution is to try these two configurations and see for yourself which is more appropriate. But if keepalives is enabled, it is wiser to use a smaller timeout, such as 2, or KeepAliveTimeout 2. This ensures that clients wishing to make another request have sufficient time to ensure that the worker process does not remain idle and waits for the next request that may never occur.
Compression
The WEB server can compress the output before it is sent back to the client. This will make the pages sent over the Internet smaller, at the expense of the CPU cycles on the WEB server. This is a good way to increase the speed of page downloads for those servers that can afford CPU overhead--it's not uncommon for a page to become one-third of the size of the original.
Pictures are usually already compressed, so compression should be limited to text output. Apache provides compression via mod_deflate. Although mod_deflate can be easily enabled, it involves too much complexity, and many manuals explain these complex content. The compressed configuration is not covered in this article, but links to the appropriate documentation are provided (see the Resources section).
Tuning PHP
PHP is the engine that runs the application code. You should install only those modules that you plan to use and configure your WEB server to use PHP, not all static files, only for script files (usually those that end in. php).
OpCode cache
When a PHP script is requested, PHP reads the script and compiles it into a Zend opcode, which is a binary representation of the code to be executed. This opcode is then executed by PHP and discarded. The opcode cache will save the compiled opcode and reuse it the next time the page is called. This will save a lot of time. There are a variety of cache available, I am more commonly used is eaccelerator.
To install eaccelerator, you need a PHP development library on your computer. Because different Linux distributions have different locations for files, it is best to get installation instructions directly from the Eaccelerator Web site (see the Resources section for links). Your release may already contain an opcode cache, just install it.
Regardless of the installation of Eaccelerator on the system, there are some configuration options to be aware of. The configuration file is usually/etc/php.d/eaccelerator.ini. Eaccelerator.shm_size defines the size of the shared cache, and the compiled script is stored here. The unit of the value is megabytes (MB). Determine the appropriate size based on your application. Eaccelerator provides a script to show the state of the cache, which contains memory footprint, 64MB is a good choice (eaccelerator.shm_size= "64"). If the value you select is not accepted, you must modify the maximum shared memory size of the kernel. Add kernel.shmmax=67108864 to/etc/sysctl.conf and run Sysctl-p for the settings to take effect. The units of the Kernel.shmmax value are bytes.
If the allocation of shared memory exceeds the limit, eaccelerator must purge the old script from memory. By default, this is disabled; Eaccelerator.shm_ttl = "60" specifies that when Eaccelerator runs out of shared memory, all scripts that are not accessed within 60 seconds are purged.
Another popular Eaccelerator replacement tool is the alternative PHP Cache (APC). Zend's vendors also provide a business opcode cache, including an optimizer that further improves efficiency.
Ini
The configuration of PHP is done in php.ini. Four important settings control how much of the system resources PHP can use, as listed in table 1.

Table 1. Resource-related settings in php.ini
Set Description Suggestion Value
Max_execution_time How many CPU seconds a script can use 30
Max_input_time How long a script waits for input data (seconds) 60
Memory_limit How much memory (in bytes) a script can use before it is canceled 32M
How much data (bytes) need to be cached before output_buffering data is sent to the client 4096
The exact number depends on your application. If you want to receive large files from the user, the max_input_time may have to be increased, modified in php.ini, or rewritten by code. Similarly, programs that are CPU-or memory-intensive may also require a larger set-up value. The goal is to mitigate the effects of superscalar programs, so disabling these settings globally is not recommended. There is one more thing to note about Max_execution_time: it represents the CPU time of the process, not the absolute time. So a program that does a lot of I/O and a small amount of computation can run far more than Max_execution_time. This is why Max_input_time can be larger than max_execution_time.
The number of log records that PHP can perform is configurable. In a production environment, disabling all log records except for the most important logs can reduce disk write operations. If you need to use logs to troubleshoot problems, you can enable logging on demand. error_reporting = e_compile_error| e_error| E_core_error will enable enough logging to cause you to discover problems while eliminating a lot of useless content from the script.

http://www.bkjia.com/PHPjc/478737.html www.bkjia.com true http://www.bkjia.com/PHPjc/478737.html techarticle Apache is a highly configurable software. It has a lot of features, but each one is expensive. To some extent, tuning Apache is allocating resources in the right way ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.