nginx+fastcgi搭建高負載伺服器

餘二五發表於2017-11-16

 

一 安裝nginx fastcgi 簡介

   1 nginx是一個個高效能的 HTTP 和反向代理伺服器,並且nginx 佔用的系統資源更少
   2 xcache 是一個開源的opcode 快取器/優化器,能提高伺服器上的php 效能,xcache 通過把編譯PHP後的資料緩衝到共享記憶體從而避免重複編譯過程,能夠直接使用
    緩衝區已編譯的程式碼從而提高速度,降低伺服器的負載.
   3  gperftools 是google 開發的一款優秀的LinuxC/C++ 程式的效能剖析及優化工具,他提供了將目標程式執行時所消耗的CPU 時間片進行剖析和圖形輸出剖析結果的功能。 
     gperftools 包含四個工具,
     分別是:TCMalloc,heap-checker,heap-profiler和cpu-profiler,TCMalloc是gperftools其中一個工具,由於優化C++寫的多執行緒應用,與標準的glibc庫的malloc 相比,
     TCMalloc 自啊記憶體的分配效率和速度要高, 可以在高併發的情況下很好的控制記憶體的使用,提供伺服器的效能,降低負載.
   4 所需軟體
      libunwind-1.0.1.tar.gz
      gperftools-2.0.tar.gz
      pcre-8.31.tar.gz
      nginx-1.2.5.tar.gz
      #nginx 第三方模組,開啟nginx etag,預設情況下nginx 是沒有該模組的
      nginx-static-etags-master.zip        
      php-5.3.19.tar.gz
      xcache-3.0.0.tar.gz
      mysql-5.0.91.tar.gz



二 libunwind 安裝配置

     #tar -zxvf libunwind-1.0.1.tar.gz
     #cd libunwind-1.0.1/
     #CFLAGS=-fPIC ./configure
     #make CFLAGS=-fPIC
     #make CFLAGS=-fPIC install
     注:libunwind 庫為基於64位CPU和作業系統的程式提供了基本的堆疊輾轉開解功能,其中包括用於輸出堆疊跟蹤的API、
        用於以程式設計方式輾轉開解堆疊的API以及支援C++異常處理機制的API



三 gperftools安裝配置

  1 #tar xf   gperftools-2.0.tar.gz
    #cd   gperftools-2.0
    #./configure --enable-frame-pointers
    #make && make install
    注:如果是32位系統,可以不新增 –enable-frame-pointers,如果是64位系統,並且之前沒有安裝libunwind,
    那麼一定要新增 –enable-frame-pointers 引數



四 pcre 安裝

   #tar  xf  pcre-8.31.tar.gz
   #cd   pcre-8.31
   #./configure && make && make install



