完整構建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 10000 -n 20000 http://192.168.0.156/index.php 

沒有優化前:不管如何,就是上不了1W5……

優化之後:輕輕鬆鬆突破2W

你可曾想過這是512M內存的實力?
也希望各位能在實現之後使用Webbench測試工具進行併發峯值5W+的測試,我相信,512M的服務器,完全能夠輕鬆對付。

感謝各位的閱讀~
如果你覺得這篇博文對你有用,歡迎留言討論~(反賊在這裏感激不盡~哈!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章