Performance Optimization of lamp (Linux + Apache + MySQL + PHP) servers
Contributed by jieshiwang, Cao jianghua
Source: http://www.ccw.com.cn/server/yyjq/htm2006/20060627_193322.htm
Currently lamp (Linux + Apache + MySQL + PHP) It has developed rapidly in recent years and has become a de facto standard for Web servers. The term lamp first came from the German magazine "C' t mag
Azine ", Michael Kunze first combined these projects in 1990 to create the abbreviation of lamp. Although these components are not designed for use at the beginning, these open-source software can be easily obtained at any time and free of charge. As a result, these components are often used together. Over the past few years, the compatibility of these components has been constantly improved, and the application situation has become very general. Some extension functions have been created to improve collaboration between different components. Currently, almost all Linux releases contain "LAMP stack" by default. These products form a powerful web application platform. Every component in LAMP stack is a FOSS (free or open source software) instance. There are three advantages of the FOSS method. First, the nature of the FOSS software means that applications can be downloaded for free, so that more people can use the software without paying. This free method is especially attractive to users. If these users do not use free software, they need to pay for "professional" commercial software tools. This is usually an expensive step in website creation. The FOSS license is open, so there are very few use and restrictions on Application Software Based on the FOSS technology. You can develop and apply lamp-based projects without having to pay any license fee for software release. Therefore, this is very attractive to amateurs and professionals. The main reason for the growth and use of FOSS technology (including lamp) is that users can access their resources, fix faults, and improve the performance of their applications. Combined with open-source software licenses, this approach simplifies the development process for many enterprises and provides them with the flexibility not limited by proprietary or commercial software. This article describes the performance optimization of lamp-based servers.
I. Linux host Performance Optimization
1. Clear server disk fragments:
No matter what file formats (ext3, JFS, XFS, and reiserfs) and what types of Hard Disks (IDE and SCSI) are used by the Linux File System, the file system tends to be fragmented over time. Ext3, JFS, and other advanced file systems can reduce file system fragmentation, but they are not eliminated. In a busy database server, file fragmentation will reduce the hard disk performance over time, and the hard disk performance can be noticed only when data is read or written from the hard disk. After a long time, you will find that a lot of junk files are accumulated on each disk. Releasing disk space can help the system better work. In Linux, the best way to clear disk fragments is to make a full backup, reformat the partition, and restore the file from the backup. However, it is difficult for a 7 × 24 key task server. Kleandisk is an efficient disk cleanup tool that divides files on disks into different "groups". For example, all "core" files are grouped into a group ), in this way, you only need to delete this group when deleting all core files. A core file is a file generated when a software running error occurs. It is useful to software developers and does not make any sense to other users (such as email servers. Therefore, if you do not need software development, you can delete the core file.
2. Enable hard disk DMA
Currently, the IDE Hard Drive supports dma66/100/133 (Direct Memory reading), but it is not enabled after the Linux release version is installed. It can be/etc/rc. d/rc. Lo.CAL add a line at the end:/sbin/hdparm-D1-x66-C3-M16/dev/hda. In this way, the DMA of the hard disk will be enabled each time it is started, without manual configuration. You can use the command hdparm-Tt/dev/hda to test and compare before and after adding.
3. Adjust the buffer refresh Parameters
The Linux kernel contains configurable parameters for the system running state. You can adjust the buffer refresh parameters by adjusting the/proc/sys/Vm/bdflush file. The format of this file is as follows:
# Cat/proc/sys/Vm/bdflush
30 64 64 256 500 3000 60 0 0
Each column is a parameter, the most important of which is the previous parameters. The first number is to force the bdflush process to refresh the hard disk when the "dirty" buffer reaches, and the second number is the number of dirty blocks each time the bdflush process refreshes. The dirty block must be written to the cache block on the disk. The following parameter lists the number of memory blocks allowed to be flushed into idle buffer blocks each time. The above values are the default values in RHEL 4.0. You can modify it in two ways:
(1) Use commands
# Echo "100 128 128 512 5000 3000 60 0 0">/proc/sys/Vm/bdflush
Add this command to the/etc/rc. d/rc. Local file.
(2) Add the following lines to the/etc/sysctl. conf file:
VM. bdflush = 100 128 128 512 5000 60 0 0
The preceding settings increase the buffer size and reduce the frequency of bdflush startup. The buffer refresh mechanism of VFS is one of the reasons for Linux file system efficiency.
4. Optimize Input and Output
I/O programs are also very important to Linux system performance, and network hardware I/O is especially important to servers. Currently, most Linux servers use 10/100 MB Ethernet. If there is a heavy network load, you can consider a Gigabit Ethernet Card. If you cannot buy a gigabit network card, you can use multiple network cards to create a virtual network card with the same IP address. In Linux, this technology is called bonding. Bonding is included in the kernel above linux2.4. You only need to select bonding driver support in the network device option during compilation, as shown in figure 1. Of course, the prerequisite for using Bonding Technology to configure dual-nic binding is that the two NICs have the same chipset model and have independent BIOS chips.
Figure 1 Linux kernel bonding driver support option
Then, recompile the core, restart the computer, and execute the following command:
# Ismod Bonding
# Ifconfig eth0 down
# Ifconfig eth1 down
# Ifconfig bond0 IPaddress
# Ifenslave bond0 eth0
# Ifenslave bond0 eth1
Now the two NICs are working like one. This improves data transmission between cluster nodes. bonding is a good choice for Servers. When there is no Gigabit Nic, using two 100 m NICs as the bonding can greatly increase the bandwidth between the server and the switch. however, you need to set the two sub-ports connected to the bonding Nic on the vswitch to map to the same Virtual Interface. Edit the/etc/modules. conf file and add the following content so that the system can load the bonding module at startup.
Alias bond0 Bonding
Options bond0 mode = 0
The value of "mode" indicates the working mode. There are four modes: 0, 1, 2, and 3. The value is set to 0. Bonding works in the load balancing (round-robin) mode, that is, two NICs work simultaneously. In this case, bonding can theoretically provide twice the bandwidth. Bonding runs in promisc mode and modifies the MAC addresses of the two NICs to the same. In hybrid mode, the NIC no longer only receives data frames whose destination hardware address is its MAC address, but can receive all frames on the network.
5. Reduce the number of virtual terminals.
After Linux is installed, the system defaults to 6 virtual terminals, that is, CTRL + ALT F1 ~ Six of F6, which can be used as servers, can be switched off, leaving only CTRL + ALT F1 ~ F2, which saves about 4 Mbytes of memory, but in this way, X-window will change from CTRL + ALT F7 to CTRL + ALT F3. In the/etc/inittab, set mingetty 3 ~ 6. Add the # font size to all parts.
6. disable unnecessary services.
When a Linux server is started, many system services need to be started. They provide Linux system function interfaces to local and network users and are directly oriented to applications and users. The programs that provide these services are executed by daemons running in the background. A daemon is a process with a long lifetime. They are independent of control terminals and periodically execute a task or wait for some events to be processed. They are often started during system boot loading and terminated when the system is shut down. In Linux, there are many daemon processes, and most servers use daemon. Such as Web Service HTTP. At the same time, the daemon completes many system tasks, such as job planning process crond and printing process lqd. Some books and materials also refer to the daemon process as "services ". For how to disable the service, see the author's article: a deep understanding of the Linux daemon process. Link: http://www.ccw.com.cn/server/yyjq/htm2005/20050914_14ND5_1.htm.
7. Use the tool software powertweak to optimize the system
Powertweak for linux0.99 can monitor your system and network connections, and set your system to the best.
Home: http://linux.powertweak.com/
Software installation:
# Wegt http://prdownloads.sourceforge.net/powertweak/powertweak-0.99.2-1.i386.rpm;
# Wegt http://prdownloads.sourceforge.net/powertweak/powertweak-gtk-0.99.2-1.i386.rpm
# Rpm-IVH powertweak-0.99.2-1.i386.rpm
# Rpm-IVH powertweak-gtk-0.99.2-1.i386.rpm
The powertweak-0.99.2-1.i386.rpm is the main program, and the powertweak-gtk-0.99.2-1.i386.rpm is the graphics front-end in the KDE environment. After the program is installed, it is automatically added to "System Tools" in the main menu. The running interface is shown in figure 2.
Figure-2 powertweak performance optimization program
Powertweak can be used to optimize X86 architecture processors, chipset, voodoo, and other software. It supports most of the central processors and chipset, includingIntel, AMD, and cyrix, with four built-in optimization settings, you can set the hardware you want to optimize (central processor, CD-Rom, PCI bus, hard disk, disk array), kernel (including logs, security, resources), network (including IP, TCP, core, ICMP, Unix domain routing, ARP, Token Ring), virtual file system, performance memory management (page allocation, high-speed cache, swap partition ). Powertweak is a powerful system performance tuning software. However, the requirements for users are relatively high. Many options require you to have a better understanding of the Linux system to be accurate.
For installation of Apache, PHP, and MySQL software, we recommend that you install the latest version from the source code. Although many Linux distributions (RedHat, Suse, and turbolinux) have the appropriate RPM packages, compiling and installing programs from the source code will suit your machine settings, it is usually installed in the/usr/local directory, which is easy to manage. The installation process is not described here.
Ii. Apache Server Detection and Optimization
1. Introduction to Zend Performance Suite
For Apache, you must compile PHP or use the DSO (dynamic shared object) mode. Do not use CGI. The most important reason for using DSO is efficiency. Apache is a modular design, so it can load a variety of server-side script interpreters to support dynamic web pages. However, as the page access volume increases, CGI is no longer overwhelmed to improve efficiency. Therefore, we chose to compile the most frequently called module into a dynamic shared object (DSO ). Zendperformancesuite produced by Zend is a tool for testing and optimizing the performance of Apache servers. It can be registered on its home page and downloaded for free. And get a protocol file. The downloaded package contains two files: Main Program: ZendPerformanceSuite-3.6.0a-Linux_glibc21-i386.tar.gz and Protocol File: zend_performance_suite.dat
2. software installation:
Gunzip ZendPerformanceSuite-3.6.0a-Linux_glibc21-i386.tar.gz
Tar vxf ZendPerformanceSuite-3.6.0a-Linux_glibc21-i386.tar
CP zend_performance_suite.dat/ZendPerformanceSuite-3.6.0
./Install
(1) software installation is very simple as long as you follow the prompts in the installation wizard, as shown in figure 3.
Figure 3 Software Installation Wizard
3. Test the Apache server
(1) Open a Web browser input: http://www.cjh.com/ZendPerformanceSuite/login.php
Enter the password to go to the main interface of the software.
(2) the main interface of zendperformancesuite is divided into four parts. See Figure 4.
Figure 4 main software interface
Zendperformancesuite consists of four parts: "fast track", "console", "FileView", and "testing ". Fast track is the Test Wizard, console is the parameter settings, FileView shows the stored files, and testing is the test command.
(3) parameter description
The "console" section is important. Here we will introduce its main options: see figure-3:
Figure 5 "console" page of the software
In this menu, set the parameters of the Apache server:
"Modified file detection": automatically checks the file type,
"Filepath identifiction": depth of all files,
"Accelerator memory": accelerates memory capacity,
"Memory reclaim threshold": Memory reclaim ratio,
"Maximum accelerated Files": Maximum number of files to be accelerated.
"Extensions for PHP files" extension file type,
Does "Dynamic Caching enabled" Support Dynamic Caching,
"Maximum Cache size" Maximum Cache capacity,
"Minimum free diskspace": Minimum disk space,
"Maximum cached file size" Maximum Cache file size,
"Default cache lifetime" indicates the default cache file survival time,
"Default Dynamic Caching conditions": Default cache status,
"Compress files" indicates whether to compress the file. Configure the parameters in the "console" based on your Apache server to test the performance. Currently, zendcompucesuite supports "Performance Test" and "compression test ).
(4) Stress Testing
The stress test is used as an example. after entering the parameters of the "console", you can perform the test. Select the "testing" menu to perform the test. The result is shown in-4.
Figure 6 Apache server stress test results
You can see that the test data is displayed in Figure 4 in two ways: numerical value. The performance test procedure is the same as the stress test. You need to modify the parameters in the "console" menu for multiple tests, and finally find the best option for your Apache server. Click "Apply change" to save the settings.
Zend Performance Suite is a software package that greatly improves Apache running efficiency! It can enhance the server's data throughput, save server resource consumption, and support Linux, Solaris, And FreeBSD. It can reduce server load, reduce page response time, and reduce database load. Increase user size and compress files. Flexible buffer configuration and application programming interface functions.
Iii. Accelerating PHP
1. Use eaccelerator
We have introduced the optimization of the Apache server. If you have browsed the php web page, you may find: How does PHP speed slowly? What is the matter? Isn't PHP a fast response? How can this happen slowly? This is because PHP program code calls too many function libraries, and each call to these function libraries needs to be read by the hard disk. Is there any way to speed up PHP Execution. If we can read these function libraries in the hard disk into the cache, the memory speed is much faster than that of the hard disk. In this way, it can certainly increase the speed. Here we will introduce a software license on GPL that can cache PHP code and optimize it, that is, eaccelerator his official website in: http://www.arnot.info/eaccelerator. Current version: 0.9.3.
2. download and install the software:
Wget http://internap.dl.sourceforge.net/sourceforge/eaccelerator/eaccelerator-0.9.3.tar.bz2
Tar jxf eaccelerator-0.9.3.tar.bz2
/Usr/local/bin/phpize
./Configure -- enable-eaccelerator = shared -- With-PHP-Config =/usr/local/bin/PHP-config
Make; make install
Modify the/etc/PHP. ini file and add the following content:
Extension = "/path/to/eaccelerator. So"
Eaccelerator. shm_size = "16"
Eaccelerator. cache_dir = "/tmp/eaccelerator"
Eaccelerator. Enable = "1"
Eaccelerator. optimizer = "1"
Eaccelerator. check_mtime = "1"
Eaccelerator. DEBUG = "0"
Eaccelerator. Filter = ""
Eaccelerator. shm_max = "0"
Eaccelerator. shm_ttl = "0"
Eaccelerator. shm_prune_period = "0"
Eaccelerator. shm_only = "0"
Eaccelerator. Compress = "1"
Eaccelerator. compress_level = "9"
Then create a directory for fast data access:
Mkdir/tmp/eaccelerator
Chmod 0777/tmp/eaccelerator
Restart the Apache server:
/Etc/rc. d/init. d/httpd restart
Open the web page in the lynx browser and check that phpinfo () shows figure 7, which indicates that the installation is successful.
Figure 7 enable eaccelerator
You can see that the eaccelerator is enabled. The following uses the AB command: Apache HTTP server performance testing tool, which is a tool to test your Apache HTTP server, you can use this tool to specify the number of requests sent to Apache within a unit of time to see the performance of your Apache and machine cooperation. The command is as follows:
/Home/Apache/bin/AB-C 20-N100-W http: // localhost/phpinfo> 1.html
-C: the number of requests sent to the server at the same time. By default, only one HTTP request is executed at a time.
-N: number of requests sent when a test session is executed.
-W: print the output result to the HTML table. The default table is a black box with N rows in white.
The requests per second (RPS) of the test data of apacheap refers to the number of pages returned by the server per second. After comparison, the web page speed is significantly faster with eaccelerator. Figure 8 test results of the lynx browser in HTML format.
Figure 8 HTML format test results
2. Use Zend Optimizer
Zend optimizer uses code optimization methods to speed up the execution of PHP 4.0 applications. The principle of implementation is to optimize the code generated by the run-time compiler before it is finally executed. Generally, the execution of a PHP program using Zend optimizer is 40% to 100% faster than that without Zend optimizer. This means that the visitor of the website can browse the webpage faster, so as to complete more transactions and create better customer satisfaction. Faster response also means saving hardware investment and enhancing the services provided by the website. Therefore, using Zend optimizer improves the profitability of e-commerce. Zend optimizer can bring many benefits to PhP users, especially those who operate websites. Quick running of the PHP program can significantly reduce the server's CPU load and reduce the response time by half, that is, the time between the visitor clicking the link to the server and reading the page.
Zend optimizer installation is a fool. The installation wizard automatically modifies PHP. ini based on your choice to help you start this engine.
Download and install the software:
Wget http://downloads.zend.com/optimizer/3.0.0/ZendOptimizer-3.0.0-linux-glibc21-i386.tar.gz
Gunzip ZendOptimizer-3.0.0-linux-glibc21-i386.tar.gz
Tar vxf ZendOptimizer-3.0.0-linux-glibc21-i386.tar
CD ZendOptimizer-3.0.0-linux-glibc21-i386
./Install
Figure 9 Zend optimizer Installation Wizard
Restart the Apache server:
/Etc/rc. d/init. d/httpd restart
On the web page, you can see the figure through phpinfo (), indicating that Zend optimizer is successfully installed.
Figure 10 Zend optimizer installed successfully
Then you can run the AB command to perform another test. The siege (http://www.joedog.org/siege/) can also be used for testing, which is a stress testing and evaluation tool designed for web development which assesses the application's affordability under pressure: you can perform concurrent access to multiple users on a Web site according to the configuration, record the corresponding time of all the request processes of each user, and repeat it with a certain number of concurrent accesses.
Iv. MySQL Optimization
For program developers, the two most popular backend databases are MySQL and SQL Server. The most basic similarity between the two is data storage and query system. If you want to establish a. NET Server System, which allows you to access data from multiple different platforms and manage databases, you can select the SQL Server server. If you want to create a third-party dynamic website from which you can read data from some clients, MySQL will be a good choice.
1. Compile and install MySQL
By selecting the best possible compiler in your system, you can generally achieve a performance improvement of 10-30%. On Linux/Intel Platform, use PGCC (GCC Pentium chip optimized version) to compile MySQL. However, binary code can only run on Intel Pentium CPU. For a specific platform, use the optimization options recommended in the MySQL reference manual. Compile MySQL with the character set you will use. Static compilation generates the mysqld execution file (use -- With-mysqld-ldflags = All-static) and uses strip SQL/mysqld to organize the final execution file. Note that since MySQL does not use C ++ extensions, compilation of MySQL without extensions won huge performance improvements.
2. Optimization table
MySQL has a set of rich types. Try to use the most effective type for each column. The analyse process helps you find the optimal table Type: Select * From table_name procedure analyse (). Not null is used for columns that do not store null values. This is especially important for the columns you want to index. Change the isam type table to MyISAM. Use a fixed table to create a table.
3. Correct Use of Indexes
Indexes are used to quickly search for records with specific values. All MySQL indexes are saved as B-trees. If no index exists, MySQL must scan all the records of the entire table from the first record until the required records are found. If the table has 1000 records, the index search records should be at least 100 times faster than the Sequential Scan records.
Suppose we have created a table named "people:
Create Table people (peopleid smallint not null, name char (50) not null );
Then, we randomly insert 1000 different name values into the people table.
However, indexes also have disadvantages. First, indexes occupy disk space. Generally, this problem is not very prominent. However, if you create an index for each possible combination of columns, the size of the index file will grow much faster than that of the data file. If you have a large table, the size of the index file may reach the maximum file size allowed by the operating system. If MySQL can predict that it will be faster than scanning the entire table, no index will be used. In addition, for operations that require data writing, such as Delete and update operations, indexes will reduce their speed. This is because MySQL not only writes the changed data to the data file, but also writes the changes to the index file.
4. Reduce the use of character sets to compile MySQL
MySQL currently provides up to 24 different character sets (many language versions), allowing global users to insert or view data in tables in their own language. By default, MySQL installs the character sets of the owner, so the best option is to install either of the two types you need (Chinese and English ).
Summary: This article describes how to improve system performance with existing hardware conditions. network administrators fully understand their computers and networks to find the real bottleneck. In today's budget shortage, understanding how to optimize system performance is more important than ever. Blindly investing in hardware is not a way to make people accept it-and it does not necessarily take effect.