五 nginx 安裝配置

  1 #tar  xf nginx-1.2.5.tar.gz
   #cd nginx-1.2.5
   # useradd -s /sbin/noloin  nginx
   #./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module
    --with-http_ssl_module --with-google_perftools_module --with-pcre --without-mail_pop3_module 
    --without-mail_imap_module  --without-mail_smtp_module --with-http_gzip_static_module 
    --add-module=../nginx-static-etags-master
   #make && make install 
  2 nginx  配置優化
    #vim  nginx.conf
     
   user  nginx nginx ;
   worker_processes  12;
   error_log  logs/error.log  notice;
   pid        logs/nginx.pid;
   #使用google_perftools優化nginx 記憶體使用
   google_perftools_profiles /tmp/tcmalloc;
   worker_cpu_affinity  000000000001 000000000010 0000000000100 000000001000 000000010000 000000100000 000001000000 000010000000  000100000000 001000000000 010000000000 100000000000;
   worker_rlimit_nofile 819200;
   events {
      use  epoll;
      worker_connections  8000;
   }
 http {
   include       mime.types;
   default_type  application/octet-stream;
   #定義nginx 日誌格式
   log_format  main  `$remote_addr $host $remote_user [$time_local] "$request" `
                     `$status $body_bytes_sent "$http_referer" `
                     `"$http_user_agent" "$http_x_forwarded_for"`;
   access_log  logs/access.log  main; 
  #charst
  charset UTF-8;
  server_names_hash_bucket_size 128;
  client_header_buffer_size 2k;
  large_client_header_buffers 4 128k;
  client_max_body_size 8m;
   sendfile        on;
   tcp_nopush     on;
   server_tokens off;
   #keepalive_timeout  0;
   keepalive_timeout  120;   
   #gzip  on;
   gzip  on;
   gzip_proxied  any;
   gzip_min_length   1k;
   gzip_buffers   4 16k;
   gzip_http_version 1.1;
   gzip_comp_level 3;
   gzip_types text/plain  text/css text/xml  text/javascript  application/x-javascript  charset=utf-8 application/x-java-archive application/xml image/gif image/png image/jpeg image/tiff image/x-ms-bmp application/x-shockwave-flash ;
   gzip_vary on;
  #fastcgi  set
   #設定連線後端fastcgi 超時時間
   fastcgi_connect_timeout 180;
   #設定FastCGI傳送請求的超時時間
   fastcgi_send_timeout 300;
   #設定 接收FastCGI應答的超時時間
   fastcgi_read_timeout 300;
   #設定於指定讀取FastCGI應答第一部分需要多大的緩衝區,這個值表示將使用1個64KB的緩衝區讀取應答的第一部分(應答頭)
   #   ,可以設定為fastcgi_buffers選項指定的緩衝區大小。
   fastcgi_buffer_size 128k;
   #指定本地需要用多少和多大的緩衝區來緩衝FastCGI的應答請求。如果一個PHP指令碼所產生的頁面大小為256KB,
    #那麼會為其分配4個64KB的緩衝區來快取;如果頁面大小大於256KB,那麼大於256KB的部分會快取到fastcgi_temp
    指定的路徑中,但是這並不是好方法,因為記憶體中的資料處理速度要快於硬碟。
    一般這個值應該為站點中PHP指令碼所產生的頁面大小的中間值,如果站點大部分指令碼所產生的頁面大小為256KB,
    那麼可以把這個值設定為“16 16k”、“4 64k”等。
   fastcgi_buffers 4  256k;
   fastcgi_busy_buffers_size 256k;
   #表示在寫入快取檔案時使用多大的資料塊,預設值是fastcgi_buffers的兩倍
   fastcgi_temp_file_write_size 256k;
   fastcgi_intercept_errors on;
   fastcgi_ignore_client_abort on ;    
   server {
       listen       80;
       server_name  ad.frank.com.cn;
       #設定只允許訪問域名,非域名返回403錯誤
       if ($host !~ `ad.frank.com.cn`) {
               return 403;
             }
       index index.php index.html  index.htm ;
       root /usr/local/nginx/html;
       #charset koi8-r;
        charset UTF-8;
       #設定允許訪問openx 管理後臺的IP 地址
        location ^~ /www/admin/ {
            allow  192.168.1.0/24;
            allow  127.0.0.1;
            deny all;       
        location ~ .*.(php|php5)?$ {
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
             }
        }
     #設定檢視Xcache 狀態及允許訪問的IP 地址
     #set Xcache status 
       location ^~ /xcache/ {
             allow  192.168.1.0/24;
             deny all;
         
          location ~ .*.(php|php5)?$ {
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
              }
         } 
     #設定php-fpm 的狀態頁面及允許訪問的IP 
     #set php-fpm status 
      location ^~ /(status)$ {
         
          allow 192.168.1.0/24;
          deny all;
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
        }
       #access_log  logs/host.access.log  main;
       location / {
           root   /usr/local/nginx/html;
           index index.php  index.html index.htm;
       }
       #error_page  404              /404.html;
       #定義nginx 40X 錯誤頁面
        error_page  400 = http://img.frank.com.cn/error.html;
        error_page  403 = http://img.frank.com.cn/error.html;
        error_page  404 = http://img.frank.com.cn/error.html;
      #定義 nginx 50X 錯誤頁面
      # redirect server error pages to the static page /50x.html
        error_page  500 = http://img.frank.com.cn/error.html;
        error_page  501 = http://img.frank.com.cn/error.html;
        error_page  502 = http://img.frank.com.cn/error.html;
        error_page  503 = http://img.frank.com.cn/error.html;
       #設定吧php 代理到 php-fpm
       # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
       location ~ .*.(php|php5)?$ {
           root    html;
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;   
           include  fastcgi_params;
       }
      #設定在瀏覽器中快取的檔案型別及時間
     location ~.*.(jpg|js|css|png|bmp|jpeg|gif|swf)$ 
             {
        #設定防盜鏈,非允許的域名,返回404錯誤
             valid_referers none blocked *.frank.com.cn;
               if ($invalid_referer) {
                  return 404;
                 }
             root  html;
             expires 360d;
             #開啟nginx etag 標籤
             FileETag on;
             etag_format "%X%X";
           }
       #設定產看nginx 執行狀態及允許訪問的IP 地址
       #Nginx status
       location ~^/NginxStatus {
           allow 192.168.1.0/24;
           deny all;
           stub_status on;
           access_log off;
           if ( -d $request_filename){
            rewrite ^/(.*)([^/])$ http://$host/$1$2 permanent;
             }
            }
     }
  }
  3 配置nginx service啟動指令碼,並新增開啟自動啟動
     #vim  /etc/init.d/nginx
      #!/bin/sh
      #
      # nginx - this script starts and stops the nginx daemin
      #
      # chkconfig:   - 85 15
      # description:  Nginx is an HTTP(S) server, HTTP(S) reverse 
      #               proxy and IMAP/POP3 proxy server
      # processname: nginx
      # config:      /usr/local/nginx/conf/nginx.conf
      # pidfile:     /usr/local/nginx/logs/nginx.pid
      # Source function library.
      . /etc/rc.d/init.d/functions
      # Source networking configuration.
      . /etc/sysconfig/network
      # Check that networking is up.
      [ "$NETWORKING" = "no" ] && exit 0
      nginx="/usr/local/nginx/sbin/nginx"
      prog=$(basename $nginx)
      NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
      lockfile=/var/lock/subsys/nginx
      start() {
          [ -x $nginx ] || exit 5
          [ -f $NGINX_CONF_FILE ] || exit 6
          echo -n $"Starting $prog: "
          daemon $nginx -c $NGINX_CONF_FILE
          retval=$?
          echo
          [ $retval -eq 0 ] && touch $lockfile
          return $retval
      }
      stop() {
          echo -n $"Stopping $prog: "
          killproc $prog -QUIT
          retval=$?
          echo
          [ $retval -eq 0 ] && rm -f $lockfile
          return $retval
      }
     restart() {
          configtest || return $?
          stop
          start
      }
      reload() {
          configtest || return $?
          echo -n $"Reloading $prog: "
          killproc $nginx -HUP
          RETVAL=$?
          echo
      }
      force_reload() {
          restart
      }
      configtest() {
         $nginx -t -c $NGINX_CONF_FILE
      }
      rh_status() {
          status $prog
      }
      rh_status_q() {
          rh_status >/dev/null 2>&1
      }
      case "$1" in
          start)
              rh_status_q && exit 0
              $1
              ;;
          stop)
              rh_status_q || exit 0
              $1
              ;;
          restart|configtest)
              $1
              ;;
          reload)
              rh_status_q || exit 7
              $1
              ;;
          force-reload)
              force_reload
              ;;
          status)
              rh_status
              ;;
          condrestart|try-restart)
              rh_status_q || exit 0
              ;;
          *)
              echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
              exit 2
      esac
      #chmod 700  /etc/init.d/nginx
      #chkconfig --add nginx
      #chkconfig nginx on
   4 nginx 日誌切割,並把其新增到crontable 中讓其每天零點零分執行
     #cd /usr/local/nginx/sbin
     #vim   cut.nginx.log.sh
      #!/bin/bash
      #
      ##
      logs_path="/usr/local/nginx/logs/"
      if [ ! -d "$logs_path$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")" ]
        then
            mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
      fi
      mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
      kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
      cd  ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
      gzip -9 access_$(date -d "yesterday" +"%Y%m%d").log



