Build stable and reliable Apache, MySQL, and PHP

Source: Internet
Author: User
Tags epoll
  • I. Preface
  • Ii. Compilation and Installation
  • Iii. Install MySQL and memcache
  • 4. install Apache, PHP, eaccelerator, and PHP-memcache
  • 5. Install squid
  • Vi. Postscript

 

I. Preface

I. Preface and preparations
Currently, the lamp development mode is the first choice for web development. How to build an efficient, reliable, and stable web server is always a hot topic. This article is an attempt on this topic.
The architecture diagram is as follows:

-------- ---------- ------------- --------- ---------- | Client | ==>| Server Load balancer |==>| reverse proxy/cache |==>| Web Server |==> | Database server | -------- ---------- ------------- --------- ---------- nginx squid Apache, PHP MySQL/memcacheeaccelerator

Preparations:
Server: Intel (r) Xeon (TM) CPU 3.00 GHz X 2, 2 gb mem, scisc hard drive
Operating System: Linux Redhat as4, kernel version 2.6.9-22. elsmp, GCC version 3.4.4
Software:
Apache 2.2.3 (MPM mode available)
PHP 5.2.0 (this version is used because the engine of 5.2.0 is relatively more efficient)
Eaccelerator 0.9.5 (accelerates the PHP engine and encrypts the PHP source program)
Memcache 1.2.0 (used to cache frequently used data)
Libevent 1.2a (required for memcache operating mechanism)
MySQL 5.0.27 (use a binary version to save compilation effort)
Nginx 0.5.4 (used as a server Load balancer)
Squid-2.6.STABLE6 (providing professional caching while doing reverse proxy)

Ii. Compilation and Installation

Ii. Compilation and Installation
1) install nginx
1) install
Nginx is pronounced as [engine X] and is a project established by the Russian Igor Sysoev Based on the BSD license. It is said that he was a member of F5, Home: http://nginx.net. Some large Russian websites have been using it for more than two years and have been doing well.
The nginx compilation parameters are as follows:

[root@localhost]#./configure --prefix=/usr/local/server/nginx --with-openssl=/usr/include /--with-pcre=/usr/include/pcre/ --with-http_stub_status_module --without-http_memcached_module /--without-http_fastcgi_module --without-http_rewrite_module --without-http_map_module /--without-http_geo_module --without-http_autoindex_module

Here, we need to explain that because I want to use regular expressions in the nginx configuration filepcreModule support. I have installedpcreAndpcre-develBut ngxin cannot find the. h/. So/. A/. La file correctly, so I made some changes:

[root@localhost]#mkdir /usr/include/pcre/.libs/[root@localhost]#cp /usr/lib/libpcre.a /usr/include/pcre/.libs/libpcre.a[root@localhost]#cp /usr/lib/libpcre.a /usr/include/pcre/.libs/libpcre.la

Then, modifyobjs/MakefileComment out the following content at the location of approximately 908 rows:

./configure --disable-shared

Next, you can run the command normally.makeAndmake install.

2) modify the configuration file/usr/local/server/nginx/conf/nginx.conf
Here is mynginx.confContent, for reference only:

# Run the user nobody Nobody; # start the process worker_processes 2; # The global error log and the PID file error_log logs/error. log notice; PID logs/nginx. PID; # working mode and maximum number of connections events {use epoll; worker_connections 1024;} # Set the HTTP server, using its reverse proxy function, Server Load balancer supports HTTP {# setting the MIME type include CONF/mime. types; default_type application/octet-stream; # Set the log format log_format main' $ remote_addr-$ remote_user [$ time_local] ''" $ request "$ Status $ bytes_sent'' "$ http_referer" "$ http_user _ Agent "'' "$ gzip_ratio "'; log_format download '$ remote_addr-$ remote_user [$ time_local] ''" $ request "$ Status $ bytes_sent'' "$ http_referer" "$ http_user_agent" ''" $ http_range "$ sent_http_content_range "'; # Set Request Buffer client_header_buffer_size 1 K; limit 4 4 K; # enable gzip module gzip on; gzip_min_length 1100; gzip_buffers 4 8 K; gzip_types text/plain; output_buffers 1 32 K; postpone_output 1460; # Set access Logaccess_log logs/access. log main; client_header_timeout 3 m; client_body_timeout 3 m; send_timeout 3 m; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; # Set the Server list of Server Load balancer upstream mysvr {# The weigth parameter indicates the weight value. The higher the weight value, the higher the chance of being allocated to it # enable port 3128 server 192.168.8.1 on squid on the local machine: 3128 Weight = 5; server 192.168.8.2: 80 Weight = 1; server 192.168.8.3: 80 Weight = 6 ;}# set the VM server {Listen 80; SERVER_NAME 192.168.8.1 www.yejr.com; charset Gb2312; # Set the access log access_log logs/www.yejr.com. access. log main; # If you access/img/*,/JS/*,/CSS/* resources, you can directly retrieve local files without passing squid # If these files are large, this method is not recommended, because the cache effect through squid is better location ~ ^/(IMG | JS | CSS)/{root/data3/html; expires 24 h;} # enable Server Load balancer location/{proxy_pass http: // mysvr; proxy_redirect off; proxy_set_header host $ host; proxy_set_header X-real-IP $ remote_addr; proxy_set_header X-forwarded-for $ scheme; limit 10 m; Limit 128 K; Limit 90; Limit 90; proxy_read_timeout 90; proxy_buffer_size 4 K; proxy_buffers 4 32 K; Limit 64 K; Limit 64 K;} # Set the address location/nginxstatus {stub_status on; access_log on; auth_basic "nginxstatus"; auth_basic_user_file CONF/htpasswd ;}}}

