nginx

nginx学习笔记

nginx是什么?

nginx是反向代理服务器。

正向代理和反向代理

  • 正向代理:与客户端绑定在一起,所有的客户端发起的请求,都会经过代理对请求进行包装,然后所有的客户端的请求都是通过这个代理发送到服务器,
    服务器并不知道具体是哪儿个客户端发过来的请求。
  • 反向代理:与服务器绑定在一起,客户端发起请求后,所有的客户端的请求都会通过代理服务器分发给不同的服务器去处理,客户端并不知道自己请求的
    服务器是哪儿个。

为什么要使用nginx?

  • 保证系统安全性:可以使用nginx来过滤那些可能会威胁服务安全的请求以及禁用恶意请求的ip来保证服务的安全。
  • 负载均衡:在集群环境下,对请求进行分发,保证每个服务器都可以拿到请求,降低单个服务器节点的压力。

为什么会出现集群?
如果只有一台服务器节点,那么当并发量大的时候,单个节点的压力就会增大,当压力非常大的时候就会造成服务的宕机。或者当服务器出现硬件问题,就会宕机
那么服务器宕机期间,我们的服务就是不可用的。为了保证服务的可用性,就需要启用多个服务的实例,形成集群,当一台服务器宕机时,还有其他的服务器可以
提供服务。
那么此时就会有一个问题,当启动了多个服务实例时,就会相应的出现多个服务的ip地址,每个服务的ip地址是不一样的,客户端请求时如何知道当前服务可不可用
该请求哪儿个节点的ip。当出现多个不同的服务时?这个地址又该如何处理?
nginx的负载均衡就可以很好的处理。只需要对外提供一个nginx的服务ip地址。然后所有的请求都发到nginx,通过nginx转发到不同的服务器。以及对单个服务的多个节点
进行请求分发。
此时那么此时又会引出一个新问题,如果nginx宕机了该怎么办?
对nginx也启用多个节点,保证服务的可用性。这是很容易就想到的,那么当nginx切换后,客户端怎么知道ip地址变成了什么?
这时就会出现一个新技术--keepalived。使用keepalived可以监控nginx节点,如果nginx宕机的话,就为一台健康的nginx节点设置ip地址为我们提供服务的ip地址。

nginx的安装

  • 下载nginx压缩包 wget http://nginx.org/download/nginx-1.17.3.tar.gz
  • 解压压缩包 tar zxvf nginx-1.17.3.tar.gz
  • 安装nginx配置包 yum -y install gcc pcre-devel openssl openssl-devel
  • 创建nginx快捷方式
    进入nginx解压后目录,执行 ./configure --prefix=/usr/local/nginx-1.17.3(--prefix设置nginx的安装目录)
Configuration summary
+ using system PCRE library
+ OpenSSL library is not used
+ using system zlib library

nginx path prefix: "/usr/local/nginx-1.17.3"
nginx binary file: "/usr/local/nginx-1.17.3/sbin/nginx"
nginx modules path: "/usr/local/nginx-1.17.3/modules"
nginx configuration prefix: "/usr/local/nginx-1.17.3/conf"
nginx configuration file: "/usr/local/nginx-1.17.3/conf/nginx.conf"
nginx pid file: "/usr/local/nginx-1.17.3/logs/nginx.pid"
nginx error log file: "/usr/local/nginx-1.17.3/logs/error.log"
nginx http access log file: "/usr/local/nginx-1.17.3/logs/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp"

出现上面内容表示创建快捷方式成功。

  • 编译
    进入nginx解压目录下,执行 make && make install
