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. 


--- 第一部分完成!


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