Nginx学习笔记

warning: 这篇文章距离上次修改已过249天,其中的内容可能已经有所变动。

一、简介
Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

二、Nginx的五个特点
1、动静分离
2、负载均衡
3、反向代理
4、正向代理
5、单点故障

三、安装(编译)
官方下载:http://nginx.org/en/download.html

列举Linux版本安装

wget http://nginx.org/download/nginx-1.16.1.tar.gz
yum install make openssl-devel openssl gcc pcre pcre-devel zlib-devel zlib 
cd /usr/local/src
tar zxvf nginx-1.16.1.tar.gz
cd nginx-1.16.1
./configure --prefix=/usr/local/nginx   //安装路径
make && make install

启动服务

cd /usr/local/nginx
./nginx/sbin/nginx

四、常用命令
1、查看nginx版本

./nginx -v

2、启动服务

./nginx 

3、关闭服务

./nginx -s stop

4、重新加载

./nginx -s reload

五、配置文件
nginx三部分组成

1、全局块
从配置文件开始到events块之间的内容,主要会设置一些影响nginx服务器整体运行的配置指令,主要包括配置运行nginx服务器的用户(组)、允许生产的worker process数,进程PID存放路径、日志存放路径和类型以及配置文件的引入。

eg:

#user  nobody;
worker_processes  1;  // 值越大,可以支持的并发处理量也越多,但是受到硬件、软件影响
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;

2、events块
events块涉及的指令主要影响nginx服务器与用户的网络连接

eg:

events {
    worker_connections  1024;  //支持最大连接数
}

3、http块
nginx服务器配置中最频繁的部分包含http全局块和server块

3.1、http全局块
eg:

    include       mime.types;
    default_type  application/octet-stream;
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;    

3.2、server块
eg:

    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }

六、配置实例
1、反向代理
1.1、案例1
当访问 192.168.128.110:80,自动跳转至www.ytyzhn.cn

当访问 192.168.128.110:80,自动跳转至127.0.0.1:8080

     server {
        listen       80;
        server_name  192.168.128.110;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http://www.ytyzhn.cn:80;
            root   html;
            index  index.html index.htm;
        }
     server {
        listen       80;
        server_name  192.168.128.110;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            proxy_pass http://127.0.0.1:8080;  //反向解析,当访问192.168.128.110:80时,会转发到127.0.0.1:8080
            index  index.html index.htm;
        } 