make[1]: Leaving directory `/home/apps/nginx-1.17.3'

出现以上内容,表明编译成功。

  • 启动服务
    进入快捷方式目录 cd /usr/local/nginx-1.17.3/sbin
    执行启动脚本: ./nginx

nginx的负载均衡配置

打开nginx的配置文件 vi /usr/local/nginx-1.17.3/conf/nginx.conf
nginx的配置的每条指令必须要以分号结束。

#user  nobody; # 配置用户或用户组
worker_processes  1; #允许生成的进程数

#error_log  logs/error.log; # 指定nginx日志以及日志级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid; # 指定nginx运行时进程id文件存放地址

# events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。
events {
    worker_connections  1024;
}

# nginx虚拟服务器配置
http {
    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;
    # 配置负载均衡,weight配置权重
    # 更多信息:https://www.cnblogs.com/Zs-book1/p/11436798.html
    upstream git.com {
        server 192.168.226.138:7000 weight=1;
        server 192.168.226.139:7000 weight=2;
    }

    # 配置虚拟主机的参数
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        location /git {

            # 设置最大允许上传单个的文件大小
            client_max_body_size 1024m;
            proxy_redirect off;
            #以下确保 gitlab中项目的 url 是域名而不是 http://git,不可缺少
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            # ip黑名单
            deny 192.168.226.138;
            # ip白名单
            allow 192.168.226.138;         
            ### 黑名单和白名单要配置在proxy_pass上面,all
   
            # 反向代理到 gitlab 内置的 nginx
            proxy_pass http://git.com/gitlab;
            index index.html index.htm;
            
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

负载均衡实践:

首先启动两台linux服务器,nginx01,nginx02。然后安装nginx,jdk,tomcat。
我启动的两台服务的ip地址分别为: 192.168.226.139, 192.168.226.140
启动tomcat两台服务器的tomcat服务:

[root@nginx02 apache-tomcat-8.5.43]# pwd
/usr/local/apache-tomcat-8.5.43
[root@nginx02 apache-tomcat-8.5.43]# cd bin/
[root@nginx02 bin]# ./catalina.sh start
Using CATALINA_BASE:   /usr/local/apache-tomcat-8.5.43
Using CATALINA_HOME:   /usr/local/apache-tomcat-8.5.43
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-8.5.43/temp
Using JRE_HOME:        /usr/local/jdk1.8.0_221
Using CLASSPATH:       /usr/local/apache-tomcat-8.5.43/bin/bootstrap.jar:/usr/local/apache-tomcat-8.5.43/bin/tomcat-juli.jar
Tomcat started.

测试访问8080端口,tomcat启动成功。然后修改tomcat的主页内容:

[root@nginx02 ROOT]# pwd
/usr/local/apache-tomcat-8.5.43/webapps/ROOT
[root@nginx02 ROOT]# vi index.jsp 

在body标签下加h1标签展示ip地址:

    ....
    <body>
        <h1>192.168.226.139</h1>
        <div id="wrapper">
    ....

然后重启tomcat服务。再次访问8080端口,可以看到tomcat主页上会显示ip地址。
按照同样的操作,在另一台服务器启动tomcat,此时我们就启动了两台tomcat服务,然后使用139的nginx来对这两台服务做负载均衡。
编辑上的的nginx.conf文件:

[root@nginx02 ROOT]# vi /usr/local/nginx-1.17.3/conf/nginx.conf
...省略不变内容
    upstream tomcat.com{
        server 192.168.226.139:8080;
        server 192.168.226.140:8080;
    }
    server {
        listen       80;
        server_name  location;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://tomcat.com;
        }
...省略不变内容

然后直接在浏览器访问nginx,输入http://192.168.226.139可以直接访问到tomcat,点击ip地址,重新请求,可以看到tomcat展示的IP地址是来回变化的。
至此nginx的负载均衡就实现了。

nginx高可用--keepalived

通过nginx的负载均衡,我们可以通过一个对外提供一个ip地址,将不同的请求分发到不同的服务器进行处理。内部服务可以配置多实例,通过nginx负载均衡来
分发,然后如果有服务宕机,nginx会自动重新发送到可用的服务。但是nginx只有一台,那么就容易发生单点故障。当nginx宕机时,或者nginx这个服务器断电,断网等都可能
造成整个服务不可用。可以使用keepalived解决这个问题。

keepavlied安装

[root@zhaoshuai ~]# yum -y install keepalived
......
Installed:
  keepalived.x86_64 0:1.2.13-5.el6_6                                                                                                                                                           

Complete!
[root@zhaoshuai ~]# rpm -q -a keepalived
keepalived-1.2.13-5.el6_6.x86_64

重新编辑配置文件,本次配置为抢占式配置:

[root@zhaoshuai ~]# cd /etc/keepalived/
[root@zhaoshuai keepalived]# mv keepalived.conf keepalived.conf.backup
[root@zhaoshuai keepalived]# vi keepalived.conf
global_defs {
   #标识本节点的名称,通常为hostname
   router_id nginx01  
}

## keepalived会定时执行脚本并对脚本执行的结果进行分析,动态调整vrrp_instance的优先级。
##如果脚本执行结果为0,并且weight配置的值大于0,则优先级相应的增加。如果脚本执行结果非0,
##并且weight配置的值小于 0,则优先级相应的减少。其他情况,维持原本配置的优先级,即配置文件中priority对应的值。
vrrp_script chk_nginx {
       # 检测nginx状态的脚本
       script "/etc/keepalived/nginx_check.sh"
       #每2秒检测一次nginx的运行状态
       interval 2  
       #失败一次,将自己的优先级-20
       weight -20  
}

vrrp_instance VI_1 {
    state MASTER                  # 状态,主节点为MASTER,备份节点为BACKUP
    interface eth0             # 绑定VIP的网络接口,通过ifconfig查看自己的网络接口,vip:虚拟ip
    virtual_router_id 51          # 虚拟路由的ID号,两个节点设置必须一样,可选IP最后一段使用,相同的VRID为一个组,他将决定多播的MAC地址
    mcast_src_ip 192.168.226.139    # 本机IP地址
    priority 100                  # 节点优先级,值范围0~254,MASTER要比BACKUP高
    advert_int 1                  # 组播信息发送时间间隔,两个节点必须设置一样,默认为1秒
    # 设置验证信息,两个节点必须一致
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    # 虚拟IP:vip,两个节点设置必须一样。可以设置多个,一行写一个
    virtual_ipaddress {
        192.168.226.100
    }

    track_script {
       # nginx存活状态检测脚本
       chk_nginx  
    }
}

检测nginx存货状态的脚本 nginx_chkconfig内容如下:

#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
    /usr/local/nginx-1.17.3/sbin/nginx #尝试重新启动nginx
    sleep 2  #睡眠2秒
    if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
        killall keepalived #启动失败,将keepalived服务杀死。将vip漂移到其它备份节点
    fi
fi

此脚本的位置需要与keepalived.conf中chk_nginx中 script配置的路径一致,上面配置的是 script "/etc/keepalived/nginx_check.sh",因此
我们放到这个位置,并为它添加权限。 chmod +x /etc/keepalived/nginx_check.sh
keepalived.conf中配置interface 取值:

[root@nginx01 keepalived]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:9C:34:C6  
          inet addr:192.168.226.139  Bcast:192.168.226.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe9c:34c6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1937 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1903 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:214100 (209.0 KiB)  TX bytes:347042 (338.9 KiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:150 errors:0 dropped:0 overruns:0 frame:0
          TX packets:150 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:126362 (123.4 KiB)  TX bytes:126362 (123.4 KiB)

[root@nginx01 keepalived]# 

注意ip地址192.168.226.139是在 eth0后面的内容,因此配置文件中写的时 interface eth0
配置完成,启动keepalived:

[root@zhaoshuai keepalived]# service keepalived start

查看进程:

[root@nginx01 keepalived]# ps -ef |grep keepalived
root       4799      1  0 03:56 ?        00:00:00 /usr/sbin/keepalived -D
root       4801   4799  0 03:56 ?        00:00:00 /usr/sbin/keepalived -D
root       4802   4799  0 03:56 ?        00:00:00 /usr/sbin/keepalived -D
root       4804   2622  0 03:56 pts/0    00:00:00 grep keepalived
[root@nginx01 keepalived]# 

keepalived启动成功。然后输入 ip add

[root@nginx01 keepalived]# ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:9c:34:c6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.226.139/24 brd 192.168.226.255 scope global eth0
    inet 192.168.226.100/32 scope global eth0
    inet6 fe80::20c:29ff:fe9c:34c6/64 scope link 
       valid_lft forever preferred_lft forever
3: pan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN 
    link/ether da:6c:83:d9:d8:3e brd ff:ff:ff:ff:ff:ff

注意到2:后面,ip地址下出现配置的vip:192.168.226.100。
修改nginx的监听端口为 192.168.226.100:

......
    server {
        listen       80;
        server_name  192.168.226.100;
......

然后重启nginx,此时重启nginx,页面访问 http://192.168.226.100仍然可以访问到tomcat
然后我们配置keepalived备份节点,keepalived.conf内容中 state 修改为BACKUP, 实际ip地址修改,备份节点优先级降低。

global_defs {
   router_id nginx02
}

vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    mcast_src_ip 192.168.226.140
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.226.100
    }

    track_script {
       chk_nginx
    }
}

剩下的操作与master中操作相同。配置完成后,将nginx01的keepalived停掉。然后继续访问 http://192.168.226.100,发现仍能访问,在140上输入ip add,
可以看到 192.168.226.100因为master宕机的原因,漂到了140这台服务器。

动静分离

将动态请求和静态请求分开,nginx处理静态页面,tomcat处理动态请求。
在nginx配置文件中配置静态资源处理:

        location /static {
            # root后面接 根据经
            root   /usr/local/nginx-1.17.3/;
        }

参考资料

nginx高可用
就是要让你搞懂nginx

原文地址:https://www.cnblogs.com/Zs-book1/p/13958702.html