Nginx從入門到掌握【(第1節(共3節)】Centos6.6版本

目錄:

  1. Nginx簡介.  

  2. Nginx的特性.

  3. Nginx的功能.

  4. Nginx的模塊類型.

  5. 源碼編譯安裝Nginx.

  6. nginx相關命令.

  7. Nginx的配置文件介紹.

  8. Nginx的配置指令詳解.


正文:

一、Nginx簡介:(摘自nginx官網wiki文檔)

  NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. NGINX is known for its high performance, stability(穩定性), rich feature set, simple configuration, and low resource consumption(消耗).

  NGINX is one of a handful of servers written to address the C10K problem. Unlike traditional servers, NGINX doesn’t rely(依靠) on threads to handle (線程處理)requests. Instead it uses a much more scalable(可擴展的) event-driven (asynchronous,異步) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from NGINX’s high-performance and small memory footprint. NGINX scales(規模) in all directions: from the smallest VPS all the way up to large clusters of servers.


二、Nginx的特性. 

  1)模塊化設計;

  2)高可靠性:

    master --> worker 

  3)低內存消耗: 

    10000個keep-alive模式下的connection,僅需要2.5MB的內存; 

  4)支持熱部署:

    不停機而更新配置文件,日誌文件滾動,升級程序版本; 


三、Nginx的功能. 

  1.基本功能:
    1)靜態資源的web服務器,能緩存打開的文件描述符;
    2)http,smpt,pop3協議的反向代理服務器;
    3)緩存加速,負載均衡;
    4)支持FastCGI(fpm,LNMP),uWSGI(python)等; 
    5)模塊化(非DSO機制),過濾器zip,SSI及圖像的大小寫調整;
    6)支持SSL:
  2.擴展功能:
    1)基於名稱和IP的虛擬主機;
    2)支持keepalive;
    3)支持平滑升級;
    4)定製訪問日誌,支持使用日誌緩衝區提供日誌存儲性能;
    5)支持url rewrite;
    6)支持路徑別名;
    7)支持基於IP及用戶的訪問限制;
    8)支持速率限制,支持併發數限制;


四、Nginx的模塊類型.

  1. 核心模塊
  2. Standard HTTP modules 
  3. Optional HTTP modules  
  4. Mail modules 
  5. 3rd party modules 


五、源碼編譯安裝Nginx. 

  系統環境:CentOS7.3 

  nginx軟件包版本:1.10.2 Stable version

  Nginx的安裝方式有兩種,即RPM安裝和源碼編譯安裝。此處採用編譯安裝的方式,Linux系統爲CentOS7.3. 

  首先到官網下載相應Stable version安裝包:

[root@localhost ~]# cat /etc/centos-release 
CentOS release 6.6 (Final)
[root@localhost ~]# wget http://nginx.org/download/nginx-1.10.2.tar.gz


開始安裝:

[root@localhost ~]# useradd -s /sbin/nologin -M nginx
//創建nginx用戶及nginx組來運行nginx服務進程.
[root@localhost ~]# mkdir /data/nginx/logs/ -p
[root@localhost ~]# touch /data/nginx/logs/error.log  
[root@localhost ~]# touch /data/nginx/{nginx.pid,nginx.lock}  
//創建相關文件的存儲位置.
[root@localhost ~]# yum -y gd gd-devel pcre pcre-devel
[root@localhost ~]# tar zxf nginx-1.10.2.tar.gz
[root@localhost ~]# cd nginx-1.10.2
[root@localhost nginx-1.10.2]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
[root@localhost nginx-1.10.2]#

 注:

  1)gd庫,是php處理圖形的擴展庫,GD庫提供了一系列用來處理圖片的API,使用GD庫可以處理圖片,或者生成圖片。 

  2)PCRE(Perl Compatible Regular Expressions)是一個Perl庫,包括 perl 兼容的正則表達式庫。

  查看編譯安裝的選項:


[root@localhost nginx-1.10.2]# ./configure --help
 
  --help                             print this message
 
  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set nginx.pid pathname
  --lock-path=PATH                   set nginx.lock pathname
 
  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes
 
  --build=NAME                       set build name
  --builddir=DIR                     set build directory
 
  --with-select_module               enable select module
  --without-select_module            disable select module
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module
 
  --with-threads                     enable thread pool support
 
  --with-file-aio                    enable file AIO support
  --with-ipv6                        enable IPv6 support
 
  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
  --with-http_image_filter_module=dynamic
   
  ......
 
[root@localhost nginx-1.10.2]#


  注:以上模塊編譯時需要有選擇性的安裝,萬一哪個模塊安裝時漏掉了也不用擔心,因爲nginx支持熱部署,可以隨時增加需要的模塊!

  下一步進行編譯:

[root@nginx nginx-1.10.2]# ./configure \
 --prefix=/usr/local/nginx-1.10.2 \
 --error-log-path=/data/nginx/logs/error.log \
 --pid-path=/data/nginx/nginx.pid \
 --lock-path=/data/nginx/nginx.lock \
 --user=nginx \
 --group=nginx \
 --with-threads \
 --with-http_ssl_module \
 --with-http_image_filter_module \
 --with-http_image_filter_module=dynamic \
 --with-http_flv_module \
 --with-http_mp4_module  \
 --with-http_gunzip_module \
 --with-http_gzip_static_module \
 --with-http_slice_module  \
 --with-stream \
[root@nginx nginx-1.10.2]# make && make install


 做軟連接: 