六 mysql 安裝配置

 1 建立mysql 使用者
 #groupadd mysql
  #useradd -g mysql mysql 
 
   2 編譯安裝mysql  #tar zxvf mysql-5.0.91.tar.gz #cd mysql-5.0.91 #./configure --prefix=/usr/local/mysql --localstatedir=/var/lib/mysql --with-plugins=innobase --with-mysqld-user=mysql --without-debug --with-big-tables --with-charset=utf8 --with-extra-charsets=all --with-pthread --enable-static --enable-thread-safe-client --with-unix-socket-path=/var/lib /mysql/mysql.sock #make&&make install 3 初始化mysql #cd /usr/local/mysql #bin/mysql_install_db –user=mysql #chown –R root:mysql . #chown –R mysql /var/lib/mysql #cp share/mysql/my-medium.cnf /etc/my.cnf #cp share/mysql/mysql.server /etc/rc.d/init.d/mysqld #chmod 755 /etc/rc.d/init.d/mysqld #chkconfig –add mysqld #chkconfig mysqld on 4 優化mysql 配置,再次省略了



七 libmcrypt 安裝配置

  #tar  xf libmcrypt-2.5.8.tar.gz
  #./configure --prefix=/usr/local/libmcrypt
  #make  && make install



八 libiconv 安裝配置

  #tar  xf libiconv-1.14.tar.gz
  #cd libiconv-1.14
  #./configure  --prefix=/usr/local/libiconv
  #make && make install 
 



