一、Nginx概述

1、nginx简介

  传统上基于进程或线程模型架构的web服务通过每进程或每线程处理并发连接请求,这势必会在I/O操作时产生阻塞,其另一个必然结果则是对内存或CPU的利用率低下。生成一个新的进程/线程需要事先备好其运行时环境,这包括为其分配堆内存和栈内存,以及为其创建新的执行上下文等。这些操作都需要占用CPU,而且过多的进程/线程还会带来线程抖动或频繁的上下文切换,系统性能也会由此进一步下降。

nginx的主要着眼点就是其高性能以及对物理计算资源的高密度利用,因此其采用了不同的架构模型。受启发于多种操作系统设计中基于“事件”的高级处理机制,nginx采用了模块化事件驱动异步单线程非阻塞的架构,并大量采用了多路复用及事件通知机制。在nginx中,连接请求由为数不多的几个仅包含一个线程的进程worker以高效的回环(run-loop)机制进行处理,而每个worker可以并行处理数千个的并发连接及请求。

Nginx:Engine X

官网:www.nginx.org

最新稳定版:nginx-1.10.3

apache:重量级,稳定,功能强大(丰富)

lighttpd:轻量级



2、nginx的特性

基本功能:

静态资源的web服务器,能自动缓存打开的文件描述符

反向代理服务器:缓存,负载均衡、后端服务器健康状态检测

支持FastCGI,此时nginx也工作于反向代理服务器

模块化机制:非DSO机制,支持多种过滤器gzip,SSI和图像的模块完成图形大小调整等

支持SSL

 

扩展功能:

   基于名称和IP做虚拟主机

   支持keeplive

   支持平滑配置更新或程序版本升级

   定制访问日志,支持使用日志缓存以提高性能

   支持URL rewrite

   支持路径别名

   支持基于IP及用户的认证:

   支持速率限制,并发数限制等


3、Nginx工作原理

一个主进程(master)和几个工作进程(worker),配置了缓存时还会有缓存加载器进程(cache loader)和缓存管理器进程(cache manager)等。所有进程均是仅含有一个线程,并主要通过“共享内存”的机制实现进程间通信。主进程以root用户身份运行,而worker、cacheloader和cache manager均应以非特权用户身份运行。

主进程主要完成如下工作:        

   读取并验正配置信息;

   创建、绑定及关闭套接字;         

   启动、终止及维护worker进程的个数;        

   无须中止服务而重新配置工作特性;         

   控制非中断式程序升级,启用新的二进制程序并在需要时回滚至老版本;         

   重新打开日志文件;        

   编译嵌入式perl脚本;        

worker进程主要完成的任务包括:

    接收、传入并处理来自客户端的连接;        

    提供反向代理及过滤功能;        

    nginx能完成的任何其它任务;        

注:

   如果负载以CPU密集型应用为主,如SSL或压缩应用,则worker数应与CPU数 - 1;如果负载以IO密集型为主,如响应大量内容给客户端,则worker数应该为CPU个数的1.5或2倍。


4、Nginx架构

Nginx的代码是由一个核心和一系列的模块组成, 核心主要用于提供Web Server的基本功能,以及Web和Mail反向代理的功能;还用于启用网络协议,创建必要的运行时环境以及确保不同的模块之间平滑地进行交互。不过,大多跟协议相关的功能和某应用特有的功能都是由nginx的模块实现的。

这些功能模块大致可以分为事件模块、阶段性处理器、输出过滤器、变量处理器、协议、upstream和负载均衡几个类别,这些共同组成了nginx的http功能。

每一个功能或操作都由一个模块来实现。例如,压缩、通过FastCGI或uwsgi协议与upstream服务器通信,以及与memcached建立会话等。


事件驱动方式:

   FreeBSD:kqueue

   Linux:epoll

   solaris:/dev/poll

消息通知:

   select,poll,rt rignals(实时信号)


支持文件AIO

支持sendfile,sendfile64

支持mmap


模块的类别:

  核心模块

  http模块

  邮件模块

  基于TCP的代理、负载均衡模块

  第三方扩展模块

    

