Tag Archives: nginx优化

最新版LNMP源码优化配置

2011.09.28 , 企业架构 , No Comments , 104 views

朋友写的最新版的LNMP教程,支持一下

原文出自:http://foreveryan.blog.51cto.com/3508502/674322

 

132201509 最新版LNMP源码优化配置

 LNMP简介


1.什么是LNMP?

    也许大家对LAMP比较熟悉,LAMP代表Linux下Apache、MySQL、PHP这种网站服务器架构;同上LNMP代表的就是Linux下Nginx、MySQL、PHP这种网站服务器架构。

2.我们为什么要采用LNMP这种架构呢?

    使用Linux、PHP外加MySQL的优点我就无需多说相信大家也都很明了。

    Nginx是一个轻量级且高效的Linux下的Web服务器软件,最初是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的反向代理工具,02年的时候他将源代码公开出来,成为了一个开源软件。

    Nginx相当的稳定、功能丰富、安装配置简单、低系统资源……

3.LNMP这种架构有什么优势?

    作为 Web 服务器:相比 Apache,Nginx 使用更少的资源,支持更多的并发连接,而且在访问静态页面的时候有着无与伦比的性能和效率。

    作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP,也可以支持作为 HTTP代理服务器 对外进行服务。Nginx 用 C 编写, 不论是系统资源开销还是 CPU 使用效率都比 Perlbal 要好的多。

    作为邮件代理服务器: Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last.fm 描述了成功并且美妙的使用经验。

    Nginx 配置文件非常简洁(还能够支持perl语法),Bugs少,启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下进行软件版本的升级。

    Nginx的官方网站:http://nginx.org/

接下来,依然是,一步步搭建LNMP的开始!最后,我们将通过手动的检测,去发现自己构建的LNMP到底有多大的能力!

 

阅读示例:

    文中所有需要在终端界面输入的命令,都是用代码框的形式展现

    如:


  1. ulimit -SHn 65535  
  2. /usr/local/php/sbin/php-fpm start 

    文中所有使用文本编辑器打开或者编辑配置文件的内容,都使用“引用框”来展现。配置文件中写入的内容都在引用框中用灰色字体展现。     如:

vim /etc/profile 在里面加入: PATH=$PATH:/usr/local/mysql/bin

 

 


一、准备工作:

(1)我们采用虚拟机的形式来构建整个服务器。     虚拟机:512M内存(你会看到512M内存的情况下Nginx带来的超高并发请求)     系统:Redhat5.4 (Kernel:2.6.18) (2)我们编译安装所需的开发组件包都是通过yum直接安装的。yum源指向的是http://mirrors.163.com,当然如果你使用自己的光盘也是可以的。构建LNMP所需要的编译源码包,大都通过官方网站下载。

 

