总结:高性能web服务器Nginx

编译
[root@CentOS7 ~]# curl -I -A  IE http://www.163.com      返回报头-A 冒充浏览器
HTTP/1.1 200 OK

[root@CentOS7 ~]# yum install gcc pcre-devel openssl-devel zlib-devel -y
[root@CentOS7 ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
[root@CentOS7 ~]# tar xf nginx-1.18.0.tar.gz 
[root@CentOS7 ~]# useradd -r -s /sbin/nologin nginx
[root@CentOS7 ~]# cd nginx-1.18.0/
[root@CentOS7 ~/nginx-1.18.0]# ./configure --prefix=/apps/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre --with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
[root@CentOS7 ~/nginx-1.18.0]# make && make install
[root@CentOS7 ~/nginx-1.18.0]# cp /apps/nginx/conf/nginx.conf /apps/nginx/conf/nginx
[root@CentOS7 ~/nginx-1.18.0]# ln -s /apps/nginx/sbin/nginx /usr/sbin/ 
[root@CentOS7 ~/nginx-1.18.0]# vim /etc/rc.d/rc.local         开机启动
/usr/sbin/nginx  
[root@CentOS7 ~/nginx-1.18.0]# chmod +x /etc/rc.d/rc.local

nginx服务启动一般用nginx、停止用nginx -s stop ,而不是用systemctl,nginx启动服务systemctl停止不了,systemctl启动的nginx -s stop能停止

nginx
[root@CentOS7 ~]# nginx -v           显示版本
nginx version: nginx/1.16.1
[root@CentOS7 ~]# nginx -V           显示配置参数(可作为编译参考)
[root@CentOS7 ~]# nginx -t           检查语法
[root@CentOS7 ~]# nginx -T           查看配置文件
[root@CentOS7 ~]# nginx -s stop      停止服务
[root@CentOS7 ~]# nginx -s reload    加载配置文件
[root@CentOS7 ~]# nginx              开启服务

修改并发数

[root@CentOS7 /usr/local/src]# ulimit -n 65535    临时修改
[root@CentOS7 /usr/local/src]# vim /etc/security/limits.conf
*                -        nofile         65535  
[root@CentOS7 /usr/local/src]# vim /etc/nginx/nginx.conf
worker_rlimit_nofile number 65535     所有worker进程能打开的文件数量上限,

events {
     
    worker_connections 10240;      每个worker进程所能够打开的最大并发连接数
}

default_type

[root@CentOS7 ~]# vim /etc/nginx/nginx.conf
    include             /etc/nginx/mime.types;         #支持文档格式
    default_type        application/octet-stream;      不支持的格式默认为下载,若不写默认为text/plain
[root@CentOS7 ~]# cat /etc/nginx/mime.types

types {
     
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
}

[root@CentOS7 ~]# curl -I 192.168.8.7/test.xyz
Content-Type: application/octet-stream          不能识别

#    default_type        application/octet-stream; 
[root@CentOS7 ~]# curl -I 192.168.8.7/test.xyz      注销后默认为text/plain
Content-Type: text/plain


    include             /etc/nginx/mime.types;
#    default_type        application/octet-stream;
    default_type        text/html;                      修改默认
[root@CentOS7 ~]# curl -I 192.168.8.7/test.xyz
Content-Type: text/html

配置虚拟主机
[root@nginx ~]# mkdir /data/site{1,2}
[root@nginx ~]# echo /data/site1/index.html > /data/site1/index.html
[root@nginx ~]# echo /data/site2/index.html > /data/site2/index.html
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen      80;
        server_name www.magedu.com;
        root        /data/site1;
}

server {
     
        listen      80;
        server_name www.magedu.org;
        root        /data/site2;                                                                                                                                   
}
    
[root@nginx ~]# nginx -s reload


[root@CentOS7 ~]# curl http://www.magedu.com
/data/site1/index.html
[root@CentOS7 ~]# curl http://www.magedu.org
/data/site2/index.html

[root@client ~]# curl 192.168.8.7           默认访问路径
welcome to magedu

修改默认访问路径
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen      80 default_server;           新增 default_server                                                                                                                        
        server_name www.magedu.com;
        root        /data/site1; 
}
[root@nginx ~]# vim /etc/nginx/nginx.conf
    server {
     
        listen       80 ;                    删除default_server

[root@client ~]# curl 192.168.8.7
/data/site1/index.html


[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen      80 default_server;
        server_name www.magedu.com www.magedu.net;        添加多个域名                                                                                                              
        root        /data/site1;
}
[root@client ~]# curl http://www.magedu.net
/data/site1/index.html
[root@client ~]# curl http://www.magedu.com
/data/site1/index.html



  • 支持通配符、正则表达式
  • 匹配优先级机制从高到低
    • (1) 首先是字符串精确匹配 如:www.magedu.com
    • (2) 左侧通配符 如:.magedu.com
    • (3) 右侧通配符 如:www.magedu.
    • (4) 正则表达式 如: ~^.*.magedu.com$
    • (5) default_server
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen      80 default_server;
        server_name *.magedu.net;                                                                                                                                  
        root        /data/site1;
}

server {
     
        listen      80;
        server_name ~^.*\.magedu\.net$;
        root        /data/site2;
}
[root@client ~]# curl http://www.magedu.net      优先访问通配符
/data/site1/index.html

location
实验:基于location实现特定网页访问特定地址
  • root
  • 指定虚拟主机根目录,在定义location时,文件的绝对路径等于 root+location,示例:
