本文已有最新版本:

  请点击Nginx 0.8.x + PHP 5.2.13(FastCGI)搭建胜过Apache十倍的Web服务器(第6版)




  [文章作者:张宴 本文版本:v2.1 最后修改:2008.02.27 转载请注明出处:http://blog.zyan.cc]

  前言:本文为我2007年9月写过的文章《Nginx 0.5.31 + PHP 5.2.4(FastCGI)搭建可承受3万以上并发连接数,胜过Apache 10倍的Web服务器》的第2版,经过了多台服务器的测试,修正了PHP iconv和gd库冲突的BUG,增加了PHP mcrypt、memcache扩展,修改了PHP和Nginx编译参数,优化了Nginx配置文件,添加了部分功能。

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

  Nginx 的中文维基:http://wiki.codemongers.com/NginxChs



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

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

  而这台 Nginx 0.5.33 + PHP 5.2.5 (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.5.33 + PHP 5.2.5 (FastCGI) 服务器的PHP程序,仍然速度飞快。下图为Nginx的状态监控页面,显示的活动连接数为28457(关于Nginx的监控页配置,会在本文接下来所给出的Nginx配置文件中写明):

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

  以下为 Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 服务器在3万并发连接下,开启的10个Nginx进程和64个php-cgi进程时的系统负载情况:

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



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

  一、获取相关开源程序:
  1、下载程序源码包到当前目录:
  本文中提到的所有开源软件为截止到2007年11月25日的最新稳定版。我将它们打了两个压缩包。

  第一个压缩包:nginx-php-1.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746375

  第二个压缩包:nginx-php-2.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746370

  附:各开源软件单独下载地址(如果下载了以上两个压缩包,则无需下载以下软件):
  http://down.zyan.cc/linux/nginx-php/ (登录用户名、密码均为blog.zyan.cc)

  2、解压缩:
mkdir -p /data0/software
cd /data0/software
unzip nginx-php-1.zip
unzip nginx-php-2.zip
cd /data0/software/nginx-php



  二、安装PHP 5.2.5(FastCGI模式)
  1、编译安装PHP 5.2.5所需的支持库:
tar zxvf libiconv-1.11.tar.gz
cd libiconv-1.11/
./configure --prefix=/usr/local
make
make install
cd ../

tar zxvf freetype-2.3.5.tar.gz
cd freetype-2.3.5/
./configure
make
make install
cd ../

tar zxvf libpng-1.2.20.tar.gz
cd libpng-1.2.20/
./configure
make
make install
cd ../

tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b/
./configure --enable-static --enable-shared
make
make install
make install-lib
cd ../

#----If your system was install libxml2, you do not need to install it.----
#tar zxvf libxml2-2.6.30.tar.gz
#cd libxml2-2.6.30/
#./configure
#make
#install
#cd ../

tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make
make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

tar zxvf mhash-0.9.9.tar.gz
cd mhash-0.9.9/
./configure
make
make install
cd ../

cp /usr/local/lib/libmcrypt.* /usr/lib
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2

tar zxvf mcrypt-2.6.6.tar.gz
cd mcrypt-2.6.6/
./configure
make
make install
cd ../



  2、编译安装MySQL 5.0.45
/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql
tar zxvf mysql-5.0.45.tar.gz
cd mysql-5.0.45
./configure --prefix=/usr/local/webserver/mysql/ --without-debug --with-unix-socket-path=/tmp/mysql.sock --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static --enable-assembler --with-extra-charsets=gbk,gb2312,utf8 --with-pthread --enable-thread-safe-client
make && make install
chmod +w /usr/local/webserver/mysql
chown -R mysql:mysql /usr/local/webserver/mysql
cp support-files/my-medium.cnf /usr/local/webserver/mysql/my.cnf
cd ../



  附:以下为附加步骤,如果你想在这台服务器上运行MySQL数据库,则执行以下两步。如果你只是希望让PHP支持MySQL扩展库,能够连接其他服务器上的MySQL数据库,那么,以下两步无需执行。
  ①、以mysql用户帐号的身份建立数据表:
/usr/local/webserver/mysql/bin/mysql_install_db --defaults-file=/usr/local/webserver/mysql/my.cnf --basedir=/usr/local/webserver/mysql --datadir=/usr/local/webserver/mysql/data --user=mysql --pid-file=/usr/local/webserver/mysql/mysql.pid --skip-locking --port=3306 --socket=/tmp/mysql.sock


  ②、启动MySQL(最后的&表示在后台运行)
/bin/sh /usr/local/webserver/mysql/bin/mysqld_safe --defaults-file=/usr/local/webserver/mysql/my.cnf &



  3、编译安装PHP(FastCGI模式)
tar zxvf php-5.2.5.tar.gz
cd php-5.2.5/
./configure --prefix=/usr/local/webserver/php --with-config-file-path=/usr/local/webserver/php/etc --with-mysql=/usr/local/webserver/mysql --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir --enable-xml --disable-debug --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-force-cgi-redirect --enable-mbstring --with-mcrypt
sed -i 's#-lz -lm -lxml2 -lz -lm -lxml2 -lz -lm -lcrypt#& -liconv#' Makefile
make
make install
cp php.ini-dist /usr/local/webserver/php/etc/php.ini
cd ../



  4、编译安装PHP5扩展模块
tar zxvf memcache-2.2.1.tgz
cd memcache-2.2.1/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../

cd php-5.2.5/ext/gd/
/usr/local/webserver/php/bin/phpize
./configure --with-jpeg-dir --with-png-dir --with-zlib-dir --with-ttf --with-freetype-dir --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 = "gd.so"

  自动修改:若嫌手工修改麻烦,可执行以下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 = "gd.so"\n#' /usr/local/webserver/php/etc/php.ini



  6、创建www用户和组,以及其使用的目录:
/usr/sbin/groupadd www -g 48
/usr/sbin/useradd -u 48 -g www www
mkdir -p /data0/vshare/htdocs
chmod +w /data0/vshare/htdocs
chown -R www:www /data0/vshare/htdocs


  7、安装lighttpd中附带的spawn-fcgi,用来启动php-cgi
  注:压缩包中的spawn-fcgi程序为已经编译成二进制的版本。
cp spawn-fcgi /usr/local/webserver/php/bin
chmod +x /usr/local/webserver/php/bin/spawn-fcgi


  8、启动php-cgi进程,监听127.0.0.1的10080端口,进程数为64(如果服务器内存小于3GB,可以只开启25个进程),用户为www:
/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi



  三、安装Nginx 0.5.33
  1、安装Nginx所需的pcre库:
tar zxvf pcre-7.2.tar.gz
cd pcre-7.2/
./configure
make && make install
cd ../


  2、安装Nginx
tar zxvf nginx-0.5.33.tar.gz
cd nginx-0.5.33/
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_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

  输入以下内容:
引用
user  www www;

worker_processes 10;

error_log  /data1/logs/nginx_error.log  crit;

#pid        logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
{
       use epoll;

       worker_connections 51200;
}

http
{
       include       conf/mime.types;
       default_type  application/octet-stream;

       charset  gb2312;
      
       server_names_hash_bucket_size 128;
      
       #sendfile on;
       #tcp_nopush     on;

       keepalive_timeout 60;

       tcp_nodelay on;

       gzip on;
       gzip_min_length  1k;
       gzip_buffers     4 8k;
       gzip_http_version 1.1;
       gzip_types       text/plain application/x-javascript text/css text/html application/xml;

       server
       {
               listen       80;
               server_name  blog.zyan.cc;
               index index.html index.htm index.php;
               root  /data0/vshare/htdocs;

               if (-d $request_filename)
               {
                      rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
               }
                              
               location ~ .*\.php?$
               {
                    include conf/fcgi.conf;      
                    fastcgi_pass  127.0.0.1:10080;
                    fastcgi_index index.php;
               }

               log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                                     '$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  status.blog.zyan.cc;

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


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

  输入以下内容:
引用
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param  REDIRECT_STATUS    200;


  5、启动Nginx
ulimit -SHn 51200
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf



  四、配置开机自动启动Nginx + PHP
vi /etc/rc.local

  在末尾增加以下内容:
引用
ulimit -SHn 51200
/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf



  五、优化Linux内核参数
vi /etc/sysctl.conf

  在末尾增加以下内容:
引用
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000


  使配置立即生效:
/sbin/sysctl -p



  六、在不停止Nginx服务的情况下平滑变更Nginx配置
  (1)、修改/usr/local/webserver/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
/usr/local/webserver/nginx/sbin/nginx -t

  如果屏幕显示以下两行信息,说明配置文件正确:
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf syntax is ok
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf was tested successfully


  (2)、这时,输入以下命令查看Nginx主进程号:
ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

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



  本文若有小的修改,会第一时间在以下网址发布:
  http://blog.zyan.cc/read.php/314.htm

  (全文完)

Tags: , ,



技术大类 » Web服务器 | 评论(238) | 引用(1) | 阅读(240422)
kengi Email
2008-3-9 18:53
请教张老师, 我这里nginx参考您的美文已经基本弄成功了, 只有一个小问题
在/usr/local/nginx/logs/error.log里, 会出现一大堆的
2008/03/09 18:47:00 [alert] 17811#0: sendmsg() failed (9: Bad file descriptor)
...
google一下也发现有人有同样的问题, 说加上worker_rlimit_nofile 就可以了
我的已经设成了 worker_rlimit_nofile 51200,试过调大调小 都会出来
请问你有遇到过这个情况吗?
我的系统也是CentOS 64bit, nginx 是yum得的.
kongsan
2008-3-13 12:35
我现在安装的环境是freebsd 7.0 软件基本上用make install 安装。原来是apache +php4 我现在把apache4 停止,然后安装了nginx,其他配置都类似于您的配置,现在访问web,出现了问题,提示:502 Bad Gateway,这个提示是在访问php网页的时候出现的,而在访问静态网页的时候一切正常。

请教问题出在什么地方?如何解决。
张宴 回复于 2008-3-13 13:08
Nginx无法与FastCGI通信,请检查一下PHP FastCGI进程是否正常。
ngwsx
2008-3-16 16:13
学学
2008-3-18 09:57
[root@host188 bin]# /usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 25 -u www -f /usr/local/webserver/php/bin/php-cgi
sh: /usr/local/webserver/php/bin/php-cgi: 成功
spawn-fcgi.c.211: child exited with: 1, Operation not permitted
出现这样的错误应该怎样解决,谢谢
小虫
2008-3-18 22:16
我拿webbench和apachebench打的结果表明,lamp性能要比楼主的Nginx+fastcgi好,具体的先不贴了。要说明的一点是apache是2.2 prefork模式,请求的是内容为<?phpinfo()?>的phpinfo.php,贴一部分,failed request也是Nginx来得多
Server Software:        nginx/0.5.33
Server Hostname:        172.24.x.x
Server Port:            80

Document Path:          /env2.php
Document Length:        32684 bytes

Concurrency Level:      1020
Time taken for tests:   6.483147 seconds
--------------------
Server Software:        Apache
Server Hostname:        172.24.x.x2
Server Port:            80

Document Path:          /env.php
Document Length:        45722 bytes

Concurrency Level:      1020
Time taken for tests:   4.60018 seconds
dd
2008-3-21 12:00
cd php-5.2.5/ext/gd/
/usr/local/webserver/php/bin/phpize

怎么没有你说的 ./configure的啊
ngwsx Email Homepage
2008-3-21 17:25
ngwsx-0.1.1 —— nginx的Windows移植版
当前版本支持静态文件请求,支持反向代理,下一版本将支持FastCGI。
欢迎大家帮忙测试。

博客:http://blog.csdn.net/ngwsx/
下载:ngwsx-0.1.1.rar http://download.csdn.net/source/390623
ngwsx Email Homepage
2008-3-21 21:09
经过测试,ngwsx-0.1.1已支持FastCGI,有兴趣的朋友可以试试。

配置文件:
master_process    off;
worker_processes  1;

# 工作线程数
worker_threads    128;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  info;

event {
   worker_connections   1024;

   iocp_post_acceptex   64;
   iocp_acceptex_read   on;
   iocp_events          512;
   iocp_timeout         100ms;
}

http {
   include       mime.types;

   default_type  application/octet-stream;

   sendfile            on;
   keepalive_timeout   65;

   server {
       listen       80;
       server_name  localhost;

       root         e:/ngwsx/objs/html;

       location / {
           index  index.html index.htm index.php;
       }

       location /stub_status {
           stub_status   on;
       }

       location /_.gif {
           empty_gif;
       }

       # FastCGI
       #
       location ~ \.php$ {
           fastcgi_pass   127.0.0.1:8090;
           fastcgi_index  index.php;
           fastcgi_param  SCRIPT_FILENAME  e:/ngwsx/objs/html$fastcgi_script_name;
           include        fastcgi_params;
       }

       # 反向代理
       #
       #location ~ \.php$ {
       #    #proxy_pass    http://127.0.0.1:8080;
       #}

       error_page   500 502 503 504  /50x.html;
       location = /50x.html {
           root   html;
       }
   }
}
yls
2008-4-9 10:09
nginx_uploadprogress_module 是第三方模块,可能是版本较旧,与Nginx的最新版本不兼容。
如果你只想让Nginx可以处理1M以上的文件上传,可以更改设置(例如允许30M的文件上传):

client_max_body_size 30m
这个在哪里修改,是nginx_uploadprogress_module里还是nginx.conf里
阿宝
2008-4-9 15:11
我觉得楼主的对比环境还是有失公平

nginx的PHP使用了memcache,而apache+mod_php下却是没有任何辅助的配置,如果你同样在apache+mod_php的方式下配置了memcache,或者同时加入了诸如apc、ea、xcache之类的PHP加速器,那么这样的对比才有意义,不知道楼主有没有在这种公平的环境下对比测试呢?

我最想看这样的对比数据。。。
阿宝
2008-4-9 15:11
我觉得楼主的对比环境还是有失公平

nginx的PHP使用了memcache,而apache+mod_php下却是没有任何辅助的配置,如果你同样在apache+mod_php的方式下配置了memcache,或者同时加入了诸如apc、ea、xcache之类的PHP加速器,那么这样的对比才有意义,不知道楼主有没有在这种公平的环境下对比测试呢?

我最想看这样的对比数据。。。
rickyfang
2008-4-10 13:49
我测试了下,
client_max_body_size 30m
这个在哪里修改,是nginx_uploadprogress_module里还是nginx.conf里

是在NGINX。CONF里改,我用的也是YUM安装的
mengfei
2008-4-21 12:17
无论是centos还是rhel5 都出现错误。
Configuring extensions
checking whether to enable LIBXML support... yes
checking libxml2 install dir... /usr/local/webserver/lib/libxml
checking for xml2-config path... /usr/local/webserver/lib/libxml/bin/xml2-config
checking whether libxml build works... no
configure: error: build test failed.  Please check the config.log for details.
kingway
2008-4-21 13:19
我也碰到php编译无法通过的问题 我重新编译按照了libxml,可是还是不行。
mengfei
2008-4-21 14:57
找到原因了,安装系统时选择开发库时,不要选择libxml2就成、
qdsam
2008-4-22 15:49
你好,张老师。我配置了nginx + php(fastcgi),但是在大访问量的情况下比较频繁的出现php-cgi不干活的情况。一般php-cgi的cpu占用率都在40-50%,出现问题时cup的idle为100%。感觉就是php-cgi不工作了。然后访问网站就会出现超时错误。过上几十秒php-cgi的cpu占用率又上来了,网站也会正常。不知道是什么原因。求教。
cci
2008-4-24 11:45
你好。
http://www.nginx.cn/NginxChsHttpAccessKeyModule
请问我安装时添加了这个模块,安装成功了,但在把示例里的conf代码添加配制文件后


出现这样的错误:
2008/04/24 11:53:22 [emerg] 22789#0: unknown directive "accesskey" in /usr/local/nginx/conf/nginx.conf:49
2008/04/24 11:53:22 [emerg] 22789#0: the configuration file /usr/local/nginx/conf/nginx.conf test failed
zhangbin
2008-4-26 13:22
我按照你的配置成功啦,但是上传附件不能成功
能不能说明下是什么原因
lele
2008-4-29 14:28
我想请问下,如何让l输入http://adc.xxx.com/这样的地址,重定位到
http://www.xxx.com/abc/ 这样子?
lele
2008-4-29 22:43
很好,我已经安装使用,我们公司的web站点上已经在用了,速度飞快,性能OK,只是有些模块还不知道怎么使用,比如日志轮循什么的
分页: 4/12 第一页 上页 1 2 3 4 5 6 7 8 9 10 下页 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]