[root@nginx nginx-1.10.2]# cd
[root@nginx ~]# ls /usr/local/nginx-1.10.2/ -d
/usr/local/nginx-1.10.2/
[root@nginx ~]# ln -sv /usr/local/nginx-1.10.2/ /usr/local/nginx
"/usr/local/nginx" -> "/usr/local/nginx-1.10.2/"
[root@nginx ~]#


 啓動服務並查看監聽端口:

[root@nginx ~]# ./usr/local/nginx/sbin/nginx 
[root@nginx ~]# ss -tunlp |egrep "nginx"
tcp    LISTEN     0      128       *:80                    *:*                   users:(("nginx",pid=11743,fd=6),("nginx",pid=11742,fd=6))
[root@nginx ~]#


 在iptables添加允許訪問80端口規則

    

[root@localhost sbin]# iptables -A INPUT -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
[root@localhost sbin]# service iptables reload                                         
iptables: Trying to reload firewall rules:                 [  OK  ]

 

六、nginx相關命令. 


 1. 查看系統已裝載的nginx模塊選項:

  # /usr/local/nginx/sbin/nginx -V    

 2. 編譯啓動腳本:

[root@localhost conf]# cat /etc/init.d/nginx 
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# 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
# config:      /usr/local/nginx/sbin/nginx
# pidfile:     /data/nginx/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"
  
[ -f /usr/local/nginx ] && . /usr/local/nginx
lockfile=/data/nginx/nginx.lock
  
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
  
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    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
    sleep 1
    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



七、Nginx的配置文件介紹. 

 Nginx的配置段主要有以下三項:

  1、main配置段:全局配置段              
  2、event: 定義event模型工作特性        
  3、http{}: 定義http協議相關的配置    

 配置文件介紹:

八、Nginx的配置指令詳解. 

 1. 正常運行的必備配置段:

 1) user USERNAME [GROUPNAME]  

   指定運行worker進程的用戶和組;
   例:user nginx nginx  

   注: 用戶和組如果一起部署且相同的話,GROUPNAME可以省略. 

 2) pid /path/to/PID_FILE 

   指定nginx守護進程的pid文件. 

   例: pid /data/nginx/nginx.pid  

   注: pid文件的作用在於防止進程啓動多個副本.只有獲得pid文件寫入權限的進程才能正常啓動並  把自身進程pid寫入該文件中,其他同一個程序的多餘進程會自動退出.

  查看本系統的pid文件:

1
2
3
4
5
6
7
8
9
10
11
[root@nginx ~]# cat /data/nginx/nginx.pid
cat/data/nginx/nginx.pid: 沒有那個文件或目錄
[root@nginx ~]# /usr/local/nginx/sbin/nginx 
[root@nginx ~]# cat /data/nginx/nginx.pid
2561
[root@nginx ~]# ps -aux |egrep "nginx"
root       2529  0.1  0.5 151800  5436 pts/0    S+   10:18   0:00 vim /usr/local/nginx/conf/nginx.conf
root       2561  0.0  0.1  45376  1112 ?        Ss   10:27   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      2562  0.0  0.1  45824  1884 ?        S    10:27   0:00 nginx: worker process
root       2565  0.0  0.0 112664   972 pts/1    S+   10:28   0:00 grep -E --color=auto nginx
[root@nginx ~]#

 3) worker_connections  NUM; 

   指定所有worker進程所能夠打開的最大文件句柄數; 
   默認打開文件最大數爲1024個.

 2. 性能優化相關的配置:

 1) worker_processes NUM; 

   指定nginx進程數,建議按照cpu 數目來指定,一般爲它的倍數 (如,2個四核的cpu計爲8)。

   例: worker_processes 4;

 2) worker_cpu_affinity cpumask ...; 
   指定爲每個進程分配CPU,提升緩存的命中率.

   例: worker_cpu_affinity 00000001 00000010 00000100 00001000;

   上例中將4個進程分配到4個cpu,注意與worker_process數相對應.當然可以寫多個,或者將一個進程分配到多個cpu。

 3) timer_resolution TIME; 

   指定計時器解析度:降低此值,可減少gettimeofday()系統調用的次數;

   默認值:none
   例: timer_resolution 100ms;

   該配置指令允許用戶減少調用gettimeofday()的次數。默認情況下,該函數在每次I/O端口監聽 (比如epoll_wait)返回後都將被調用,而通過timer_resolution配置選項可以直接指定調用 gettimeofday()函數的間隔時間.

 4) worker_priority NUM:  

   指明worker進程的nice值,即worker進程的優先級; 

   nice值越小,優先級越高,默認只能由管理員有權限調整nice值; 

 3. 事件相關的配置: 

 1) accept_mutex {off|on};
   指定master進程調度用戶請求至各worker進程時使用的負載均衡鎖; on表示能讓多個worker輪流地、序列化地去響應新請求;
 2) lock_file file;
   accept_mutex用到的鎖文件路徑;     
 3) use [epoll|rtsig|select|poll]; 
   指明使用的時間模型;建議讓nginx自行選擇;     
 4) worker_connections #; 
   設定單個worker進程所能夠處理的最大併發連接數量;
   計算公式:worker_connections * work_processes , 可能會小於這個值; 

 4. 用戶用於調試, 定位問題:
 1) daemon {on|off}; 
   是否以守護進程方式運行nginx: 調試時應該設置爲off。 
 2) master_process {on|off}; 
   是否以master/worker模型來運行nginx;調試時可以設置爲off;
 3) error_log file |stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg]; 
   語法: error_log [位置] [級別]; 
   若要使用debug級別, 需要在編譯nginx時使用--with-debug選項; 

 5. 總結:常需要進行調整的參數:
   worker_processes,worker_connections,worker_cpu_affinity,worker_priority. 


--- 第一部分完成!


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