首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Nginx 0.8.x + PHP 5.2.13(FastCGI)筹建胜过Apache十倍的Web服务器(第6版)【转载】

2012-08-10 
Nginx 0.8.x + PHP 5.2.13(FastCGI)搭建胜过Apache十倍的Web服务器(第6版)【转载】[文章作者:张宴 本文版本:

Nginx 0.8.x + PHP 5.2.13(FastCGI)搭建胜过Apache十倍的Web服务器(第6版)【转载】

[文章作者:张宴 本文版本:v6.3 最后修改:2010.07.26 转载请注明原文链接:http://blog.s135.com/nginx_php_v6/]

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

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

  Nginx 0.8.x + PHP 5.2.13(FastCGI)筹建胜过Apache十倍的Web服务器(第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 0.8.x + PHP 5.2.13(FastCGI)筹建胜过Apache十倍的Web服务器(第6版)【转载】

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

  Nginx 0.8.x + PHP 5.2.13(FastCGI)筹建胜过Apache十倍的Web服务器(第6版)【转载】

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

  Nginx 0.8.x + PHP 5.2.13(FastCGI)筹建胜过Apache十倍的Web服务器(第6版)【转载】


  下面是用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.s135.com/post/288/

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

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

????function_start_mysql
elif [ "$1" = "stop" ]; then
????function_stop_mysql
elif [ "$1" = "restart" ]; then
function_restart_mysql
elif [ "$1" = "kill" ]; then
function_kill_mysql
else
????printf "Usage: /data0/mysql/${mysql_port}/mysql {start|stop|restart|kill}\n"
fi


  ⑤、赋予shell脚本可执行权限:

chmod +x /data0/mysql/3306/mysql



  ⑥、启动MySQL:

/data0/mysql/3306/mysql start



  ⑦、通过命令行登录管理MySQL服务器(提示输入密码时直接回车):

/usr/local/webserver/mysql/bin/mysql -u root -p -S /tmp/mysql.sock



  ⑧、输入以下SQL语句,创建一个具有root权限的用户(admin)和密码(12345678):

GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY '12345678';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'127.0.0.1' IDENTIFIED BY '12345678';



  ⑨、(可选)停止MySQL:

/data0/mysql/3306/mysql stop



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

tar zxvf php-5.2.14.tar.gz
gzip -cd php-5.2.14-fpm-0.5.14.diff.gz | patch -d php-5.2.14 -p1
cd php-5.2.14/
./configure --prefix=/usr/local/webserver/php --with-config-file-path=/usr/local/webserver/php/etc --with-mysql=/usr/local/webserver/mysql --with-mysqli=/usr/local/webserver/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap
make ZEND_EXTRA_LIBS='-liconv'
make install
cp php.ini-dist /usr/local/webserver/php/etc/php.ini
cd ../



  4、编译安装PHP5扩展模块

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

tar jxvf eaccelerator-0.9.6.1.tar.bz2
cd eaccelerator-0.9.6.1/
/usr/local/webserver/php/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../

tar zxvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config --with-pdo-mysql=/usr/local/webserver/mysql
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/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../



  5、修改php.ini文件
  手工修改:查找/usr/local/webserver/php/etc/php.ini中的extension_dir = "./"
  修改为extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"
  并在此行后增加以下几行,然后保存:
  extension = "memcache.so"
  extension = "pdo_mysql.so"
  extension = "imagick.so"

  再查找output_buffering = Off
  修改为output_buffering = On

  再查找; cgi.fix_pathinfo=0
  修改为cgi.fix_pathinfo=0,防止Nginx文件类型错误解析漏洞。

  自动修改:若嫌手工修改麻烦,可执行以下shell命令,自动完成对php.ini文件的修改:

sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"\nextension = "memcache.so"\nextension = "pdo_mysql.so"\nextension = "imagick.so"\n#' /usr/local/webserver/php/etc/php.ini
sed -i 's#output_buffering = Off#output_buffering = On#' /usr/local/webserver/php/etc/php.ini
sed -i "s#; always_populate_raw_post_data = On#always_populate_raw_post_data = On#g" /usr/local/webserver/php/etc/php.ini
sed -i "s#; cgi.fix_pathinfo=0#cgi.fix_pathinfo=0#g" /usr/local/webserver/php/etc/php.ini



  6、配置eAccelerator加速PHP:

mkdir -p /usr/local/webserver/eaccelerator_cache
vi /usr/local/webserver/php/etc/php.ini


  按shift+g键跳到配置文件的最末尾,加上以下配置信息:

<configuration>

??All relative paths in this config are relative to php's install prefix

??<section name="global_options">

????Pid file
????<value name="pid_file">/usr/local/webserver/php/logs/php-fpm.pid</value>

????Error log file
????<value name="error_log">/usr/local/webserver/php/logs/php-fpm.log</value>

????Log level
????<value name="log_level">notice</value>

????When this amount of php processes exited with SIGSEGV or SIGBUS ...
????<value name="emergency_restart_threshold">10</value>

????... in a less than this interval of time, a graceful restart will be initiated.
????Useful to work around accidental curruptions in accelerator's shared memory.
????<value name="emergency_restart_interval">1m</value>

????Time limit on waiting child's reaction on signals from master
????<value name="process_control_timeout">5s</value>

????Set to 'no' to debug fpm
????<value name="daemonize">yes</value>

??</section>

??<workers>

????<section name="pool">

??????Name of pool. Used in logs and stats.
??????<value name="name">default</value>

??????Address to accept fastcgi requests on.
??????Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket'
??????<value name="listen_address">127.0.0.1:9000</value>

??????<value name="listen_options">

????????Set listen(2) backlog
????????<value name="backlog">-1</value>

????????Set permissions for unix socket, if one used.
????????In Linux read/write permissions must be set in order to allow connections from web server.
????????Many BSD-derrived systems allow connections regardless of permissions.
????????<value name="owner"></value>
????????<value name="group"></value>
????????<value name="mode">0666</value>
??????</value>

??????Additional php.ini defines, specific to this pool of workers.
??????<value name="php_defines">
????????<value name="sendmail_path">/usr/sbin/sendmail -t -i</value>
????????<value name="display_errors">0</value>
??????</value>

??????Unix user of processes
??????<value name="user">www</value>

??????Unix group of processes
??????<value name="group">www</value>

??????Process manager settings
??????<value name="pm">

????????Sets style of controling worker process count.
????????Valid values are 'static' and 'apache-like'
????????<value name="style">static</value>

????????Sets the limit on the number of simultaneous requests that will be served.
????????Equivalent to Apache MaxClients directive.
????????Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi
????????Used with any pm_style.
????????<value name="max_children">128</value>

????????Settings group for 'apache-like' pm style
????????<value name="apache_like">

??????????Sets the number of server processes created on startup.
??????????Used only when 'apache-like' pm_style is selected
??????????<value name="StartServers">20</value>

??????????Sets the desired minimum number of idle server processes.
??????????Used only when 'apache-like' pm_style is selected
??????????<value name="MinSpareServers">5</value>

??????????Sets the desired maximum number of idle server processes.
??????????Used only when 'apache-like' pm_style is selected
??????????<value name="MaxSpareServers">35</value>

????????</value>

??????</value>

??????The timeout (in seconds) for serving a single request after which the worker process will be terminated
??????Should be used when 'max_execution_time' ini option does not stop script execution for some reason
??????'0s' means 'off'
??????<value name="request_terminate_timeout">0s</value>

??????The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file
??????'0s' means 'off'
??????<value name="request_slowlog_timeout">0s</value>

??????The log file for slow requests
??????<value name="slowlog">logs/slow.log</value>

??????Set open file desc rlimit
??????<value name="rlimit_files">65535</value>

??????Set max core size rlimit
??????<value name="rlimit_core">0</value>

??????Chroot to this directory at the start, absolute path
??????<value name="chroot"></value>

??????Chdir to this directory at the start, absolute path
??????<value name="chdir"></value>

??????Redirect workers' stdout and stderr into main error log.
??????If not set, they will be redirected to /dev/null, according to FastCGI specs
??????<value name="catch_workers_output">yes</value>

??????How much requests each process should execute before respawn.
??????Useful to work around memory leaks in 3rd party libraries.
??????For endless request processing please specify 0
??????Equivalent to PHP_FCGI_MAX_REQUESTS
??????<value name="max_requests">1024</value>

??????Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.
??????Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+)
??????Makes sense only with AF_INET listening socket.
??????<value name="allowed_clients">127.0.0.1</value>

??????Pass environment variables like LD_LIBRARY_PATH
??????All $VARIABLEs are taken from current environment
??????<value name="environment">
????????<value name="HOSTNAME">$HOSTNAME</value>
????????<value name="PATH">/usr/local/bin:/usr/bin:/bin</value>
????????<value name="TMP">/tmp</value>
????????<value name="TMPDIR">/tmp</value>
????????<value name="TEMP">/tmp</value>
????????<value name="OSTYPE">$OSTYPE</value>
????????<value name="MACHTYPE">$MACHTYPE</value>
????????<value name="MALLOC_CHECK_">2</value>
??????</value>

????</section>

??</workers>

</configuration>

  9、启动php-cgi进程,监听127.0.0.1的9000端口,进程数为128(如果服务器内存小于3GB,可以只开启64个进程),用户为www:

ulimit -SHn 65535
/usr/local/webserver/php/sbin/php-fpm start


  注:/usr/local/webserver/php/sbin/php-fpm还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。


  三、安装Nginx 0.8.46
  1、安装Nginx所需的pcre库:

tar zxvf pcre-8.10.tar.gz
cd pcre-8.10/
./configure
make && make install
cd ../



  2、安装Nginx

tar zxvf nginx-0.8.46.tar.gz
cd nginx-0.8.46/
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
cd ../



  3、创建Nginx日志目录

mkdir -p /data1/logs
chmod +w /data1/logs
chown -R www:www /data1/logs



  4、创建Nginx配置文件
  ①、在/usr/local/webserver/nginx/conf/目录中创建nginx.conf文件:

rm -f /usr/local/webserver/nginx/conf/nginx.conf
vi /usr/local/webserver/nginx/conf/nginx.conf


  输入以下内容:

??????????????'$status $body_bytes_sent "$http_referer" '
??????????????'"$http_user_agent" $http_x_forwarded_for';
????access_log??/data1/logs/access.log??access;
??????}

??server
??{
????listen?????? 80;
????server_name??www.s135.com;
????index index.html index.htm index.php;
????root??/data0/htdocs/www;

????location ~ .*\.(php|php5)?$
????{??????
??????#fastcgi_pass??unix:/tmp/php-cgi.sock;
??????fastcgi_pass??127.0.0.1:9000;
??????fastcgi_index index.php;
??????include fcgi.conf;
????}

????log_format??wwwlogs??'$remote_addr - $remote_user [$time_local] "$request" '
?????????????? '$status $body_bytes_sent "$http_referer" '
?????????????? '"$http_user_agent" $http_x_forwarded_for';
????access_log??/data1/logs/wwwlogs.log??wwwlogs;
??}

??server
??{
????listen??80;
????server_name??status.blog.s135.com;

????location / {
????stub_status on;
????access_log?? off;
????}
??}
}



  ②、在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件:

vi /usr/local/webserver/nginx/conf/fcgi.conf


  输入以下内容:


  屏幕显示的即为Nginx主进程号,例如:
  6302
  这时,执行以下命令即可使修改过的Nginx配置文件生效:

kill -HUP 6302


  或者无需这么麻烦,找到Nginx的Pid文件:

kill -HUP `cat /usr/local/webserver/nginx/nginx.pid`



  七、编写每天定时切割Nginx日志的脚本
  1、创建脚本/usr/local/webserver/nginx/sbin/cut_nginx_log.sh

vi /usr/local/webserver/nginx/sbin/cut_nginx_log.sh


  输入以下内容:

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 /usr/local/webserver/nginx/nginx.pid`



  2、设置crontab,每天凌晨00:00切割nginx访问日志

crontab -e


  输入以下内容:

引用00 00 * * * /bin/bash??/usr/local/webserver/nginx/sbin/cut_nginx_log.sh




  本文若有小的修改,会第一时间在以下网址发布:
  http://blog.s135.com/nginx_php_v6/

热点排行