[root@nginx ~]# echo /opt/tvim /etc/nginx/conf.d/test.conf
server {
     
        listen      80 default_server;
        server_name *.magedu.net;
        root        /data/site1;
        location    /test {
     
                root    /opt/testdir;                                                                                                                              
        }

}
[root@nginx ~]# mkdir /opt/testdir/test/ -p
[root@nginx ~]# echo /opt/testdir/test/index.html >/opt/testdir/test/index.html
[root@client ~]# curl http://www.magedu.net/test/       访问test目录时访问特定路径
/opt/testdir/test/index.html
[root@client ~]# curl http://www.magedu.net/
/data/site1/index.html

  • = 对URI做精确匹配;
    location = / {

    }
    http://www.magedu.com/ 匹配
    http://www.magedu.com/index.html 不匹配
  • ^~ 对URI的最左边部分做匹配检查,不区分字符大小写
  • ~ 对URI做正则表达式模式匹配,区分字符大小写
  • ~* 对URI做正则表达式模式匹配,不区分字符大小写
  • 不带符号 匹配起始于此uri的所有的uri
  • \ 转义符,可将 . * ?等转义为普通符号
  • 匹配优先级从高到低:
    • =, ^~, ~/~*, 不带符号

alias

  • 路径别名,文档映射的另一种机制;仅能用于location上下文
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen      80 default_server;
        server_name *.magedu.net;
        root        /data/site1;
        location  /test/ {
     
                root    /opt/testdir/;
        }

        location  /ab {
                        注意:/ab后建议不要加/                                                                                            
                alias   /opt/testdir/;
        }
}


[root@CentOS7 ~]# curl www.magedu.net/test/
/opt/testdir/test/index.html
[root@CentOS7 ~]# curl www.magedu.net/ab/
/opt/testdir/index.html

注意:location中使用root指令和alias指令的意义不同
(a) root,给定的路径对应于location中的/uri 左侧的/
(b) alias,给定的路径对应于location中的/uri 的完整路径

实验:基于location实现页面动静分离处理
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen      80 default_server;
        server_name *.magedu.net;
        root        /data/site1;
        location  ~* \.(jpg|gif|html|txt|js|css)$ {
     
                root    /opt/static;
        }

        location  ~* \.(php|jsp|asp)$ {
     
                root    /opt/dynamic;
        }
}

[root@nginx ~]# mkdir /opt/static
[root@nginx ~]# mkdir /opt/dynamic
[root@nginx ~]# echo jpg >/opt/static/a.jpg
[root@nginx ~]# echo php >/opt/dynamic/a.php    

[root@CentOS7 ~]# curl www.magedu.net/a.jpg
jpg
[root@CentOS7 ~]# curl www.magedu.net/a.php
php  

动态页面利用代理访问后端服务器

实验:实现错误页面跳转至自定义错误页面或返回定义状态码
[root@CentOS7 ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        server_name  www.magedu.net;
                root /data/nginx/;

        error_page 404 /40x.html;
                location = /40x.html {
     
                        root /data/nginx;                                                                                 
                }

       error_page 500 502 503 504 /50x.html;
               location = /50x.html {
     
                       root /data/nginx;
               }
}
[root@CentOS7 ~]# mkdir /data/nginx
[root@CentOS7 ~]# echo 401 >/data/nginx/40x.html
[root@CentOS7 ~]# echo 501 >/data/nginx/50x.html

访问错误页面时返回/data/nginx40x.html内容401


实验:实现basic验证(访问控制)
[root@nginx ~]# yum install httpd-tools
[root@nginx ~]# htpasswd -b -c /data/nginx/.ngxpasswd alice centos
[root@nginx ~]# htpasswd -b  /data/nginx/.ngxpasswd bob centos

[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        server_name  www.magedu.net;
                root /data/nginx/;
        allow 192.168.8.1;
        allow 192.168.8.27;
        deny all;
        location /admin {
                                                                                                      
                auth_basic "Admin Area";
                auth_basic_user_file /data/nginx/.ngxpasswd;
        }
}
只允许192.168.8.1、27访问www.magedu.net/admin且需要输入用户密码验证登录

实验:实现下载功能
server {
     
        server_name  www.magedu.net;
            root /data/nginx/;
                
		location /download {
     
			autoindex on;                     自动文件索引
			autoindex_exact_size off;
			autoindex_localtime on;
			autoindex_format html;            可以不写,默认html
			limit_rate 100k;
			root /data/nginx/download;
			index index.html;
		}
}

