Nginx 1.9.x + PHP 5.6.x(FastCGI)搭建胜过Apache十倍的Web服务器(第7版)[原创]

[文章原作者:张宴 现修改:徐超 本文版本:v6.4 最后修改:2015.08.26 转载请注明原文链接:http://www.l68.net/472.html]

前言:本文是我撰写的关于搭建“Nginx + PHP(FastCGI)”Web服务器的第6篇文章。本系列文章作为国内最早详细介绍 Nginx + PHP 安装、配置、使用的资料之一,为推动 Nginx 在国内的发展产生了积极的作用。本文可能不断更新小版本,请记住原文链接“http://www.l68.net/472.html”,获取最新内容。第7篇文章主要介绍了Nginx 1.9.x,将PHP升级到了5.6.x。另将MySQL 5.1.x升级到了5.5.x系列,配置文件变更较大。

链接:《2007年9月的第1版》、《2007年12月的第2版》、《2008年6月的第3版》、《2008年8月的第4版》、《2009年5月的第5版》、《2009年5月的第6版

点击在新窗口中浏览此图片

Nginx (“engine x”) 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过三年了。Igor 将源代码以类BSD许可证的形式发布。

Nginx 超越 Apache 的高性能和稳定性,使得国内使用 Nginx 作为 Web 服务器的网站也越来越多,其中包括新浪博客新浪播客网易新闻腾讯网搜狐博客等门户网站频道,六间房56.com等视频分享网站,Discuz!官方论坛水木社区等知名论坛,盛大在线金山逍遥网等网络游戏网站,豆瓣人人网YUPOO相册金山爱词霸迅雷在线等新兴Web 2.0网站。


Nginx 的官方中文维基:http://wiki.nginx.org/NginxChs


在高并发连接的情况下,Nginx是Apache服务器不错的替代品。Nginx同时也可以作为7层负载均衡服务器来使用。根据我的测试结果,Nginx 0.8.46 + PHP 5.2.14 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍

根据我的经验,4GB内存的服务器+Apache(prefork模式)一般只能处理3000个并发连接,因为它们将占用3GB以上的内存,还得为系统预留1GB的内存。我曾经就有两台Apache服务器,因为在配置文件中设置的MaxClients为4000,当Apache并发连接数达到3800时,导致服务器内存和Swap空间用满而崩溃。

而这台 Nginx 0.8.46 + PHP 5.2.14 (FastCGI) 服务器在3万并发连接下,开启的10个Nginx进程消耗150M内存(15M*10=150M),开启的64个php-cgi进程消耗1280M内存(20M*64=1280M),加上系统自身消耗的内存,总共消耗不到2GB内存。如果服务器内存较小,完全可以只开启25个php-cgi进程,这样php-cgi消耗的总内存数才500M。

在3万并发连接下,访问Nginx 0.8.46 + PHP 5.2.14 (FastCGI) 服务器的PHP程序,仍然速度飞快。下图为Nginx的状态监控页面,显示的活动连接数为28457(关于Nginx的监控页配置,会在本文接下来所给出的Nginx配置文件中写明):

点击在新窗口中浏览此图片

我生产环境下的两台Nginx + PHP5(FastCGI)服务器,跑多个一般复杂的纯PHP动态程序,单台Nginx + PHP5(FastCGI)服务器跑PHP动态程序的处理能力已经超过“700次请求/秒”,相当于每天可以承受6000万(700*60*60*24=60480000)的访问量(更多信息见此),而服务器的系统负载也不高:

点击在新窗口中浏览此图片

2009年9月3日下午2:30,金山游戏《剑侠情缘网络版叁》临时维护1小时(http://kefu.xoyo.com/gonggao/jx3/2009-09-03/750438.shtml),大量玩家上官网,论坛、评论、客服等动态应用Nginx服务器集群,每台服务器的Nginx活动连接数达到2.8万,这是笔者遇到的Nginx生产环境最高并发值。

点击在新窗口中浏览此图片


下面是用100个并发连接分别去压生产环境中同一负载均衡器VIP下、提供相同服务的两台服务器,一台为Nginx,另一台为Apache,Nginx每秒处理的请求数是Apache的两倍多,Nginx服务器的系统负载、CPU使用率远低于Apache:

你可以将连接数开到10000~30000,去压Nginx和Apache上的phpinfo.php,这是用浏览器访问Nginx上的phpinfo.php一切正常,而访问Apache服务器的phpinfo.php,则是该页无法显示。4G内存的服务器,即使再优化,Apache也很难在“webbench -c 30000 -t 60 http://xxx.xxx.xxx.xxx/phpinfo.php”的压力情况下正常访问,而调整参数优化后的Nginx可以。

webbench 下载地址:http://blog.zyan.cc/post/288/

注意:webbench 做压力测试时,该软件自身也会消耗CPU和内存资源,为了测试准确,请将 webbench 安装在别的服务器上。

测试结果:##### Nginx + PHP #####

[root@localhost webbench-1.5]# webbench -c 100 -t 30 http://192.168.1.21/phpinfo.php
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://192.168.1.21/phpinfo.php
100 clients, running 30 sec.

Speed=102450 pages/min, 16490596 bytes/sec.
Requests: 51225 susceed, 0 failed.

top - 14:06:13 up 27 days,  2:25,  2 users,  load average: 14.57, 9.89, 6.51
Tasks: 287 total,   4 running, 283 sleeping,   0 stopped,   0 zombie
Cpu(s): 49.9% us,  6.7% sy,  0.0% ni, 41.4% id,  1.1% wa,  0.1% hi,  0.8% si
Mem:   6230016k total,  2959468k used,  3270548k free,   635992k buffers
Swap:  2031608k total,     3696k used,  2027912k free,  1231444k cached

测试结果:##### Apache + PHP #####

[root@localhost webbench-1.5]# webbench -c 100 -t 30 http://192.168.1.27/phpinfo.php
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://192.168.1.27/phpinfo.php
100 clients, running 30 sec.

Speed=42184 pages/min, 31512914 bytes/sec.
Requests: 21092 susceed, 0 failed.

top - 14:06:20 up 27 days,  2:13,  2 users,  load average: 62.15, 26.36, 13.42
Tasks: 318 total,   7 running, 310 sleeping,   0 stopped,   1 zombie
Cpu(s): 80.4% us, 10.6% sy,  0.0% ni,  7.9% id,  0.1% wa,  0.1% hi,  0.9% si
Mem:   6230016k total,  3075948k used,  3154068k free,   379896k buffers
Swap:  2031608k total,    12592k used,  2019016k free,  1117868k cached

为什么Nginx的性能要比Apache高得多?这得益于Nginx使用了最新的epoll(Linux 2.6内核)和kqueue(freebsd)网络I/O模型,而Apache则使用的是传统的select模型。目前Linux下能够承受高并发访问的Squid、Memcached都采用的是epoll网络I/O模型。

处理大量的连接的读写,Apache所采用的select网络I/O模型非常低效。下面用一个比喻来解析Apache采用的select模型和Nginx采用的epoll模型进行之间的区别:

假设你在大学读书,住的宿舍楼有很多间房间,你的朋友要来找你。select版宿管大妈就会带着你的朋友挨个房间去找,直到找到你为止。而epoll版宿管大妈会先记下每位同学的房间号,你的朋友来时,只需告诉你的朋友你住在哪个房间即可,不用亲自带着你的朋友满大楼找人。如果来了10000个人,都要找自己住这栋楼的同学时,select版和epoll版宿管大妈,谁的效率更高,不言自明。同理,在高并发服务器中,轮询I/O是最耗时间的操作之一,select和epoll的性能谁的性能更高,同样十分明了。


安装步骤:
(系统要求:Linux 2.6+ 内核,本文中的Linux操作系统为CentOS 6.6)

一、获取相关开源程序:
1、【适用CentOS操作系统】利用CentOS Linux系统自带的yum命令安装、升级所需的程序库(RedHat等其他Linux发行版可从安装光盘中找到这些程序库的RPM包,进行安装):

sudo -s
LANG=C
yum -y install patch make cmake gcc gcc-c++ gcc-g77 bison flex file libtool libtool-libs autoconf kernel-devel libjpeg libjpeg-devel libpng libpng-devel gd gd-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel gmp-devel gettext gettext-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers vim-minimal nano fonts-chinese gmp-devel pspell-devel unzip libcap diffutils readline-devel libxslt libxslt-devel ntp wget ctags

 

2、【适用CentOS、RedHat及其它Linux操作系统】下载程序源码包:
本文中提到的所有开源软件为截止到2010年07月26日的最新稳定版。
从软件的官方网站下载:

mkdir -p software
cd software
wget http://7xk96f.com1.z0.glb.clouddn.com/software/libiconv/libiconv-1.14.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/php/php-5.6.15.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/mcrypt/libmcrypt-2.5.8.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/mhash/mhash-0.9.9.9.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/mcrypt/mcrypt-2.6.8.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/luajit/LuaJIT-2.0.4.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/pcre/pcre-8.37.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/tengine/tengine-2.1.1.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/phpmyadmin/phpMyAdmin-4.4.13-all-languages.tar.gz
wget http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.45.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/php/p.tar.gz
wget http://7xk96f.com1.z0.glb.clouddn.com/software/zend/zend-loader-php5.6-linux-x86_64.tar.gz
wget http://www.imagemagick.org/download/ImageMagick.tar.gz
wget http://sourceforge.net/projects/boost/files/boost/1.59.0/boost_1_59_0.tar.gz/download

二、安装PHP 5.6.15(FastCGI模式)
1、编译安装PHP 5.6.15所需的支持库:

软件的默认安装目录是/usr/local

tar zxf libiconv-1.14.tar.gz
cd libiconv-1.14/
./configure
make && make install
cd ../

tar zxf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make && make install
ldconfig
cd libltdl/
./configure --enable-ltdl-install
make && make install
cd ../../

tar zxf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9/
./configure
make && make install
cd ../

ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1

tar zxf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make && make install
cd ../

tar zxf LuaJIT-2.0.4.tar.gz
cd LuaJIT-2.0.4/
make && make install
cd ../


 

2、编译安装PHP(FastCGI模式)

tar zxf php-5.6.15.tar.gz
cd php-5.6.15/
./configure --prefix=/usr/local --mandir=/usr/local/share/man --infodir=/usr/local/share/info --sysconfdir=/etc --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php --with-libxml-dir --with-openssl --with-kerberos --with-zlib --enable-bcmath --with-bz2 --enable-calendar --with-curl --enable-exif --enable-fpm --enable-ftp --with-png-dir --with-gd --with-jpeg-dir --enable-gd-native-ttf --with-icu-dir --enable-mbstring --enable-mbregex --enable-shmop --enable-soap --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-wddx --with-xmlrpc --with-readline --with-iconv-dir --with-xsl --enable-zip --with-pcre-regex --with-freetype-dir --enable-xml --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-pdo-sqlite --with-sqlite3 --disable-rpath  --enable-inline-optimization --with-mcrypt  --with-mhash --enable-pcntl --enable-sockets  --without-pear --with-gettext --enable-fileinfo --enable-opcache --enable-cli
make ZEND_EXTRA_LIBS='-liconv'
make install

cp php.ini-production /etc/php.ini
cp /etc/php-fpm.conf.default /etc/php-fpm.conf
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm
chkconfig php-fpm on
cd ../

3、编译安装PHP5扩展模块

tar zxvf memcache-2.2.5.tgz
cd memcache-2.2.5/
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/bin/php-config
make
make install
cd ../

tar zxvf ImageMagick.tar.gz
cd ImageMagick-6.5.1-2/
./configure
make
make install
cd ../

tar zxvf imagick-2.3.0.tgz
cd imagick-2.3.0/
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/bin/php-config
make
make install
cd ../

三、安装Tngine 2.1.1

1、安装Tngine所需的pcre库:

tar zxf pcre-8.37.tar.gz
cd pcre-8.37/
./configure --enable-utf8  
make && make install
cd ../

ln -s /usr/local/lib/libpcre.so.1 /usr/lib/libpcre.so.1

2、安装Tngine

tar zxf tengine-2.1.1.tar.gz
cd tengine-2.1.1
./configure --user=www --group=www --prefix=/usr/local --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-ipv6 --with-pcre-jit --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_spdy_module --with-http_stub_status_module --with-http_lua_module=shared --with-luajit-inc=/usr/local/include/luajit-2.0 --with-luajit-lib=/usr/local/lib --with-http_footer_filter_module=shared --with-http_sysguard_module=shared --with-http_limit_req_module=shared --with-http_trim_filter_module=shared --with-http_upstream_ip_hash_module=shared --with-http_upstream_least_conn_module=shared --with-http_upstream_session_sticky_module=shared --with-http_concat_module=shared

make && make install
cd ../

3、创建Tngine日志目录

mkdir /var/log/nginx
mkdir /var/lib/nginx
mkdir /usr/local/nginx/conf/sites-available
mkdir /usr/local/nginx/conf/sites-enabled

4、创建Tngine配置文件

/usr/sbin/groupadd www
/usr/sbin/useradd -m -g www www

5、启动Tngine

service nginx start

四、安装Mysql 5.7

1、安装Mysql

tar zxf boost_1_57_0.tar.gz
cp boost_1_57_0 /usr/local/src/boost
/usr/sbin/groupadd mysql
/usr/sbin/useradd -m -g mysql mysql

tar zxf mysql-5.7.9.tar.gz
cd mysql-5.7.9/
cmake -DCMAKE_INSTALL_PREFIX=/usr/local -DMYSQL_DATADIR=/home/mysql/data -DSYSCONFDIR=/etc -DMYSQL_USER=mysql -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_ARCHIVE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DMYSQL_TCP_PORT=3306 -DMYSQL_UNIX_ADDR=/tmp/mysqld.sock -DENABLED_LOCAL_INFILE=1 -DENABLE_DOWNLOADS=1 -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH_DEBUG=0 -DMYSQL_MAINTAINER_MODE=0 -DWITH_SSL=system -DWITH_ZLIB=system -DWITH_EMBEDDED_SERVER=1 -DWITH_BOOST=/usr/src/boost
make
make install
#配置my.conf
mv /etc/my.conf /etc/my.conf.bak
cp support-files/my-default.cnf /etc/my.conf
vi /etc/my.conf
#写入以下配置
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the
# *** default location during install, and will be replaced if you
# *** upgrade to a newer version of MySQL.

[client]
port=3306
socket=/tmp/mysql.sock

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
user = mysql
basedir = /usr/local
datadir = /home/mysql/data
port=3306
server-id = 1
socket=/tmp/mysql.sock

character-set-server = utf8
log-error = /var/log/mysql/error.log
pid-file = /var/run/mysql/mysql.pid
general_log = 1
skip-name-resolve
#skip-networking
back_log = 300

max_connections = 1000
max_connect_errors = 6000
open_files_limit = 65535
table_open_cache = 128 
max_allowed_packet = 4M
binlog_cache_size = 1M
max_heap_table_size = 8M
tmp_table_size = 16M

read_buffer_size = 2M
read_rnd_buffer_size = 8M
sort_buffer_size = 8M
join_buffer_size = 28M
key_buffer_size = 4M

thread_cache_size = 8

query_cache_type = 1
query_cache_size = 8M
query_cache_limit = 2M

ft_min_word_len = 4

log_bin = mysql-bin
binlog_format = mixed
expire_logs_days = 30


performance_schema = 0
explicit_defaults_for_timestamp

#lower_case_table_names = 1



myisam_sort_buffer_size = 8M
myisam_repair_threads = 1

interactive_timeout = 28800
wait_timeout = 28800


# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M 

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

# Recommended in standard MySQL setup
sql_mode=NO_ENGINE_SUBSTITUTION,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES 

[mysqldump]
quick
max_allowed_packet = 16M

[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
read_buffer = 4M
write_buffer = 4M

2、配置Mysql

#设置启动文件
cp support-files/mysql.server /etc/init.d/mysql
chmod +x /etc/init.d/mysql
#初始化数据库
mysqld --initialize --user=mysql --basedir=/usr/local --datadir=/home/mysql/data
#主意看初始化的最后一行,会告诉你root的密码是什么
mysql -uroot -p密码
SET PASSWORD = PASSWORD('123456');
#设置Mysql自动启动
chkconfig mysql on

3、启动Mysql

service mysql start

4、设置Mysql开启启动

chkconfig mysql on

四、配置开机自动启动Nginx + PHP

chkconfig nginx on
chkconfig php-fpm on

五、优化Linux内核参数

cat >>/etc/security/limits.conf<<eof
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
eof

echo "fs.file-max=65535" >> /etc/sysctl.conf

六、在不停止Nginx服务的情况下平滑变更Nginx配置

service nginx reload

七、编写每天定时切割Nginx日志的脚本

vi /usr/local/sbin/cut_nginx_log.sh
#!/bin/bash
# This script run at 00:00

# The Nginx logs path
logs_path="/var/log/nginx/"

mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /var/run/nginx.pid`

未经允许不得转载:SuperMan's blog » Nginx 1.9.x + PHP 5.6.x(FastCGI)搭建胜过Apache十倍的Web服务器(第7版)[原创]

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址