Run the following command to check whether the configuration file is correct:

If no error is reported, you can start to run nginx and execute the following command:
Note: The content of the conf/htpasswd file can be generated using the htpasswd tool provided by Apache. The content is roughly as follows:
3) view nginx running status input address http: // 192.168.8.1/nginxstatus/, enter the verification account password, you can see the following content:
Active connections: 328server accepts handled requests9309 8982 28890Reading: 1 Writing: 3 Waiting: 324

The first line indicates the number of currently active connections.
The third number in the third row indicates the total number of requests received from nginx running to the current time. If the limit is reached, the upper limit must be increased.
The fourth line does not understand

Iii. Install MySQL and memcache
    
    

1) to install MySQL, follow these steps:

[root@localhost]#tar zxf mysql-standard-5.0.27-linux-i686.tar.gz -C /usr/local/server[root@localhost]#mv /usr/local/server/mysql-standard-5.0.27-linux-i686 /usr/local/server/mysql[root@localhost]#cd /usr/local/server/mysql[root@localhost]#./scripts/mysql_install_db --basedir=/usr/local/server/mysql /--datadir=/usr/local/server/mysql/data --user=nobody[root@localhost]#cp /usr/local/server/mysql/support-files/my-large.cnf //usr/local/server/mysql/data/my.cnf

2) modify the MySQL configuration and add some optimization parameters as follows:

[root@localhost]#vi /usr/local/server/mysql/data/my.cnf

The main content is as follows:

[Mysqld] basedir =/usr/local/Server/mysqldatadir =/usr/local/Server/MySQL/datauser = nobodyport = 3306 socket =/tmp/MySQL. sockwait_timeout = 30long_query_time = 1 # log-queries-not-using-indexes = truelog-Slow-queries =/usr/local/Server/MySQL/slow. loglog-error =/usr/local/Server/MySQL/error. logexternal-locking = bytes = 512mback_log = 400table_cache = bytes = 64mthread_concurrency = 4thread_stack = 128ktmp_table_size = bytes = 128mbulk_insert_buffer_size = 8mmyisam_repair_threads = 1skip-bdb # disable this option if InnoDB is not needed # skip-innodbinnodb_data_home_dir =/usr/local/Server/MySQL/data/innodb_data_file_path = ibdata1: 256 m; ibdata2: 256 m: export =/usr/local/Server/MySQL/data/innodb_log_arch_dir =/usr/local/Server/MySQL/data/innodb_buffer_pool_size = bytes = 2innodb_file_io_threads = 4innodb_thread_concurrency = 16innodb_log_files_in_group = 3

The preceding configuration parameters must be modified as needed.
Run the following command to start the MySQL server:

/usr/local/server/mysql/bin/mysqld_safe /--defaults-file=/usr/local/server/mysql/data/my.cnf &

Because MySQL is not installed in the standard directory, you must modify the location of the my_print_defaults file in mysqld_safe to pass
Mysqld_safe to start the MySQL server.

3. Install memcache + libevent
Compile and install:

[root@localhost]#cd libevent-1.2a[root@localhost]#./configure --prefix=/usr/ && make && make install[root@localhost]#cd ../memcached-1.2.0[root@localhost]#./configure --prefix=/usr/local/server/memcached --with-libevent=/usr/[root@localhost]#make && make install