九 php 安裝配置

 1 #tar xf php-5.3.19.tar.gz
   #cd php-5.3.19
   #./configure  --prefix=/usr/local/php --with-freetype-dir --with-jpeg-dir --with-png-dir 
    --with-zlib --with-libxml-dir --enable-xml --disable-debug --enable-fpm --enable-mbstring
    --with-gd --enable-gd-native-ttf  --with-openssl --with-curl --with-curlwrappers 
    --enable-sockets --with-xmlrpc --with-mhash --with-mcrypt=/usr/local/libmcrypt/ 
    --with-mysqli=/usr/bin/mysql_config --with-mysql --enable-zend-multibyte 
    --with-iconv-dir=/usr/local/libiconv/
   #make && make install
 2 #cp   php.ini-production  /usr/local/php/lib/php.ini
 3 配置service啟動php-fpm 的指令碼
   #cd  sapi/fpm
   #cp  init.d.php-fpm.in   /etc/init.d/php-fpm
   #chmod 700 /etc/init.d/php-fpm
   #chkconfig --add php-fpm
   #chkconfig php-fpm on
 4 開啟php 的短標籤,並修改php 的時區
  #vim php.ini
    #開啟php 短標籤
    short_open_tag = On
    #設定php時區
    date.timezone = Asia/Hong_Kong
 5  優化php-fpm
    #cd  /usr/local/php/etc
    #cp  php-fpm.conf.default  php-fpm.conf
     修改下面的引數, 並取消註釋
    #php-fpm程式檔案
     pid = run/php-fpm.pid
    #設定php-fpm日誌級別
     log_level =notice
    #設定php-fpm 子程式最大數目
     process.max = 300
    #設定 master process 開啟的檔案數目
      rlimit_files = 819200
    #指定fpm mechanism event 方式
       events.mechanism = epoll
    #指定php-fpm 執行的使用者
      user = nginx 
      group = nginx
    #指定php-fpm 監聽的埠
       listen = 127.0.0.1:9000
    #指定 php-fpm 監聽的佇列長度,預設情況下是不限制的
       listen.backlog = 2048
    #設定允許訪問PHP-fpm 的IP 地址
       listen.allowed_clients = 127.0.0.1
    #指定php-fpm 的執行方式,分為static 和dynamic兩種
       pm = dynamic
    # 設定最大的子程式
        pm.max_children = 300
    #設定php-fpm啟動是,開啟的子程式數目
        pm.start_servers = 65
    #設定php-fpm 最小空閒程式數目
        pm.min_spare_servers = 50
    #設定php-fpm,最大空閒程式數目
        pm.max_spare_servers = 80
    #設定每個子程式處理的請求數
        pm.max_requests = 1000
    #設定檢視php-fpm執行狀態
        pm.status_path = /status
        ping.path = /ping
        ping.response = pong
    #設定響應超時時間
        request_slowlog_timeout = 30(s)
    # 設定slow request 日誌檔案
        slowlog = /usr/local/php/var/log/$pool.slow.log