实验:location if实现HTTP跳转https
[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 

server {
     `在这里插入代码片`
        listen 443 ssl;
        listen 80;                                                                                                                 
        server_name  www.magedu.net;
                root /data/nginx/;

        if ( $scheme = http ) {
                                 跳转
                return 301 https://www.magedu.net/;
        }
        ssl_certificate /etc/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;



如果浏览器是curl拒绝访问

[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 443 ssl;
        listen 80;
        server_name  www.magedu.net;
                root /data/nginx/;

#        if ( $scheme = http ) {
     
 #               return 301 https://www.magedu.net/;
  #      }
        if ( $http_user_agent ~ curl ){
     
                return 405 "deny curl";                                                                                            
        }
        ssl_certificate /etc/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;



[root@CentOS7 ~]# curl -A IE  http://www.magedu.net    IE可以
192.168.8.17
[root@CentOS7 ~]# curl   http://www.magedu.net     拒绝访问
deny curl
实验:log模块实现日志及json格式日志
[root@nginx ~]# vim /etc/nginx/nginx.conf
http {
                             http模块自定义日志,原日志下方新增
    log_format compression '$remote_addr-$remote_user [$time_local] '
                           '"$request" $status $bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';
   
    access_log /data/logs/nginx-access.log compression; 
    

实现json格式日志

[root@nginx ~]# vim /etc/nginx/nginx.conf
http {
                             http模块自定义日志,原日志下方新增
    log_format access_json '{"@timestamp":"$time_iso8601",'
                           '"host":"$server_addr",'
                           '"clientip":"$remote_addr",'
                           '"size":$body_bytes_sent,'
                           '"responsetime":$request_time,'
                           '"upstreamtime":"$upstream_response_time",'
                           '"upstreamhost":"$upstream_addr",'
                           '"http_host":"$host",'
                           '"uri":"$uri",'
                           '"domain":"$host",'
                           '"xff":"$http_x_forwarded_for",'
                           '"referer":"$http_referer",'
                           '"tcp_xff":"$proxy_protocol_addr",'
                           '"http_user_agent":"$http_user_agent",'
                           '"status":"$status"}';
    access_log /data/logs/access_json.log access_json;

}

[root@nginx ~]# tail -f /data/logs/access_json.log   查看日志

Python代码统计json格式日志信息

#cat nginx_json.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
for line in f.readlines():
line = eval(line)
if line.get("status") == "200":
status_200.append(line.get)
elif line.get("status") == "404":
status_404.append(line.get)
else:
print("状态码 ERROR")
f.close()
print "状态码200的有--:",len(status_200)
print "状态码404的有--:",len(status_404)
# python nginx_json.py
状态码200的有--: 1910
状态码404的有--: 13
实验:实现zip压缩功能
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        server_name  www.magedu.net;
                root /data/nginx/;
        gzip on;
        gzip_comp_level 9;       压缩比9                                                                                                                              
        gzip_min_length 64;      64k开启压缩
        gzip_vary on;            响应头插入信息
        gzip_types text/xml text/css application/javascript;     哪些格式压缩


[root@CentOS7 ~]# curl -I --compressed www.magedu.net/access.css
HTTP/1.1 200 OK
Content-Type: text/css            文件格式
Vary: Accept-Encoding             响应报文插入信息
Content-Encoding: gzip            压缩


[root@nginx ~]# vim /etc/ngtail -f /data/logs/access_json.log    json格式日志
{
     "@timestamp":"2020-08-07T22:18:18+08:00","host":"192.168.8.17","clientip":"192.168.8.1","size":761392,"    下载文件大小比原文件小(原文件9M)
实验:实现ssl加密传输(https)
[root@nginx ~]# cd /etc/pki/tls/certs/
[root@nginx /etc/pki/tls/certs]# make magedu.net.key    需要输入密码,可以修改一下不输密码
[root@nginx /etc/pki/tls/certs]# vim Makefile
#        /usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@
         /usr/bin/openssl genrsa $(KEYLEN) > $@
[root@nginx /etc/pki/tls/certs]# make magedu.net.key       不需验证密码
[root@nginx /etc/pki/tls/certs]# make magedu.net.crt
[root@nginx /etc/pki/tls/certs]# mkdir /etc/nginx/ssl
[root@nginx /etc/pki/tls/certs]# mv magedu.net.* /etc/nginx/ssl/
[root@nginx /etc/pki/tls/certs]# chmod 600 /etc/nginx/ssl/*
[root@nginx /etc/pki/tls/certs]# ll /etc/nginx/ssl/
-rw------- 1 root root 1322 Aug  7 22:55 magedu.net.crt
-rw------- 1 root root 1675 Aug  7 22:54 magedu.net.key

[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 
server {
     
        listen 443 ssl;
        server_name  www.magedu.net;
                root /data/nginx/;
        ssl_certificate /etc/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /etc/nginx/ssl/magedu.net.key;                                                                         
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
}

访问https://www.magedu.net
实验:rewrite模块实现跳转

http跳转至https

一般常用此方法跳转

server {
     
        listen 443 ssl;
        listen 80;
        server_name  www.magedu.net;
                root /data/nginx/;
#       location / {                              location不写也可以实现
                if ( $scheme = http ) {
     
                        rewrite / https://www.magedu.net/ redirect;
                }
#       }     

跳转至其他网页

  • break:匹配成功后不再向下匹配,也不会跳转到其他的location,即直接结束匹配并给客户端返回结果数据
  • last:对某个location的URL匹配成功后会停止当前location的后续rewrite规则,并结束当前location,然后将匹配生成的新URL跳转至其他location继续匹配,直到没有location可匹配后将最后一次location的数据返回给客户端

last

[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 443 ssl;
        listen 80;
        server_name  www.magedu.net;
                root /data/nginx/;
        location /test1 {
                                                                                                               
                rewrite ^/test1/(.*)$ /test2/$1  last;    一直跳
        }

        location /test2 {
     
                rewrite ^/test2/(.*)$ /test1/$1  last;
        }

[root@CentOS7 ~]# curl -I www.magedu.net/test1/     500错误,服务器内部跳转
HTTP/1.1 500 Internal Server Error

break

[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 443 ssl;
        listen 80;
        server_name  www.magedu.net;
                root /data/nginx/;
        location /test1 {
     
                rewrite ^/test1/(.*)$ /test2/$1  break;
        }

        location /test2 {
     
                rewrite ^/test2/(.*)$ /test1/$1  break; 

[root@CentOS7 ~]# curl -I  -L www.magedu.com/test1/
HTTP/1.1 301 Moved Permanently      跳转一次中断
 
HTTP/1.1 404 Not Found              服务器无文件

[root@nginx /etc/pki/tls/certs]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 443 ssl;
        listen 80;
        server_name  www.magedu.net;
                root /data/nginx/;
        location /test1 {
     
                rewrite ^/test1/(.*)$ /test2/$1  last; last也可换成permanent   永久重定向 
        }
访问http://www.magedu.net/test1/实际访问/data/nginx/test2

[root@CentOS7 ~]# curl -L www.magedu.net/test1/
test

实验:实现状态页status
server {
     
        server_name  www.magedu.net;
                root /data/nginx/;
        location /admin {
                              用户认证
                auth_basic "Admin Area";
                auth_basic_user_file /data/nginx/.ngxpasswd;
        }
        location /nginx_status {
                   状态页
        stub_status;
        allow 192.168.8.0/24;                                                                                             
        deny all;
        }

访问http://www.magedu.net/nginx_status/

实验:实现错误页面跳转至首页
server {
     
        listen 80;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                if ( !-f $request_filename ) {
     
                rewrite ^/(.*)$ http://www.magedu.net/index.html;                                                                  
                }
        }

[root@CentOS7 ~]# curl -L www.magedu.net/inex.html
192.168.8.17
[root@CentOS7 ~]# curl -L www.magedu.net/ine
192.168.8.17


实验:实现第三方模块echo及打印变量

编译安装

#yum install git –y
#cd /usr/local/src
#git clone https://github.com/openresty/echo-nginx-module.git
#cd nginx-1.16.0/
#useradd –r –s /sbin/nologin nginx
#yum install gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
# ./configure \
--prefix=/apps/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_perl_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--add-module=/usr/local/src/echo-nginx-module
# make && make install

配置

[root@CentOS7 /app/nginx]# vim conf/nginx.conf      在server下面配置
        location /echo {
     
                echo hello;
        }
[root@CentOS7 /app/nginx]# curl 127.0.0.1/echo
hello
[root@CentOS7 /app/nginx]# vim conf/nginx.conf
        location /echo {
     
                echo hello;
        }
        location /test {
     
        index index.html;
        default_type text/html;
        echo "hello world,main-->";
        echo_reset_timer;
        echo_location /sub1;
        echo_location /sub2;
        echo "took $echo_timer_elapsed sec for total.";
        }
        location /sub1 {
     
        echo_sleep 1;
        echo sub1;
        }
        location /sub2 {
     
        echo_sleep 1;
        echo sub2;
        }
[root@CentOS7 /app/nginx]# curl 127.0.0.1/test      访问结果
hello world,main--> 
sub1
sub2
took 2.004 sec for total.

备注:若要在/app/nginx/conf/conf.d/test.conf下面配置,需要在/app/nginx/nginx.conf配置
   include /app/nginx/conf/conf.d/*.conf;          http模块下添加

自定义变量

[root@CentOS7 /app/nginx]# vim conf/nginx.conf
        location /echo {
     
        set $name magedu;
        echo $name;
        }

[root@CentOS7 /app/nginx]# curl 192.168.8.7/echo
magedu

实验:防止盗链
*.magedu.com magedu.* *.mageedu.com mageedu.* ~\.magedu\. ~\.google\. ~\.baidu\.;
if ($invalid_referer) {
     
return 403 "Forbidden Access";
}
实验:proxy实现反向代理(同构代理)

总结:高性能web服务器Nginx_第1张图片

[root@apache ~]# rpm -q httpd
httpd-2.4.6-93.el7.centos.x86_64
[root@apache ~]# systemctl start httpd
[root@apache ~]# echo apache >/var/www/html/index.html
[root@client ~]# curl 192.168.8.27
apache

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen 80;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                proxy_pass http://192.168.8.27;            后面不能加/                                                                            
        }

}
[root@client ~]# curl www.magedu.net    访问后台服务器
apache
[root@apache ~]# cat /var/log/httpd/access_log    后台服务器不知谁在访问
192.168.8.17 - - [08/Aug/2020:00:28:54 +0800] "GET / HTTP/1.0" 200 7 "-" "curl/7.29.0"


设定转发往后端主机的请求报文的请求首部的值

前面实验不能实现后端服务器查看客户端IP,不方便分析日志;若要使后端服务器能识别客户端IP,需要添加以下语句

  • 中间只有一个代理服务器
[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen 80;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                proxy_pass http://192.168.8.27;            后面不能加/  
                proxy_set_header X-Real-IP $remote_addr;                                                                          
        }

}
在后端web服务器设置日志格式
Apache "\"%{X-Real-IP}i\""

  • 中间有多层代理服务器
    后端是NGINX需使用此配置
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   新增

在后端web服务器设置日志格式
Apache %{
     X-Forwarded-For}i
nginx   $http_x_forwarded_for     默认不需配置

请求报文的标准格式如下:
X-Forwarded-For: client1, proxy1, proxy2
X-Forwarded-For为变量名称,可以随意取

实验:开启缓存功能
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf     定义缓存
http {
     
·····
    proxy_cache_path /var/cache/nginx/proxy_cache    新增
    levels=1:2:2 keys_zone=proxycache:20m
    inactive=120s max_size=1g;
····
}

[root@nginxproxy ~]# vim /etc/nginx//conf.d/test.conf      调用缓存配置
server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        proxy_cache proxycache;          新增
        proxy_cache_key $request_uri;        用url缓存依据
        proxy_cache_valid 200 302 301 1h;    缓存时长
        proxy_cache_valid any 1m;            其他1分钟                                                                                                                                            

        location / {
     
               proxy_pass http://192.168.8.27;
               proxy_set_header X-Real-IP $remote_addr;
        }

}

[root@nginxproxy ~]# mkdir /var/cache/nginx      
[root@nginxproxy ~]# curl http://www.magedu.net
192.168.8.27
 
[root@nginxproxy ~]# tree /var/cache/nginx/     访问后查看缓存
/var/cache/nginx/
└── proxy_cache
    └── 9
        └── 7d
            └── cc
                └── 6666cd76f96956469e7be39d750cc7d9
                            
实验:隐藏后端服务器特定的响应首部
[root@client ~]# curl -I http://www.magedu.net
HTTP/1.1 200 OK
Server: nginx/1.16.1
ETag: "5f2f4ef9-d"          可以隐藏
Accept-Ranges: bytes

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        proxy_hide_header Etag;                                                                                                                                                           
}

[root@client ~]# curl -I http://www.magedu.net   再次访问没有

自定义返回头部,查看缓存命中率

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 1h;
        proxy_cache_valid any 1m;
        proxy_hide_header Etag;
        add_header X-Cache $upstream_cache_status;                                                                                                                                        
        location / {
     
               proxy_pass http://192.168.8.27;
               proxy_set_header X-Real-IP $remote_addr;
        }

}

[root@client ~]# curl -I http://www.magedu.net
X-Cache: MISS               第一次没有

[root@client ~]# curl -I http://www.magedu.net
X-Cache: HIT               第二次查看缓存

实验:实现反向代理(异构代理)

总结:高性能web服务器Nginx_第2张图片

[root@nginxproxy ~]# yum install php-fpm php-mysql

[root@nginxproxy ~]# vim /etc/php-fpm.d/www.conf 
user = nginx                                                                                                                                       
group = nginx

[root@nginxproxy ~]# systemctl start php-fpm
[root@nginxproxy ~]# mkdir /data/php
[root@nginxproxy ~]# vim /data/php/test.php
<?php
phpinfo()                                                                                                                                                                                 
?>

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf
server {
     
        listen 80 default_server;
        server_name  www.magedu.net;                                                                                                                                                      
        root /data/nginx/;
        location ~* \.php$ {
     
                root /data/php;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                #fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
                include fastcgi_params;
        }
第一种方法;
第二种写法:
 fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;   直接把root写入
www.magedu.net/test.php测试


[root@mariadb ~]# yum install mariadb-server
[root@mariadb ~]# systemctl start mariadb
[root@mariadb ~]# mysql -e "create database wordpress;grant all on wordpress.* to wordpress@'192.168.8.%' identified by 'centos'"


[root@nginxproxy ~]# tar xf wordpress-5.0.4-zh_CN.tar.gz -C /data/php
[root@nginxproxy ~]# chown -R nginx.nginx /data/php/wordpress
[root@nginxproxy ~]# cd /data/php/wordpress/
[root@nginxproxy /data/php/wordpress]# cp wp-config-sample.php wp-config.php
[root@nginxproxy /data/php/wordpress]# vim wp-config.php
define('DB_NAME', 'wordpress');
define('DB_USER', 'wordpress');
define('DB_PASSWORD', 'centos');
define('DB_HOST', '192.168.8.37');  
[root@nginxproxy /data/php/wordpress]# cp /data/php/wordpress /data/nginx/wordpress -av
[root@nginxproxy /data/php/wordpress]# cd /data/nginx
[root@nginxproxy /data/nginx]# find /data/nginx/ -type f -name "*.php" -delete


[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;                     默认访问
        proxy_cache proxycache;                缓存
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 1h;
        proxy_cache_valid any 1m;
        proxy_hide_header Etag;
        add_header X-Cache $upstream_cache_status;
        location ~* \.php$ {
                                 代理
                root /data/php;
                index index.php
                default_type html/text;                                                                                                                                                   
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                #fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
                include fastcgi_params;
        }
}

图像上传不上

显示php-fpm状态

[root@nginxproxy /data/php/wordpress]# vim /etc/php-fpm.d/www.conf 
pm.status_path = /fpm_status
ping.path = /ping 
[root@nginxproxy /data/php/wordpress]# systemctl restart php-fpm

[root@nginxproxy /data/php/wordpress]# vim /etc/nginx/conf.d/test.conf 

server {
     

        location ~* ^/(fpm_status|ping)$ {
                                                                                                                                                                           
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        include fastcgi_params;
        }

支持多种格式访问
http://www.magedu.net/fpm_status?full
http://www.magedu.net/fpm_status?json
http://www.magedu.net/fpm_status?xml
http://www.magedu.net/fpm_status?html
实验:实现反向代理(异构代理跨主机)

第二种方法实现
总结:高性能web服务器Nginx_第3张图片
利用清华源安装最新版
https://mirrors.tuna.tsinghua.edu.cn/remi进入复制remi-release-7.rpm链接

php服务器设置

[root@web ~]# wget https://mirrors.tuna.tsinghua.edu.cn/remi/enterprise/remi-release-7.rpm
[root@web ~]# vim /etc/yum.repos.d/remi-php73.repo
[root@web ~]# vim /etc/yum.repos.d/remi-php73.repo 
[root@web ~]# yum list php73*
[root@web ~]# yum install php73-php-fpm php73-php-mysqlnd -y
[remi-php73]
enabled=1             启用
[root@web ~]# rpm -ql php73-php-fpm 
/etc/opt/remi/php73/php-fpm.conf
/etc/opt/remi/php73/php-fpm.d/www.conf
/etc/systemd/system/php73-php-fpm.service.d
[root@web ~]# getent passwd nginx       若没有需创建,uid与gid与前端服务器一直
nginx:x:987:981:Nginx web server:/var/lib/nginx:/sbin/nologin

[root@web ~]# vim /etc/opt/remi/php73/php-fpm.d/www.conf 
listen = 192.168.8.27:9000  
user = nginx
group = ngin
;listen.allowed_clients = 127.0.0.1      注释掉

 
[root@web ~]# mkdir /data/php
[root@web ~]# unzip wordpress-5.4.2.zip.zip 
[root@web ~]# mv wordpress /data/php/
[root@web ~]# setfacl -Rm u:nginx:rwx /data/php/wordpress
[root@web /data/php/wordpress]# cp wp-config-sample.php wp-config.php 
[root@web /data/php/wordpress]# vim wp-config.php 
define( 'DB_NAME', 'wordpress' );
define( 'DB_USER', 'wordpress' );
define( 'DB_PASSWORD', 'centos' );
define( 'DB_HOST', '192.168.8.37' );                                                                                                                                                                            
[root@web /data/php/wordpress]# systemctl start php73-php-fpm.service 
    mariadb数据库服务器不修改


[root@nginxproxy /data/php/wordpress]# systemctl stop php-fpm      停止本机php-fpm
[root@nginxproxy /data/php/wordpress]# nginx -s reload
[root@nginxproxy /data/php/wordpress]# vim /etc/nginx/conf.d/test.conf 
        location ~* \.php$ {
     
#               root /data/php;
                index index.php
                default_type html/text;
                fastcgi_pass 192.168.8.27:9000;                                                                                                                                                                 
                fastcgi_index index.php;
#               fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
                include fastcgi_params;
        }

访问http://www.magedu.net/wordpress/wp-admin/index.php 提示要更新证明已经调至后面最新的服务器

实验:fastcgi配置缓存
[root@nginxproxy /data/php/wordpress]# vim /etc/nginx/nginx.conf

http {
     
    fastcgi_cache_path /var/cache/nginx/fcgi_cache 
    levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf 
        location ~* \.php$ {
     
#               root /data/php;
                fastcgi_cache fcgicache;
                fastcgi_cache_key $request_uri;
                fastcgi_cache_valid 200 302 10m;
                fastcgi_cache_valid 301 1h;
                fastcgi_cache_valid any 1m;      
                fastcgi_pass 192.168.8.27:9000;
                fastcgi_index index.php;
#               fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name;
                include fastcgi_params;

[root@nginxproxy ~]# tree /var/cache/nginx/
/var/cache/nginx/
├── fcgi_cache
│   ├── 0
│   │   └── c7
│   │       └── 8
│   │           └── 710ec74b5725f25407ddd0c210758c70
│   ├── 6
│   │   └── a7
│   │       └── f
│   │           └── efe3ef7f50f0528d1f3948468d08fa76


[root@client ~]# ab -c100 -n 1000 www.magedu.net/wp-admin/index.php    测试
由于缓存为静态页面,处理速度大大提升
实验:实现调度功能

前面的代理实验实现往一台服务器上发送,没有实现多台调度

[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
http {
     
······
    upstream websrvs {
     
        server 192.168.8.107:80;                                                                                                                                                                                
        server 192.168.8.117:80;
    }

[root@nginxproxy ~]# vim /etc/nginx/conf.d/test.conf 
server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                proxy_pass http://websrvs;            修改
        }

[root@client ~]# curl www.magedu.net
192.168.8.107web1
[root@client ~]# curl www.magedu.net
192.168.8.117web2
后端服务器192.168.8.107、117配置不述

加权重

[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80 weight=3;                                                                                                                                                                       
        server 192.168.8.117:80;
    }

[root@client ~]# curl www.magedu.net
192.168.8.107web1
[root@client ~]# curl www.magedu.net
192.168.8.107web1
[root@client ~]# curl www.magedu.net
192.168.8.107web1
[root@client ~]# curl www.magedu.net
192.168.8.117web2


灰度发布

[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80 down;                                                                                                                                                                       
        server 192.168.8.117:80;
    }

[root@client ~]# curl www.magedu.net
192.168.8.117web2
[root@client ~]# curl www.magedu.net
192.168.8.117web2

加down后不会往该服务器调度,可以用于软件升级,升级上线后没问题再升级其他服务器

实现sorryserver
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;             80端口代理占用                                                                                                                                                                 
    }
    server {
     
        listen       8080;   
        server_name  _;
        root         /usr/share/nginx/html;
[root@nginxproxy ~]# echo sorrysever >/usr/share/nginx/html/index.html

LVS可以实现百万链接,而nginx只能实现三万多链接,因此,工作中一般LVS作为前端调度,nginx作为后端调度

调度算法

调度算法:默认wrr

  • ip_hash 源地址hash调度方法 (相当于sh,同一个IP发往同一个服务器)
  • least_conn 最少连接调度算法,当server拥有不同的权重时其为wlc,当所有后端主机连接数相同时,则使用wrr,适用于长连接
  • hash key [consistent] 基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者组合
    作用:将请求分类,同一类请求将发往同一个upstream server,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用
    hash $request_uri consistent; (URL调度)
    hash $remote_addr; (IP调度)
    hash $cookie_name; #key为name的cookie (cookie调度)
  • keepalive 连接数N;
    为每个worker进程保留的空闲的长连接数量,可节约nginx端口,并减少连接管理的消耗
ip_hash
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;             80端口代理占用 
        ip_hash;                                                                                                                                                                
    }
[root@client ~]# while : ;do curl www.magedu.net ;sleep 0.5 ;done
192.168.8.117web2
192.168.8.117web2
全往117上调
hash $request_uri
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;             80端口代理占用 
        hash $request_uri ;                                                                                                                                                                
    }

[root@web1 ~]# for i in {1..10};do echo 192.168.8.107$i > /var/www/html/test$i ;done
[root@web2 ~]# for i in {1..10};do echo 192.168.8.117$i > /var/www/html/test$i ;done
[root@client ~]# curl www.magedu.net/test1
192.168.8.1071
[root@client ~]# curl www.magedu.net/test2
192.168.8.1172

根据URL调度
hash $cookie
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;
        hash $cookie_user;   

[root@client ~]# curl -b user=wang www.magedu.net      根据user进行调度
192.168.8.117web2
[root@client ~]# curl -b user=wa www.magedu.net
192.168.8.107web1


当有权重时,根据URL调度会出现问题
总结:高性能web服务器Nginx_第4张图片

  • 当访问一个URL时,对URL进行hash取hash值,对所有权重之和取模,但当需要新增一台varnish服务器时,由于权重之和变化,会导致所有varnish服务器缓存失效;因此不能使用

一致性hash算法

总结:高性能web服务器Nginx_第5张图片

  • 一致性hash算法不再对权重之和取模,而是对2^32取模(0 -2^32-1)
  • varnish对IP进行hash运算,当权重增加时,IP加上随机数进行hash运算,对2^32进行取模,得出一个值,当URL得出的值顺时针方向越接近哪个值,就发往拥有该值的varnish服务器
  • 但当值太小时容易出现所有都往一个varnish调度,因此,工作中常常将权重乘以10000或10000,以扩大范围
[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;             80端口代理占用 
        hash $request_uri consistent;           适用于后端为缓存服务器                                                                                                                                                         
    }
实验:实验nginx四层反向代理(工作中一般不使用)
[root@web1 ~]# yum install mariadb-server -y
[root@web1 ~]# systemctl start mariadb
[root@web1 ~]# mysql -e "create database db107"
[root@web1 ~]# mysql -e "grant all on *.* to test@'192.168.8.%' identified by 'centos'"

[root@web2 ~]# yum install mariadb-server -y
[root@web2 ~]# systemctl start mariadb
[root@web2 ~]# mysql -e "create database db117"
[root@web2 ~]# mysql -e "grant all on *.* to test@'192.168.8.%' identified by 'centos'"

[root@nginxproxy ~]# vim /etc/nginx/nginx.conf
stream {
                                        于http属于同级
    upstream mysqlsrvs {
     
        server 192.168.8.107:3306;
        server 192.168.8.117:3306;
    }
    server {
     
        listen 192.168.8.17:3306;                                                                                                                                                                               
        proxy_pass mysqlsrvs;
	}
}
[root@nginxproxy ~]# nginx -s reload

[root@client ~]# mysql -utest -pcentos -h 192.168.8.17 -e "show databases;"
+--------------------+
| Database           |
+--------------------+
| db107              |
+--------------------+
[root@client ~]# mysql -utest -pcentos -h 192.168.8.17 -e "show databases;"
+--------------------+
| Database           |
+--------------------+
| db117              |
+--------------------+

调度向不同的服务器

编译tengine
[root@nginxproxy ~]# yum install gcc pcre-devel openssl-devel zlib-devel -y
[root@nginxproxy ~]# wget http://tengine.taobao.org/download/tengine-2.1.2.tar.gz
[root@nginxproxy ~]# tar xf tengine-2.1.2.tar.gz
[root@nginxproxy ~]# cd tengine-2.1.2/
[root@nginxproxy ~]# ./configure --prefix=/apps/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_concat_module=shared            share模块(编译后可以把该模块cp到同版本的服务器配置即可)
[root@nginxproxy ~/tengine-2.1.2]# cd /apps/nginx/
[root@nginxproxy /apps/nginx]# ls modules/
ngx_http_concat_module.so


keepalived实现nginx高可用

总结:高性能web服务器Nginx_第6张图片

配置keepalived的IP浮动

[root@nginxproxy-master ~]# yum install keepalived.x86_64 -y
[root@nginxproxy-master ~]# rpm -ql keepalived 
/etc/keepalived/keepalived.conf
[root@nginxproxy-master ~]# ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa
[root@nginxproxy-master ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub 127.0.0.1
[root@nginxproxy-master ~]# scp -r /root/.ssh 192.168.8.27:/root

[root@nginxproxy-master ~]# vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
     
   notification_email {
     
     root@localhost
   }
   notification_email_from keepa;ived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id ka1
   vrrp_mcast_group4 224.100.100.100     不写默认224.0.0.18
}

vrrp_instance VI_1 {
     
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
     
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
     
        192.168.8.100/24 dev ens33 label ens33:1                                                                                                                                                                
    }
}

[root@nginxproxy-slave ~]# yum install keepalived.x86_64 -y
[root@nginxproxy-master ~]# scp -r /etc/keepalived/keepalived.conf 192.168.8.27:/etc/keepalived/

[root@nginxproxy-slave ~]# vim /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {
     
   notification_email {
     
     root@localhost
   }
   notification_email_from keepa;ived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id ka2                                       修改
   vrrp_mcast_group4 224.100.100.100
}

vrrp_instance VI_1 {
     
    state BACKUP                                       修改                  
    interface ens33
    virtual_router_id 51
    priority 80                                        修改                                                                                                                                                                                                
    advert_int 1
    authentication {
     
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
     
        192.168.8.100/24 dev ens33 label ens33:1
    }
}

[root@nginxproxy-master ~]# systemctl start keepalived.service
[root@nginxproxy-slave ~]# systemctl start keepalived.service


配置代理

[root@nginxproxy-master ~]# vim /etc/nginx/nginx.conf
http {
     

    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;
    }  
[root@nginxproxy-master ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                proxy_pass http://websrvs;
        }
}  


[root@nginxproxy-slave ~]# vim /etc/nginx/nginx.conf
http {
     

    upstream websrvs {
     
        server 192.168.8.107:80;
        server 192.168.8.117:80;
        server 127.0.0.1:8080  backup;
    }  
[root@nginxproxy-slave ~]# vim /etc/nginx/conf.d/test.conf 

server {
     
        listen 80 default_server;
        server_name  www.magedu.net;
        root /data/nginx/;
        location / {
     
                proxy_pass http://websrvs;
        }
}  

客户端配置及访问

[root@client ~]# vim /etc/hosts
192.168.8.100 www.magedu.net  
[root@client ~]# while : ;do  curl www.magedu.net ;sleep 0.5 ;done
192.168.8.117web2
192.168.8.107web1

以上配置基本满足要求,但nginx服务停止不能解决,会导致调度失败,可以配合脚本来实现

实验:脚本实现nginxproxy进程监控

master上配置

[root@nginxproxy-master ~]# vim /etc/keepalived/test.sh
[[ -f /etc/keepalived/down ]] && exit 1 || exit 0     存在即返回1
[root@nginxproxy-master ~]# chmod +x /etc/keepalived/test.sh

[root@nginxproxy-master ~]# vim /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {
     
   notification_email {
     
     root@localhost
   }
   notification_email_from keepa;ived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id ka1
   vrrp_mcast_group4 224.100.100.100
}

vrrp_script chk_down {
                                              新增脚本
    script "/etc/keepalived/test.sh"           测试脚本
    interval 1                            间隔多久测试一次(1s)
    weight -30                                权重减30(减去后要小于slave权重)
}

vrrp_instance VI_1 {
     
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
     
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
     
        192.168.8.100/24 dev ens33 label ens33:1
    }
    track_script {
                                          新增实例调用脚本
        chk_down
}

实验nginx进程监控

[root@CentOS7 ~]# vim /etc/keepalived/check_nginx.sh
killall -0 nginx &>/dev/null || exit 1 
[root@CentOS7 ~]# chmod +x /etc/keepalived/check_nginx.sh


[root@CentOS7 ~]# vim /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {
     
   notification_email {
     
     root@localhost
   }
   notification_email_from keepa;ived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id ka1
   vrrp_mcast_group4 224.100.100.100
}

vrrp_script chk_nginx {
     
    script "/etc/keepalived/check_nginx.sh"
    interval 1
    weight -30
}
vrrp_instance VI_1 {
     
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
     
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
     
        192.168.8.100/24 dev ens33 label ens33:1
    }
    track_script {
     
        chk_nginx                                                                                                                                                                                               
    }
}

slave服务器是没有配置监控的,可以配

实验:实现nginx进制停止后重启
[root@CentOS7 /etc/keepalived]# vim /etc/keepalived/notify.sh      邮件脚本
contact='root@localhost'
notify() {
     
mailsubject="$(hostname) to be $1, vip floating"
mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
echo "$mailbody" | mail -s "$mailsubject" $contact
}
case $1 in
master)
        notify master
        ;;
backup)
        notify backup
        nginx                              新增重启进程                                                                                                                                                                            
        ;; 
fault)
        notify fault
        ;;
*)
        echo "Usage: $(basename $0) {master|backup|fault}"
        exit 1
        ;;
esac
[root@CentOS7 /etc/keepalived]# chmod +x notify.sh 
[root@CentOS7 /etc/keepalived]# vim keepalived.conf 
! Configuration File for keepalived

global_defs {
     
   notification_email {
     
     root@localhost
   }
   notification_email_from keepa;ived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id ka1
   vrrp_mcast_group4 224.100.100.100
}

vrrp_script chk_nginx {
     
    script "/etc/keepalived/check_nginx.sh"
    interval 1
    weight -30
}
vrrp_instance VI_1 {
     
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
     
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
     
        192.168.8.100/24 dev ens33 label ens33:1
    }
    track_script {
     
        chk_nginx
    }

        notify_master "/etc/keepalived/notify.sh master"                  新增脚本                                                                                                                                       
        notify_backup "/etc/keepalived/notify.sh backup"
        notify_fault "/etc/keepalived/notify.sh fault"
}






你可能感兴趣的:(笔记,linux,nginx,负载均衡)