NOTE: If libevent is not installed in the/usr directory, copy/link the libevent-1.2a.so.1 to/usr/lib; otherwise
Memcached cannot be loaded normally.
Run the following command to start memcached:

[root@localhost]#/usr/local/server/memcached/bin/memcached /-l 192.168.8.1 -d -p 10000 -u nobody -m 128

It means to start memcached in daemon mode, listen to port 10000 of 192.168.8.1, run the user as nobody, assign it
The memory size is 128 MB.

 

 

4. install Apache, PHP, eaccelerator, and PHP-memcache

4) install Apache, PHP, eaccelerator, and PHP-memcache
Because Apache
2. Static PHP compilation is very troublesome, so dynamic module (DSO) is used here.
1) install Apache 2.2.3

[root@localhost]#./configure --prefix=/usr/local/server/apache --disable-userdir --disable-actions /--disable-negotiation --disable-autoindex --disable-filter --disable-include --disable-status /--disable-asis --disable-auth --disable-authn-default --disable-authn-file --disable-authz-groupfile /--disable-authz-host --disable-authz-default --disable-authz-user --disable-userdir /--enable-expires --enable-module=so

Note: unnecessary modules are removed here. If you need to use these modules, remove some parameters.

2) install PHP 5.2.0

[root@localhost]#./configure --prefix=/usr/local/server/php --with-mysql /--with-apxs2=/usr/local/server/apache/bin/apxs --with-freetype-dir=/usr/ --with-png-dir=/usr/ /--with-gd=/usr/ --with-jpeg-dir=/usr/ --with-zlib --enable-magic-quotes --with-iconv /--without-sqlite --without-pdo-sqlite --with-pdo-mysql --disable-dom --disable-simplexml /--enable-roxen-zts[root@localhost]#make && make install

Note: If you do not need gd or PDO modules, remove them.

3) install eAccelerator-0.9.5

[root@localhost]#cd eAccelerator-0.9.5[root@localhost]#export PHP_PREFIX=/usr/local/server/php[root@localhost]#$PHP_PREFIX/bin/phpize[root@localhost]#./configure --enable-eaccelerator=shared --with-php-config=$PHP_PREFIX/bin/php-config[root@localhost]#make && make install

4) install the memcache Module

[root@localhost]#cd memcache-2.1.0[root@localhost]#export PHP_PREFIX=/usr/local/server/php[root@localhost]#$PHP_PREFIX/bin/phpize[root@localhost]#./configure --enable-eaccelerator=shared --with-php-config=$PHP_PREFIX/bin/php-config[root@localhost]#make && make install

5.) modify the php. ini configuration.
Modify PHP. ini and add the following content:

Extension_dir = "/usr/local/Server/PHP/lib/" extension = "eaccelerator. so "eaccelerator. shm_size = "32"; set the shared memory of the eaccelerator to 32mbeaccelerator. cache_dir = "/usr/local/Server/eaccelerator" eaccelerator. enable = "1" eaccelerator. optimizer = "1" eaccelerator. check_mtime = "1" eaccelerator. DEBUG = "0" eaccelerator. filter = "*. PHP "eaccelerator. shm_max = "0" eaccelerator. shm_ttl = "0" eaccelerator. shm_prune_period = "3600" eaccelerator. shm_only = "0" eaccelerator. compress = "1" eaccelerator. compress_level = "9" eaccelerator. LOG_FILE = "/usr/local/Server/Apache/logs/eaccelerator_log" eaccelerator. allowed_admin_path = "/usr/local/Server/Apache/htdocs/ea_admin" extension = "memcache. so"

Here, it is best to add the default file type cache mechanism in Apache configuration, that is, using the expires module of Apache, add lines similar to the following:

ExpiresActive OnExpiresByType text/html "access plus 10 minutes"ExpiresByType text/css "access plus 1 day"ExpiresByType image/jpg "access 1 month"ExpiresByType image/gif "access 1 month"ExpiresByType image/jpg "access 1 month"ExpiresByType application/x-shockwave-flash "access plus 3 day"

This setting is because my static files are rarely updated, so I chose the "access" rule. If the updates are relatively frequent, you can use the "modification" rule instead; you can also use the "access" rule, but when the file is updated, run the "Touch" command to refresh the file time.

 

 

 

5. Install squid

5. Install squid