十 xcache 安裝配置

 1 #tar  xf  xcache-3.0.0.tar.gz
   #cd  xcache-3.0.0
   #/usr/local/php/bin/phpize --clean
   #/usr/local/php/bin/phpize
   #./configure --enable-xcache --enable-xcache-optimizer 
     --with-php-config=/usr/local/php/bin/php-config
   #make && make install 
 2 在php配置檔案尾部新增xcache 的配置檔案,內容如下
   ;;Xcache
   ;; this is an example, it won`t work unless properly configured into php.ini
   ;[xcache-common]
   ;;; non-Windows example:
   # 載入xcache.so模組路徑
   extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/xcache.so
   ;;; Windows example:
   ;; extension = php_xcache.dll
   ;
   ;[xcache.admin]
   #設定xcache 管理介面(在此使用者名稱和密碼都是frank, 在此處設定的密碼為md5 加密後的密碼,md5為php計算出來的)
   xcache.admin.enable_auth = On
   xcache.admin.user = "frank"
   ;; set xcache.admin.pass = md5($your_password)
   ;; login use $your_password
   xcache.admin.pass = "712e5d9c46784262937bc4b2215c3beb"
  ;
  ;[xcache]
  ;; ini only settings, all the values here is default unless explained
  ;
  ;; select low level shm/allocator scheme implemenation
  xcache.shm_scheme =        "mmap"
  ;; to disable: xcache.size=0
  ;; to enable : xcache.size=64M etc (any size > 0) and your system mmap allows
  xcache.size  =        64M
  ;; set to cpu count (cat /proc/cpuinfo |grep -c processor)
  xcache.count =         12
  ;; just a hash hints, you can always store count(items) > slots
  xcache.slots =                4K
  ;; ttl of the cache item, 0=forever
  xcache.ttl   =                 0
  ;; interval of gc scanning expired items, 0=no scan, other values is in seconds
  xcache.gc_interval =           0
  ;
  ;; same as aboves but for variable cache
  xcache.var_size  =            4M
  xcache.var_count =             12
  xcache.var_slots =            4K
  ;; default value for $ttl parameter of xcache_*() functions
  xcache.var_ttl   =             0
  ;; hard limit ttl that cannot be exceed by xcache_*() functions. 0=unlimited  
  xcache.var_maxttl   =          0
  xcache.var_gc_interval =     300
  ;
  ;; mode:0, const string specified by xcache.var_namespace
  ;; mode:1, $_SERVER[xcache.var_namespace]
  ;; mode:2, uid or gid (specified by xcache.var_namespace)
  ;xcache.var_namespace_mode =    0
  ;xcache.var_namespace =        "" 
  ;
  ;; N/A for /dev/zero
  ;xcache.readonly_protection = Off
  ;; for *nix, xcache.mmap_path is a file path, not directory. (auto create/overwrite)
  ;; Use something like "/tmp/xcache" instead of "/dev/*" if you want to turn on ReadonlyProtection
  ;; different process group of php won`t share the same /tmp/xcache
  ;; for win32, xcache.mmap_path=anonymous map name, not file path
  xcache.mmap_path =    "/dev/zero"
  ;
  ;
  ;; leave it blank(disabled) or "/tmp/phpcore/"
  ;; make sure it`s writable by php (open_basedir is not checked)
  ;xcache.coredump_directory =   ""
  ;; disable cache after crash
  ;xcache.disable_on_crash =    Off
  ;
  ;; enable experimental documented features for each release if available
  ;xcache.experimental =        Off 
  ;
  ;; per request settings. can ini_set, .htaccess etc
  xcache.cacher =               On
  xcache.stat   =               On
  ;xcache.optimizer =           Off
  ;
  ;[xcache.coverager]
  ;; enabling this feature will impact performance
  ;; enabled only if xcache.coverager == On && xcache.coveragedump_directory == "non-empty-value"
  ;
  ;; per request settings. can ini_set, .htaccess etc
  ;; enable coverage data collecting and xcache_coverager_start/stop/get/clean() functions
  ;xcache.coverager =           Off
  ;xcache.coverager_autostart =  On
  ;
  ;; set in php ini file only
  ;; make sure it`s readable (open_basedir is checked) by coverage viewer script
  ;xcache.coveragedump_directory = ""
 3 重啟php-fpm
  #service php-fpm stop
  #service php-fpm  start
本文轉自 freehat08 51CTO部落格,原文連結:http://blog.51cto.com/freehat/1177298,如需轉載請自行聯絡原作者


相關文章