5、为什么选择Nginx         

   在高连接并发的情况下,Nginx是Apache服务器不错的替代品,Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一,能够支持高达 50,000 个并发连接数的响应。        

Nginx 是一个非常的简单, 配置文件非常简洁(还能够支持perl语法),Bugs非常少的服务器;Nginx启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动,你还能够不间断服务的情况下进行软件版本的升级。

   Nginx的诞生主要解决C10K问题,nginx并发3-5W没问题,传闻优化好能突破10W


二、nginx的安装

1、环境

CentOS6.5 x86_64

  已安装了常用开发包组:

     Desktop Platform Development

     Development tools

     Server Platform Development


2、安装依赖包



[root@Node7 ~]# yum install pcre-devel openssl-devel


3、创建系统用户nginx


[root@Node7 ~]# useradd -s /sbin/nologin -r nginx
[root@Node7 ~]# id nginx
uid=497(nginx) gid=497(nginx) groups=497(nginx)


4、解压并编译



[root@Node7 ~]# ls nginx-1.10.3.tar.gz 
nginx-1.10.3.tar.gz
[root@Node7 ~]# tar xf nginx-1.10.3.tar.gz
[root@Node7 ~]# cd nginx-1.10.3
[root@Node7 nginx-1.10.3]# ./configure --help    # 先查看编译选项

# ./configure \
  --prefix=/usr \
  --sbin-path=/usr/sbin/nginx \
  --conf-path=/etc/nginx/nginx.conf \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --pid-path=/var/run/nginx/nginx.pid  \
  --lock-path=/var/lock/nginx.lock \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_flv_module \                               # 流媒体模块
  --with-http_stub_status_module \                       # 状态统计模块
  --with-http_gzip_static_module \                       # gzip压缩模块
  --http-client-body-temp-path=/var/tmp/nginx/client/ \   # 客户端实体临时存放的目录
  --http-proxy-temp-path=/var/tmp/nginx/proxy/ \          # 上端服务器实体临时存放的目录
  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \         # 
  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
  --http-scgi-temp-path=/var/tmp/nginx/scgi \
  --with-pcre
  --with-debug
  
# make && make install



5、启动nginx


[root@Node7 ~]# nginx -h       # 先查看nginx命令的使用
nginx version: nginx/1.10.3
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file
  
 [root@Node7 ~]# nginx -t     # 启动前应先检查是否有报错
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)
nginx: configuration file /etc/nginx/nginx.conf test failed

### 解决相关报错:
[root@Node7 ~]# mkdir -pv /var/tmp/nginx/client
mkdir: created directory `/var/tmp/nginx'
mkdir: created directory `/var/tmp/nginx/client'

[root@Node7 ~]# nginx -t    # OK
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

###启动nginx
[root@Node7 ~]# nginx
[root@Node7 ~]# ps aux|grep nginx
root      1553  0.0  0.2  45196  1184 ?        Ss   11:24   0:00 nginx: master process nginx
nginx     1554  0.0  0.3  45624  1748 ?        S    11:24   0:00 nginx: worker process
root      1557  0.0  0.1 103248   852 pts/0    S+   11:24   0:00 grep nginx
[root@Node7 ~]# ss -tuanp|grep 80
tcp    LISTEN     0      128                    *:80                    *:*      users:(("nginx",1553,6),("nginx",1554,6))
[root@Node7 ~]# nginx -s stop   # 停止nginx


默认的站点页面保存位置:



[root@Node7 ~]# ls /usr/html/ 50x.html    index.html



6、为nginx提供SysV风格的服务脚本


[root@Node7 usr]# vim /etc/rc.d/init.d/nginx


[root@Node7 usr]# cat /etc/rc.d/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:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/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/sbin/nginx"
prog=$(basename $nginx)
  
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
  
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
  
lockfile=/var/lock/subsys/nginx
  
make_dirs() {
   # make required directories
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   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

[root@Node7 usr]# chmod +x /etc/rc.d/init.d/nginx 
[root@Node7 usr]# service nginx status
nginx is stopped
[root@Node7 usr]# service nginx start
Starting nginx:                                            [  OK  ]
[root@Node7 usr]# service nginx status
nginx (pid 1690 1688) is running...
[root@Node7 usr]# chkconfig nginx on