需要准备的源码包,及其下载地址:(在下载之前最好先建立一个目录方便保存我们的源码包,本文使用/root/lnmp

wget http://www.nginx.org/download/nginx-1.1.3.tar.gz wget http://fastlnmp.googlecode.com/files/php-5.2.14.tar.gz wget http://php-fpm.org/downloads/php-5.2.14-fpm-0.5.14.diff.gz wget http://download.softagency.net/mysql/Downloads/MySQL-5.5/mysql-5.5.15-linux2.6-i686.tar.gz wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz wget http://lcmp.googlecode.com/files/libmcrypt-2.5.8.tar.gz wget http://vps.googlecode.com/files/mcrypt-2.6.8.tar.gz wget http://lnmp-v4.googlecode.com/files/memcache-2.2.5.tgz wget http://acelnmp.googlecode.com/files/mhash-0.9.9.9.tar.gz wget http://acelnmp.googlecode.com/files/pcre-8.10.tar.gz wget http://acelnmp.googlecode.com/files/eaccelerator-0.9.6.1.tar.bz2 wget http://vps.googlecode.com/files/PDO_MYSQL-1.0.2.tgz wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz wget http://lnmpp.googlecode.com/files/imagick-2.3.0.tgz

 

 


二,完整编译安装的开始!

(1)编译安装PHP 5.2.14所需的支持库:


  1. tar zxvf libiconv-1.13.1.tar.gz 
  2. cd libiconv-1.13.1/ 
  3. ./configure --prefix=/usr/local 
  4. make 
  5. make install 
  6. cd ../ 

  1. tar zxvf libmcrypt-2.5.8.tar.gz  
  2. cd libmcrypt-2.5.8/ 
  3. ./configure 
  4. make 
  5. make install 
  6. /sbin/ldconfig 
  7. cd libltdl/ 
  8. ./configure --enable-ltdl-install 
  9. make 
  10. make install 
  11. cd ../../ 

  1. tar zxvf mhash-0.9.9.9.tar.gz 
  2. cd mhash-0.9.9.9/ 
  3. ./configure 
  4. make 
  5. make install 
  6. cd ../ 

  1. ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la 
  2. ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so 
  3. ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4 
  4. ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8 
  5. ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a 
  6. ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la 
  7. ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so 
  8. ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2 
  9. ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1 
  10. ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config 

  1. tar zxvf mcrypt-2.6.8.tar.gz 
  2. cd mcrypt-2.6.8/ 
  3. /sbin/ldconfig 
  4. ./configure 
  5. make 
  6. make install 
  7. cd ../ 

(2)绿色二进制包安装MySQL 5.5.15

①:安装过程


  1. ## 为MySQL建立用户和组 
  2. groupadd -g 3306 mysql 
  3. useradd -g mysql -u 3306 -s /sbin/nologin -M mysql 
  4.  
  5. ## 二进制安装方式 
  6. tar xf mysql-5.5.15-linux2.6-i686.tar.gz -C /usr/local 
  7. ln -sv /usr/local/mysql-5.5.15-linux.2.6-i686 /usr/local/mysql 
  8.  
  9. mkdir /mydata  ## 创建数据保存目录 
  10. chown -R mysql:mysql /mydata/ 
  11. cd /usr/local/mysql 
  12. scripts/mysql_install_db --user=mysql --datadir=/mydata/data     
  13. chown -R root . 
  14.  
  15. ## 加入启动脚本 
  16. cp support-files/mysql.server /etc/init.d/mysqld 
  17. chkconfig --add mysqld 
  18.  
  19. ##修改配置文件 
  20. cp support-files/my-large.cnf /etc/my.cnf
  21.  
  22. ## 加入mySQL命令
  23. export PATH=$PATH:/usr/local/mysql/bin
  24.  
  25. ## 定义头文件
  26. ln -sv /usr/local/mysql/include /usr/include/mysql
  27. ldconfig 

②:配置过程

 

vim /etc/my.cnf [mysqld]段内加入并修改以下两处 datadir = /mydata/data thread_concurrency 2    ## (并发线程数,一般是cpu核心的两倍)

 

 

vim /etc/profile 在里面加入: PATH=$PATH:/usr/local/mysql/bin

 

 

vim /etc/ld.so.conf.d/mysql.conf 写入 /usr/local/mysql/lib

 

③:启用过程


  1. service mysqld start 
  2. cd /root/lnmp

 

输入以下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';

 

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


  1. tar zxvf php-5.2.14.tar.gz 
  2. gzip -cd php-5.2.14-fpm-0.5.14.diff.gz | patch -d php-5.2.14 -p1 
  3. cd php-5.2.14
  4.  
  5. ./configure --prefix=/usr/local/php \ 
  6. --with-config-file-path=/usr/local/php/etc \ 
  7. --with-mysql=/usr/local/mysql \ 
  8. --with-mysqli=/usr/local/mysql/bin/mysql_config \ 
  9. --with-iconv-dir=/usr/local \ 
  10. --with-freetype-dir \ 
  11. --with-jpeg-dir \ 
  12. --with-png-dir \ 
  13. --with-zlib \ 
  14. --with-libxml-dir=/usr \ 
  15. --enable-xml \ 
  16. --disable-rpath \ 
  17. --enable-discard-path \ 
  18. --enable-safe-mode \ 
  19. --enable-bcmath \ 
  20. --enable-shmop \ 
  21. --enable-sysvsem \ 
  22. --enable-inline-optimization \ 
  23. --with-curl --with-curlwrappers \ 
  24. --enable-mbregex \ 
  25. --enable-fastcgi \ 
  26. --enable-fpm \ 
  27. --enable-force-cgi-redirect \ 
  28. --enable-mbstring --with-mcrypt \ 
  29. --with-gd --enable-gd-native-ttf \ 
  30. --with-openssl \ 
  31. --with-mhash \ 
  32. --enable-pcntl \ 
  33. --enable-sockets \ 
  34. --with-ldap \ 
  35. --with-ldap-sasl \ 
  36. --with-xmlrpc \ 
  37. --enable-zip \ 
  38. --enable-soap 
  39.  
  40. make ZEND_EXTRA_LIBS='-liconv' 
  41. make install 
  42. cp php.ini-dist /usr/local/php/etc/php.ini 
  43. cd ../ 

(4)编译安装PHP5扩展模块


  1. tar zxvf memcache-2.2.5.tgz 
  2. cd memcache-2.2.5
  3. /usr/local/php/bin/phpize 
  4. ./configure --with-php-config=/usr/local/php/bin/php-config 
  5. make 
  6. make install 
  7. cd ../ 

  1. tar jxvf eaccelerator-0.9.6.1.tar.bz2 
  2. cd eaccelerator-0.9.6.1
  3. /usr/local/php/bin/phpize 
  4. ./configure --enable-eaccelerator=shared \
  5. --with-php-config=/usr/local/php/bin/php-config 
  6. make 
  7. make install 
  8. cd ../ 

  1. tar zxvf PDO_MYSQL-1.0.2.tgz 
  2. cd PDO_MYSQL-1.0.2
  3. /usr/local/php/bin/phpize 
  4. ./configure --with-php-config=/usr/local/php/bin/php-config \
  5. --with-pdo-mysql=/usr/local/mysql 
  6. make 
  7. make install 
  8. cd ../ 

  1. tar zxvf ImageMagick.tar.gz 
  2. cd ImageMagick-6.5.1-2
  3. ./configure 
  4. make 
  5. make install 
  6. cd ../ 

  1. tar zxvf imagick-2.3.0.tgz 
  2. cd imagick-2.3.0/ 
  3. /usr/local/php/bin/phpize 
  4. ./configure --with-php-config=/usr/local/php/bin/php-config 
  5. make 
  6. make install 
  7. cd ../ 

(5)修改php.ini文件

 

手工修改: 查找/usr/local/php/etc/php.ini中的extension_dir = "./" 修改为 extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"

增加以下几行 extension = "memcache.so" extension = "pdo_mysql.so" extension = "imagick.so"

再查找output_buffering = Off 修改为 On

再查找 ;cgi.fix_pathinfo=0 去掉“;”号,防止Nginx文件类型错误解析漏洞。

 

(6)配置eAccelerator加速PHP:


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

跳到配置文件的最末尾,加上以下配置信息:

 

[eaccelerator] zend_extension="/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so" eaccelerator.shm_size="64" eaccelerator.cache_dir="/usr/local/eaccelerator_cache" eaccelerator.enable="1" eaccelerator.optimizer="1" eaccelerator.check_mtime="1" eaccelerator.debug="0" eaccelerator.filter="" eaccelerator.shm_max="0" eaccelerator.shm_ttl="3600" eaccelerator.shm_prune_period="3600" eaccelerator.shm_only="0" eaccelerator.compress="1" eaccelerator.compress_level="9"

(7)创建www用户和组,以及虚拟主机使用的目录:

 


  1. /usr/sbin/groupadd www 
  2. /usr/sbin/useradd -g www www 
  3. mkdir -p /web 
  4. chmod +w /web 
  5. chown -R www:www /web 

(8)创建php-fpm配置文件(php-fpm是为PHP打的一个FastCGI管理补丁,可以平滑变更php.ini配置而无需重启php-cgi): 在/usr/local/php/etc/目录中创建php-fpm.conf文件:


  1. rm -f /usr/local/php/etc/php-fpm.conf 
  2. vim /usr/local/php/etc/php-fpm.conf 

 

输入以下内容

<?xml version="1.0" ?> <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/php/logs/php-fpm.pid</value>     Error log file     <value name="error_log">/usr/local/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:


  1. ulimit -SHn 65535 
  2. /usr/local/php/sbin/php-fpm start 

  注意:如果要重启,可以使用 reload 命令

 


三、安装Nginx 1.1.3

(1)安装Nginx所需的pcre库:


  1. tar zxvf pcre-8.10.tar.gz 
  2. cd pcre-8.10
  3. ./configure 
  4. make && make install 
  5. cd ../ 

(2)安装Nginx


  1. tar zxvf nginx-1.1.3.tar.gz 
  2. cd nginx-1.1.3/
  3.  
  4. ./configure --user=www \
  5. --group=www \
  6. --prefix=/usr/local/nginx \
  7. --with-http_stub_status_module \
  8. --with-http_ssl_module
  9.  
  10. make && make install 
  11. cd ../ 

(3)创建Nginx日志目录


  1. mkdir -p /web/logs 
  2. chmod +w /web/logs 
  3. chown -R www:www /web/logs 

(4)创建Nginx配置文件

在/usr/local/nginx/conf/目录中创建nginx.conf文件:


  1. rm -f /usr/local/nginx/conf/nginx.conf 
  2. vi /usr/local/nginx/conf/nginx.conf 

输入以下内容:

 

user  www www;

worker_processes 8;  ## 根据自己的CPU来决定到底应该是多少 error_log  /web/logs/nginx_error.log  crit; pid        /usr/local/nginx/nginx.pid;

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

events  {   use epoll;   worker_connections 65535; } 

http  {   include       mime.types;   default_type  application/octet-stream;   #charset  gb2312;     server_names_hash_bucket_size 128;   client_header_buffer_size 32k;   large_client_header_buffers 4 32k;

  client_max_body_size 8m;         sendfile on;   tcp_nopush     on;

  keepalive_timeout 60;   tcp_nodelay on; 

  fastcgi_connect_timeout 300;   fastcgi_send_timeout 300;   fastcgi_read_timeout 300;   fastcgi_buffer_size 64k;   fastcgi_buffers 4 64k;   fastcgi_busy_buffers_size 128k;   fastcgi_temp_file_write_size 128k; 

  gzip on;   gzip_min_length  1k;   gzip_buffers     4 16k;   gzip_http_version 1.0;   gzip_comp_level 2;   gzip_types       text/plain application/x-javascript text/css application/xml;   gzip_vary on; 

  #limit_zone  crawler  $binary_remote_addr  10m; 

  server   {     listen       80;     server_name  192.168.0.156;  ## 这里简单测试,所以直接使用IP     index index.html index.htm index.php;     root  /web;

    #limit_conn   crawler  20;                                 

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

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$     {       expires      30d;     } 

    location ~ .*\.(js|css)?$     {       expires      1h;     }

    location /status {     stub_status on;   ## 开启状态统计,为后面的优化做测试     }    

    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  /web/logs/access.log  access;    } }

 

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


  1. vi /usr/local/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


  1. ulimit -SHn 65535 
  2. /usr/local/nginx/sbin/nginx 

(6)配置开机自动启动Nginx + PHP


  1. vim /etc/rc.local 

在末尾增加以下内容:

 

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

 

 


四、简单优化,实现高并发!

(1)Nginx的优化

一般来说nginx 配置文件中对优化比较有作用的为以下几项:

 

worker_processes 8; nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数。

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000; 为每个进程分配cpu,上例中将8 个进程分配到8 个cpu,当然可以写多个,或者将一个进程分配到多个cpu。

worker_rlimit_nofile 102400; 这个指令是指当一个nginx 进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx 进程数相除,但是nginx 分配请求并不是那么均匀,所以最好与ulimit-n 的值保持一致。

use epoll; 使用epoll 的I/O 模型,这个不用说了吧。

worker_connections 102400; 每个进程允许的最多连接数, 理论上每台nginx 服务器的最大连接数为worker_processes*worker_connections。

keepalive_timeout 60; keepalive 超时时间。

client_header_buffer_size 4k; 客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE 取得。

open_file_cache max=102400 inactive=20s; 这个将为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。

open_file_cache_valid 30s; 这个是指多长时间检查一次缓存的有效信息。

open_file_cache_min_uses 1; open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。

 

 

(2)关于内核参数的优化:请修改文件/etc/sysctl.conf

 

net.ipv4.tcp_max_tw_buckets = 6000 timewait 的数量,默认是180000。

net.ipv4.ip_local_port_range = 1024 65000 允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1 启用timewait 快速回收。

net.ipv4.tcp_tw_reuse = 1 开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接。

net.ipv4.tcp_syncookies = 1 开启SYN Cookies,当出现SYN 等待队列溢出时,启用cookies 来处理。

net.core.somaxconn = 262144 web 应用中listen 函数的backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx 定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。

net.core.netdev_max_backlog = 262144 每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans = 262144 系统中最多有多少个TCP 套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS 攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。

net.ipv4.tcp_max_syn_backlog = 262144 记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M 内存的系统而言,缺省值是1024,小内存的系统则是128。

net.ipv4.tcp_timestamps = 0 时间戳可以避免序列号的卷绕。一个1Gbps 的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。

net.ipv4.tcp_synack_retries = 1 为了打开对端的连接,内核需要发送一个SYN 并附带一个回应前面一个SYN 的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK 包的数量。

net.ipv4.tcp_syn_retries = 1 在内核放弃建立连接之前发送SYN 包的数量。

net.ipv4.tcp_fin_timeout = 1 如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2 状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60 秒。2.2 内核的通常值是180 秒,你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB 服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2 的危险性比FIN-WAIT-1 要小,因为它最多只能吃掉1.5K 内存,但是它们的生存期长些。

net.ipv4.tcp_keepalive_time = 30 当keepalive 起用的时候,TCP 发送keepalive 消息的频度。缺省是2 小时。

 

(3)关于FastCGI 的几个指令:

 

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m; 这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300; 指定连接到后端FastCGI 的超时时间。

fastcgi_send_timeout 300; 向FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI 传送请求的超时时间。

fastcgi_read_timeout 300; 接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI 应答的超时时间。

fastcgi_buffer_size 4k; 指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k。

fastcgi_buffers 8 4k; 指定本地需要用多少和多大的缓冲区来缓冲FastCGI 的应答。

fastcgi_busy_buffers_size 8k; 这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers 的两倍。

fastcgi_temp_file_write_size 8k; 在写入fastcgi_temp_path 时将用多大的数据块,默认值是fastcgi_buffers 的两倍。

fastcgi_cache TEST 开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU 负载,并且防止502 错误。

fastcgi_cache_valid 200 302 1h; fastcgi_cache_valid 301     1d; fastcgi_cache_valid any     1m; 为指定的应答代码指定缓存时间,如上例中将200,302 应答缓存一小时,301 应答缓存1 天,其他为1 分钟。

fastcgi_cache_min_uses 1; 缓存在fastcgi_cache_path 指令inactive 参数值时间内的最少使用次数,如上例,如果在5 分钟内某文件1 次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500; 不知道这个参数的作用,猜想应该是让nginx 知道哪些类型的缓存是没用的。

 

(4)使用php-fpm 来管理FastCGI,可以修改配置文件中的以下值:

 

<value name="max_children">60</value> 同时处理的并发请求数,即它将开启最多60 个子线程来处理并发连接。

<value name="rlimit_files">102400</value> 最多打开文件数。

<value name="max_requests">204800</value> 每个进程在重置之前能够执行的最多请求数。

 

(5)下面贴几张测试结果图。

测试是使用apache自带的ab命令进行压力测试:

 


  1. ab -c 20000 -n 10000 http://192.168.0.156/index.php 

动态nginx缓存优化加速搭建教程[原创]

2011.03.22 , unix, 企业架构 , 2 Comments , 2,403 views

 

此文凝聚笔者不少心血请尊重笔者劳动,转载请注明出处,侵权必究http://www.unixwind.com/ 

Nginx+php(FastCGI)+Memcached+Mysql+APC高性能web服务器安装

Nginx介绍:
Nginx 超越 Apache 的高性能和稳定性,使得国内使用 Nginx 作为 Web 服务器的网站也越来越多,其中包括国内最大的电子地图MapBar、新浪博客、新浪播客、网易新闻等门户网站频道,六间房、56.com等视频分享网站,Discuz!官方论坛、水木社区等知名论坛,豆瓣、YUPOO相册、海内SNS、迅雷在线等新兴Web 2.0网站,更多的网站都在使用Nginx配置。
Nginx(发音同 engine x)是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler(俄文:Рамблер)使用。  其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页伺服器中表现较好.目前中国大陆使用nginx网站用户有:新浪、网易、 腾讯,另外知名的微网志Plurk也使用nginx。
为什么Nginx的性能要比Apache高得多?
这得益于Nginx使用了最新的epoll(Linux 2.6内核)和kqueue(freebsd)网络I/O模型,而Apache则使用的是传统的select模型。目前Linux下能够承受高并发访问的Squid、Memcached都采用的是epoll网络I/O模型。 处理大量的连接的读写,Apache所采用的select网络I/O模型非常低效。
Nginx 是一个很牛的高性能Web和反向代理服务器, 它具有有很多非常优越的特性:
作为 Web 服务器:相比 Apache,Nginx 使用更少的资源,支持更多的并发连接,体现更高的效率,这点使 Nginx 尤其受到虚拟主机提供商的欢迎。在高连接并发的情况下,Nginx是Apache服务器不错的替代品: Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一. 能够支持高达 50,000 个并发连接数的响应, 感谢Nginx为我们选择了 epoll and kqueue 作为开发模型.
Nginx作为负载均衡服务器: Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务, 也可以支持作为 HTTP代理 服务器对外进行服务. Nginx采用C进行编写, 不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多. 。Nginx可作为7层负载均衡服务器来使用。
作为邮件代理服务器: Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器), Last.fm 描述了成功并且美妙的使用经验.
Nginx 是一个安装非常的简单 , 配置文件非常简洁(还能够支持perl语法), Bugs 非常少的服务器: Nginx 启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动. 你还能够不间断服务的情况下进行软件版本的升级 .
总体来说nginx的有以下八大优点:
1.高并发连接:官方测试能支撑5万并发连接,在实际生产环境中跑到2,~3W并发连接。
2.内存消耗少:在3W并发连接下,开启的10个NGINX进程才消耗150M内存(15M*10=150M)
3.配置文件非常简单:风格跟程序一样通俗易懂。
4.成本低廉:Nginx作为开源软件,可以免费使用,而购买F5 BIG-IP、NetScaler
等硬件负载均衡交换机则需要十多万至几十万人民币。
5.支持rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分发到不同的后端服务器群组。
6.内置的健康检查功能:如果Nginx Proxy后端的后台web服务器宕机了,不会音响前端访问。
7.节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头。
8.稳定性高:用于反向代理,宕机的概率微乎其微。
介绍这么多nginx 的优点.下面来具体实现下LEMP架构(linux+nginx+mysql+php/perl/python)
可能有朋友对静态动态解析过程不太清楚,笔者按照自己理解简单阐述,如有错误地方请前辈多加指点。
nginx只是提供一个静态web服务,动态web服务还需要与PHP等脚本语言结合使用。

Nginx+php(FastCGI)+Memcached+Mysql+APC 是目前主流的高性能服务器搭建方式!适合大中型网站,小型站长也可以采用这种组合!

前面 nginx php mysql大家已经很熟悉了,这里简单介绍下 memcached 和 APC 。
 
一:memcached
 
在很多场合,我们都会听到 memcached 这个名字,但很多同学只是听过,并没有用过或实际了解过,只知道它是一个很不错的东东。这里简单介绍一下,memcached 是高效、快速的分布式内存对象缓存系统,主要用于加速 WEB 动态应用程序。由于nginx对静态网站加速效果明显,而动态一直效果不太好,有了memcached,生活将变得简单。
 
二:APC
Alternative PHP Cache(APC)是 PHP 的一个免费公开的优化代码缓存。它用来提供免费,公开并且强健的架构来 缓存和优化 PHP 的中间代码。 


安装配置:
准备工作,需要上面提到的软件另外还有两个包mysql-5.1.41.tar.gz、php-5.3.5.tar.gz (其他相似版本也可以)可以在官网下载。
一、编译安装Nginx (安装nginx之前需要安装pcre包和zlib以支持重写,正则以及网页压缩等等

(1)首先配置安装pcre:
cd  /usr/src  &&tar xzf pcre-8.01.tar.gz   &&cd pcre-8.01  &&  ./configure   --prefix=/usr/local/pcre  &&make &&make install

(2)、然后再编译安装nginx :
useradd www  && cd  /usr/src && tar xzf  nginx-0.7.61.tar.gz   &&cd  nginx-0.7.61  &&  ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-openssl=/usr/ --with-pcre=/usr/src/pcre-8.01  --user=www --group=www  &&make  &&make install
【nginx注意*  --with-pcre=/usr/src/pcre-8.01指向的是源码包解压的路径,而不是安装的路径,否则会报
make[1]: *** [/usr/local/pcre/Makefile] Error 127 错误】
 
二、接下来安装mysql
(1)、cd   /usr/src && tar xzf  mysql-5.1.41.tar.gz   && cd mysql-5.1.41  && ./configure --prefix=/usr/local/mysql/ --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile --with-plugins=innobase  && make  &&make install

(2)、mysql安装完毕,创建mysql用户和组并初始化数据库,并启动数据库。

cd  /usr/local/mysql && useradd mysql && chown -R  mysql:mysql   /usr/local/mysql  &&  /usr/local/mysql/bin/mysql_install_db  --user=mysql   &&   chown -R   mysql:mysql  var/  && ./bin/mysqld_safe   --user=mysql &   

【如果mysql启动报错,请检查 /usr/local/mysql/var 目录,mysql是否有权限】
三、安装 php :
cd   /usr/src    &&tar xzf  php-5.3.5.tar.gz   && cd php-5.3.5  && ./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-mysql=/usr/local/mysql --with-mysqli=/u
sr/local/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-li
bxml-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-fpm  --enable-sockets  && make  &&make install  
安装完毕!【注意这个参数在此可以不加--enable-fastcgi;其他之前版本需要加上,以上安装根据自己的选择添加,如果报错,根据具体报错找原因】


四、整合Nginx和php(FastCGI)安装完php-5.3.5后支持fastCGI

(1)、配置nginx ,拷贝nginx配置文件:
user  www www;
worker_processes 8;
error_log  /usr/local/nginx/logs/error.log  crit;
pid        /usr/local/nginx/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      mime.types;
default_type  application/octet-stream;
charset    utf-8;
error_page  400 404 403 500 502 503 http://blog.mgcrazy.com;   
server_names_hash_bucket_size 128;
client_header_buffer_size 2k;
large_client_header_buffers 4 4k;
client_max_body_size 8m;
sendfile on;
tcp_nopush        on;
keepalive_timeout 60;
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
keys_zone=TEST:10m
inactive=5m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
fastcgi_busy_buffers_size 8k;
fastcgi_temp_file_write_size 8k;
##如下设置fastcGI_cache缓存,加速你的web站点!
fastcgi_cache TEST;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri; 
open_file_cache max=204800 inactive=20s;
open_file_cache_min_uses 1;
open_file_cache_valid 30s;
tcp_nodelay on;

gzip on;
gzip_min_length       1k;
gzip_buffers        4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types         text/plain application/x-javascript text/css application/xml;
gzip_vary on;

##设置301跳转,让二级域名跳转到你规定的url;
  server
  {
    listen       80;
    server_name blog.mgcrazy.com wgkgood.gicp.net linux.mgcrazy.com;
           if ($host = 'wgkgood.gicp.net' ) {
    rewrite ^/(.*)$ http://blog.mgcrazy.com/$1 permanent;   
}
    if ($host = 'linux.mgcrazy.com' ) {
    rewrite ^/(.*)$ http://blog.mgcrazy.com/$1 permanent;
}

    index index.php index.htm index.html;
    root  /home/webapps/www;
    #limit_conn   crawler  20;
    location ~ .*\.(php|php5)?$
    {
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      30d;
    }
    location ~ .*\.(js|css)?$
    {
      expires      1h;
    }
    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  /usr/local/nginx/logs/access.log  access;
      }
}

Nginx配置完毕!启动nginx ;/usr/local/nginx/sbin/nginx 即可,重启nginx命令如下/usr/local/nginx/sbin/nginx –s  reload


(2)、配置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;

五、配置php配置文件:

cd /usr/local/php5/etc/ && cp   php-fpm.conf.default   php-fpm.conf

然后根据提示编辑php-fpm.conf里面的选项。

开启php-fpm
cp /usr/src/php-5.3.5/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm 然后启动 /etc/init.d/php-fpm start 即可。

六、安装apc配置:

cd /usr/src && tar xzf APC-3.1.4.tgz &&cd APC-3.1.4
/usr/local/php5/bin/phpize && ./configure --enable-apc --enable-apc-mmap --with-php-config=/usr/local/php5/bin/php-config &&make&& make install

安装完后会生成一个apc.so在/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/里面。

七、安装memcached,使fastcGI支持memcached
首先安装libevent,

cd /usr/src && tar xzf libevent-1.4.12-stable.tar.gz && cd libevent-1.4.12-stable && ./configure –prefix=/usr/local/libevent &&make && make install
然后安装memcached  //缓存加速
tar xzf memcache-2.2.5.tar.gz && cd memcache-2.2.5 && /usr/local/php5/bin/phpize && ./configure –prefix=/usr/local/memcached --with-libevent=/usr/local/libevent --with-php-config=/usr/local/php5/bin/php-config &&make &&make install
安装完后,会在/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/里生成一个memcache.so 这个模块:


八、编辑php.ini

默认的php.ini在/usr/local/php5/lib/php.ini 
extension_dir = "./"   //修改路径
修改为
extension_dir="/usr/local/php5/lib/php/extensions/no-debug-non-zts-20090626"
把下面这些添加到最后:
extension = apc.so
extension=memcache.so //这里引用缓存模块
[APC]
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 64M
apc.optimization = 1
apc.num_files_hint = 0
apc.ttl=7200
apc.user_ttl=7200
apc.gc_ttl = 3600
apc.cache_by_default = on

安装到此已经完成!
重新启动nginx和php-fpm ,用测试页面即可访问。
此文凝聚笔者不少心血请尊重笔者劳动,转载请注明出处,侵权必究http://www.unixwind.com/