1. 程式人生 > >完整構建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不間斷執行,即使執行數個月也不需要重新啟動。你還能夠在不間斷服務的情況下進行軟體版本的升級。

接下來,依然是,一步步搭建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. tar xf mysql-5.5.15-linux2.6-i686.tar.gz -C /usr/local 
  6. ln -sv /usr/local/mysql-5.5.15-linux.2.6-i686 /usr/local/mysql 
  7. mkdir /mydata  ## 建立資料儲存目錄 
  8. chown -R mysql:mysql /mydata/ 
  9. cd /usr/local/mysql 
  10. scripts/mysql_install_db –user=mysql –datadir=/mydata/data     
  11. chown -R root . 
  12. ## 加入啟動指令碼 
  13. cp support-files/mysql.server /etc/init.d/mysqld 
  14. chkconfig –add mysqld 
  15. ##修改配置檔案 
  16. cp support-files/my-large.cnf /etc/my.cnf
  17. ## 加入mySQL命令
  18. export PATH=$PATH:/usr/local/mysql/bin
  19. ## 定義標頭檔案
  20. ln -sv /usr/local/mysql/include /usr/include/mysql
  21. 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. ./configure –prefix=/usr/local/php \ 
  5. –with-config-file-path=/usr/local/php/etc \ 
  6. –with-mysql=/usr/local/mysql \ 
  7. –with-mysqli=/usr/local/mysql/bin/mysql_config \ 
  8. –with-iconv-dir=/usr/local \ 
  9. –with-freetype-dir \ 
  10. –with-jpeg-dir \ 
  11. –with-png-dir \ 
  12. –with-zlib \ 
  13. –with-libxml-dir=/usr \ 
  14. –enable-xml \ 
  15. –disable-rpath \ 
  16. –enable-discard-path \ 
  17. –enable-safe-mode \ 
  18. –enable-bcmath \ 
  19. –enable-shmop \ 
  20. –enable-sysvsem \ 
  21. –enable-inline-optimization \ 
  22. –with-curl –with-curlwrappers \ 
  23. –enable-mbregex \ 
  24. –enable-fastcgi \ 
  25. –enable-fpm \ 
  26. –enable-force-cgi-redirect \ 
  27. –enable-mbstring –with-mcrypt \ 
  28. –with-gd –enable-gd-native-ttf \ 
  29. –with-openssl \ 
  30. –with-mhash \ 
  31. –enable-pcntl \ 
  32. –enable-sockets \ 
  33. –with-ldap \ 
  34. –with-ldap-sasl \ 
  35. –with-xmlrpc \ 
  36. –enable-zip \ 
  37. –enable-soap 
  38. make ZEND_EXTRA_LIBS=‘-liconv’ 
  39. make install 
  40. cp php.ini-dist /usr/local/php/etc/php.ini 
  41. 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. ./configure –user=www \
  4. –group=www \
  5. –prefix=/usr/local/nginx \
  6. –with-http_stub_status_module \
  7. –with-http_ssl_module
  8. make && make install 
  9. 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的伺服器,完全能夠輕鬆對付。

感謝各位的閱讀~

如果你覺得這篇博文對你有用,歡迎留言討論~(反賊在這裡感激不盡~哈!)

標籤:linuxLNMPMysqlnginx