[root@localhost]#./configure --prefix=/usr/local/server/squid --enable-async-io=100 --disable-delay-pools /--disable-mem-gen-trace --disable-useragent-log --enable-kill-parent-hack --disable-arp-acl /--enable-epoll --disable-ident-lookups --enable-snmp --enable-large-cache-files --with-large-files[root@localhost]#make && make install

If it is a 2.6 kernel, only the epoll I/O mode can be supported. The earlier kernel version can only be poll or another mode. In addition, remember to include the option to support large files. Otherwise
When the number of log files reaches 2 GB, an error is reported.
Configure squid as follows:

# Set the cache directory to/var/cache1 and/var/lib/squid. The cache size for each processing is 128 MB, when the cache space reaches 95%, # The new content replaces the old one and is not directly added to the directory, this activity will not be stopped until the space drops to 90% #/var/cache1 up to 1024 MB,/var/lib/squid up to 5000 MB, all are 16*256 subdirectories cache_dir aufs/var/cache1 1024 16 256cache_dir aufs/var/lib/squid 5000 16 256cache_mem 128 running 95 # setting storage policies and other maximum_object_size 4096 limit 0 limit 80 kbipcache_size 1024ipcache_low 90ipcache_high 95cache_replacement_policy lrumemory_replacement_policy LRU # Set the Timeout Policy forward_timeout 20 secondsconnect_timeout 15 secondsread_timeout 3 limit 1 limit 15 limit 15 limit 5 limit 10 seconds # limit one IP address to a maximum of 16 connection ACLs overconnlimit maxconn 16http_access deny overconnlimit # Restrict Baidu spider access # ACL antibaidu req_header User-Agent baiduspider # http_access deny antibaidu # Set visible_hostname cache in general. yejr. comcache_mgr webmaster@yejr.comclient _ persistent_connections please wait too long 65535 off # Set the cache-free rules against CGI-binacl query urlpath_regex CGI-bincache deny query # Do not trust etag because of the gzipacl Apache rep_header server ^ handle allow Apache # Set access log, the format is the same as that of Apache, so that AWStats can analyze emulate_httpd_log onlogformat Apache %> A % UI % UN [% TL] "% RM % Ru HTTP/% RV" % hs %
     

Initialize and start squid

[root@localhost]#/usr/local/server/squid/sbin/squid -z[root@localhost]#/usr/local/server/squid/sbin/squid

The first command First initializes the Squid cache hash sub-directory and only needs to be executed once.

Vi. Postscript
      
      

Vi. Postscript
1) changes required to enable squid
To make better use of squid's cache function, you can simply enable it. We need to make the following adjustments:

1. Enable Apachemod_expiresModule, modify httpd. conf, and add the following content:

# Expiresdefault "modification plus 2 weeks"
Expiresactiveon
Expiresbytype text/html "access plus 10 minutes"
Expiresbytypeimage/GIF "modification plus 1 month"
Expiresbytype image/JPEG "modificationplus 1 month"
Expiresbytype image/PNG "modification plus 1 month"
Expiresbytype text/CSS "access plus 1 day"
Expiresbytypeapplication/X-Shockwave-flash "access plus 3 day"

The above configuration sets the cache rules for various types of files. static files such as images and Flash files are always cached and can be adjusted as needed.

2. Modify the php. ini configuration as follows:

Session. cache_limiter = nocache

The above configuration is used to cancel the cache function in PHP by default to avoid abnormal cache generation.

3. modify the application
For example, there is a PHP program page
Static. php stores the results of some queries to the database, and the data is not updated frequently. Therefore, we can consider its cache. Just add the following code in static. php:

Header ('cache-control: Max-age = 86400, must-revalidate ');
Header ('pragma :');
Header ('Last-modified: '. gmdate ('d, D m y h: I: s'). 'gmt ');
Header ("expires:". gmdate ('d, d m yh: I: s', time () + '000000'). 'gmt ');

The code above indicates that an HTTP header is output to let squid know that the default cache duration for this page is one day.

Ii. Brief Introduction to squidclient

* Obtain squid running status information: squidclient-P 80 Mgr: info
* Obtain squid memory usage: squidclient-P80 Mgr: Mem
* Obtain the squid cached list: squidclient-P 80 Mgr: objects. Use it carefully, it may crash
* Obtain squid disk usage: squidclient-P 80 Mgr: diskd
* Force update a URL: squidclient-P 80-M purge http://www.yejr.com/static.php
* For more information, see squidclient-H or squidclient-P 80 Mgr:

Finally, I wish you a better and better Server :)

Related Article

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.