1.2、案例2
访问 http://192.168.128.110:9001/edu/ 直接跳转到 127.0.0.1:8081
访问 http://192.168.128.110:9001/vod/ 直接跳转到 127.0.0.1:8082

 
    server {
        listen       9001;
        server_name  192.168.128.110;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location ~ /edu/ {
            proxy_pass http://127.0.0.1:8081;
        }
        
        location ~ /vod/ {
            proxy_pass http://127.0.0.1:8082;
        }

注意:

 1、= :用于不含正则表达式的uri前,要求请求字符串与uri严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。
 2、~:用于表示uri包含正则表达式,并且区分大小写。
 3、~*:用于表示uri包含正则表达式,并且不区分大小写。
 4、~~:用于不含正则表达式的uri前,要求Nginx 服务器找到标识uri和请求字符串匹配度最高的location 后,立即使用此location处理请求,
 而不再使用location块中的正则uri和请求字符串做匹配。

2、负载均衡

 访问:http://192.168.128.110/edu/a.html 流量平均分配到:
  192.168.128.110:8081
  192.168.128.110:8081

eg:

 
    http{
    ......
        upstream myserver{        //myserver 自定义名称
            ip_hash;
            server 192.168.128.110:8081 weight=1;
            server 192.168.128.110:8082 weight=1;
            fair;
        }
    ......    
        server{
            location / {
                .......
                proxy_pass http://myserver;
                proxy_connect_timeout 10;
            }
        }
    }

nginx分配服务器策略

(1)、轮询(系统默认自带)

    每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down,能自动剔除。

(2)、weight,权重

    weight代表权重默认为1,权重越高分配的客户端约多。

(3)、ip_hash,意思即为,当一个客户端第一次访问到后端一台服务器,后续操作都在那台服务器;

    每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决 session 的问题。

(4)、fair

    按后端服务器的响应时间来分配请求,响应时间短的优先分配.

3、动静分离

Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,可以理解成使用 Nginx 处理静态页面,Tomcat 处理动态页面。动静分离从目前实现角度来讲大致分为两种,

一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案;
另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开。
通过 location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使浏览器缓存过期时间,减少与服务器之前的请求和流量。具体 Expires 定义:是给一个资源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可,所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天之内访问这个 URL,发送一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码304,如果有修改,则直接从服务器重新下载,返回状态码 200。

eg:

 
    目的:访问192.168.128.110/www/a.html 192.168.128.110/images/1.png
    文件位置:   /data/www/a.html      /data/images/1.png

    server {
        listen       80;
        server_name  192.168.128.110;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location /www/ {
            root   /data/;     
            index  index.html index.htm;
        }
        
        location /images/ {
            root   /data/;     
            index  index.html index.htm;
            autoindex on;  //罗列出当前目录下所有文件,
        }
注:最后检查 Nginx 配置是否正确即可,然后测试动静分离是否成功,之需要删除后端 tomcat
服务器上的某个静态文件,查看是否能访问,如果可以访问说明静态资源 nginx 直接返回了,不走后端 tomcat 服务器

七、Nginx配置高可用的

准备
    (1)、需要两台 nginx 服务器
    (2)、需要 keepalived
    (3)、需要虚拟 ip,共计3个ip

 主从服务器配置

1、安装keepalived,nginx(安装见前面:编译安装)
 
yum –y install keepalived 

  2、修改/etc/keepalived/keepalivec.conf 配置文件

 
            global_defs {
                notification_email {
                    acassen@firewall.loc
                    failover@firewall.loc
                    sysadmin@firewall.loc
                }
                notification_email_from Alexandre.Cassen@firewall.loc
                smtp_server 192.168.128.110    # 192.168.128.110 为主服务器IP
                smtp_connect_timeout 30
                router_id LVS_DEVEL           # LVS_DEVEL 为主服务器主机名
            }

            vrrp_script chk_http_port {
                script "/usr/local/src/nginx_check.sh"
                    interval 2    #(检测脚本执行的间隔)            
                    weight 2        
            }        
                    
            vrrp_instance VI_1 {        
                state MASTER    # 备份服务器上将 MASTER 改为 BACKUP    
                interface ens33       # 网卡    
                virtual_router_id 51   # 主、备机的 virtual_router_id 必须相同    
                priority 90      # 主、备机取不同的优先级,主机值较大,备份机值较小    
                advert_int 1        
                authentication {
                    auth_type PASS    
                    auth_pass 1111   #认证密码
                }
                virtual_ipaddress {
                    192.168.128.100 // VRRP H 虚拟地址
                }
            }

  3、在/usr/local/src 添加检测脚本nginx_check.sh (主备都加)

 
            #!/bin/bash
            A=`ps -C nginx –no-header |wc -l`
            if [ $A -eq 0 ];then
                /usr/local/nginx/sbin/nginx
                sleep 2
                if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
                    killall keepalived
                fi
            fi

  4、启动服务

 
            nginx:./nginx
            keepalived:systemctl start keepalived.service

八、Nginx原理

1、一台nginx服务器中有一个mater 和 多个worker,自定义在nginx配置文件中修改worker数量
 
        worker_processes  1;
        events {
            worker_connections  1024;
        }
2、worker 如何进行工作的:采用争抢的方式。
3、一个 master 和多个 woker 有好处
    3.1、可以使用 nginx –s reload 热部署,利用 nginx 进行热部署操作
    3.2、每个 woker 是独立的进程,如果有其中的一个 woker 出现问题,其他 woker 独立的,继续进行争抢,实现请求过程,不会造成服务中断
4、设置多少个 woker 合适
    worker 数和服务器的 cpu 数相等是最为适宜的
5、连接数 worker_connection
    第一个:发送请求,占用了 woker 的几个连接数?
    答案:2 或者 4 个
    第二个:nginx 有一个 master,有四个 woker,每个 woker 支持最大的连接数 1024,支持的最大并发数是多少?
   答案:   普通的静态访问最大并发数是: worker_connections * worker_processes /2, 而如果是 HTTP 作 为反向代理来说,最大并发数量应该是 worker_connections * worker_processes/4。

教学视频可访问 https://www.bilibili.com/video/BV1zJ411w7SV

最后修改于:2023年08月14日 16:30

已有 3 条评论

  1. ivan ivan

    icon_mrgreen.gif icon_mrgreen.gif icon_mrgreen.gif icon_mrgreen.gif

  2. 小袁同学 小袁同学

    基础使用已经够了,谢谢! icon_biggrin.gif

添加新评论

icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif