nginx detailed explanation and configuration

What is a proxy:
Suppose there are two hosts and one server, and one of the hosts acts as a proxy (replaces) for the other host to access the server.
Forward proxy:
The proxy object is the client, the client forwards it to the proxy client, and the proxy client actually accesses the server, hiding The client's identity (IP).

客户端<==转发==>代理客户端的服务器<----------->服务器

The forward proxy can be turned on in win10 or browser settings. You need to specify the address and port of the proxy server. You can also turn on the proxy through third-party software.
Reverse proxy:
The proxy object is the server, and what the client actually accesses is the proxy server, hiding the true identity (IP) of the server .

客户端<----------->代理服务器的服务器<==转发==>服务器

Reverse proxy is also used for load balancing (Load Balance). The proxy server will distribute a large number of requests to multiple servers or clusters that provide the same service.
The load balancing strategy is related to the load balancing algorithm used by nginx. The polling algorithm is used by default. nginx also provides various parameters for load balancing tuning.
Polling (turn-by-turn query): Each request is assigned to different back-end servers one by one in chronological order

nginx is a lightweight web/reverse proxy server software that provides high-concurrency (high-performance) http services.
The reverse proxy will also save the content on the source web server requested by the client locally, so that when the same information request is received in the future,
will The content in the local cache is sent directly to the user to reduce the pressure on the source web server and improve response speed. Therefore nginx also has caching capabilities.

yum install -y epel-release	#安装扩展源
yum install -y nginx		#安装nginx
vim /etc/nginx/nginx.conf	#修改nginx默认配置文件
http {
    
    
  include mime.types; 		#文件扩展名与文件类型映射表
  default_type application/octet-stream; 	#默认文件类型
  autoindex on; 			#开启目录列表访问,合适下载服务器,默认关闭
  sendfile on; 			#开启高效文件传输模式
  tcp_nopush on; 			#防止网络阻塞
  tcp_nodelay on; 			#防止网络阻塞
  keepalive_timeout 120; 		#客户端连接保持存活的最大时间,单位是秒
  gzip on; 				#开启gzip压缩输出
  upstream 节点池名字 {
    
    		#均衡负载配置块
    server 127.0.0.1:8090 weight=1 max_fails=3 fail_timeout=10s;	#被http反向代理的服务器地址或域名和端口号,可添加多台
    server 127.0.0.1:8080 weight=2 max_fails=3 fail_timeout=10s;	
    #weight:代表权重,默认为 1,权重值越大被分配的客户端越多
    #max_fails:允许请求最大失败次数,用于探测后端节点状态,默认为1
    #fail_timeout:在经历了max_fails次失败后,暂停该后端节点的超时时间,等待下次探测,默认为10s
    #超时:发起请求后,等待响应发回的时间超过某段指定的时间后就称为超时,超时之后通常情况下是断开当前连接或者重连
  }
  server {
    
    				#nginx网页服务配置块
    listen 80;			#监听本机所有ipv4地址的80端口,如果有多张网卡可以在端口前指定地址,如果省略了端口则默认为80
    listen [::]:80;			#监听本机所有ipv6地址的80端口
    server_name 域名或IP地址;		#本机域名,多个域名用空格分开,可填写ip,当请求提交到nginx时,会先匹配ip,如果ip(listen字段)没有找到对应的ip,再通过域名(server_name字段)进行匹配
    client_max_body_size 1024m;	#客户端可通过http传输文件的大小,默认为1m
    keepalive_timeout 60;		#客户端连接保持存活的最大时间,默认为75秒
    charset utf-8;			#字符集
    location / {
    
    			#网站虚拟路径(虚拟主机),可添加多个,/代表根虚拟目录。当有多个location配置块时,优先匹配最符合条件的。
      proxy_pass http://地址:端口或节点池名字;	#配置http反向代理的地址(域名)和端口或者负载均衡池
      proxy_pass https://地址:端口号			#支持https反向代理,未填写端口号则为协议的默认端口
    }
    location /www/ {
    
    			#当访问虚拟目录www时,进入根目录(root)下对应的www目录
      root 根目录绝对路径;		#网站的根目录,该目录必须开放权限
      index 文件名;			#网站默认页面,默认为index.html
    }
    location /chen/ {
    
    			#当访问虚拟目录chen时,直接进入根目录(alias)
      alias 根目录绝对路径;
    }
  }
}
#配置块上下文:用花括号括起来的内容称为该配置块的上下文,类似函数的作用域。如果一个配置块包含另一个配置块,内部没有指定的字段将使用外部已指定的相同字段。
nginx -t	#检查nginx配置文件语法
nginx	#启动nginx服务

or

systemctl enable nginx --now	#永久开启nginx服务
nginx -s stop	#关闭nginx服务
nginx -s reload	#重新加载配置文件

location regular + path to achieve matching distribution
Syntax format:

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

Priority: = --> ^~ --> /* #When there are multiple inclusions< a i=3>/ When performing regular matching, select the location configuration with the longest regular expression for execution. Note: If the uri contains a regular expression, it must have ~ or ~ identifier For example:

location ~ /\.(gif | jpg | png)$ {
    
     }	#匹配根目录下所有以.gif .jpg .png结尾的uri

nginx performance optimization:

#指定nginx进程运行的用户以及用户组,默认为nobody
user 用户名 用户组;
#允许同时运行的nginx进程数,一般根据cpu的性能或线程数来设置,默认为1
worker_processes cpu线程数;
#单个进程允许同时打开的最大(网页)文件数,默认为无限制
worker_rlimit_nofile 65535;
#以上为全局配置
events {
    
    
    #单个进程允许同时建立的最大tcp连接数(并发数),默认为1024,不能超过最大打开文件数(worker_rlimit_nofile)
    worker_connections 32000;
}

High Availability:
High availability. When one server fails or requires maintenance, another server is available as a backup.
Principle: Both the active and backup servers use a virtual IP. The client accesses web resources through the virtual IP and determines which server to access first based on the priority of the configuration file.
KeepAlived is a service high availability solution based on the VRRP protocol, which can be used to avoid IP single points of failure.
The function of KeepAlived is to detect the status of the server. If a web server is down, or a work failure occurs, KeepAlived will detect it,
and will The server is removed from the system and other servers are used to replace the server's work. When the server is working normally, KeepAlived automatically adds the server to the server group.
All these tasks are completed automatically without manual intervention. , all that needs to be done manually is to repair the failed server.
nginx and keepalived are installed on both servers:

yum install -y keepalived
在主备上都编辑配置文件:
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
    
    
   router_id LVS_DEVEL	#主备一样
}
#可以实现一台机器挂了,虚拟IP会跳到另外的机器上继续运行,使用如下脚本检查nginx进程状态
vrrp_script nginx_check {
    
    			#注意:函数定义必须写在调用的前面
    script "/etc/keepalived/nginx_check.sh"	#脚本路径
    interval 2	#机器宕机时脚本调用的次数
    weight 2
}
 
vrrp_instance VI_1 {
    
    
    state BACKUP		#主MASTER  备BACKUP
    interface eth0		#绑定的网卡
    nopreempt		#备机(BACKUP)才用,不抢占的意思
    virtual_router_id 51		#组id,主备需要一致
    priority 99			#优先级,主比备高,主100,备99
    advert_int 1			#检查间隔1s
    authentication {
    
    
        auth_type PASS
        auth_pass 1111		#认证密码,可以修改主备相同
    }
    track_script {
    
    
	nginx_check		#调用nginx检查函数
    }
    virtual_ipaddress {
    
    
        192.168.1.100/24		#添加虚拟IP(vip),自己设置,要跟内网同一个网段
    }
}

Use shell scripts to detect whether the nginx service is running and control the status of the active and standby servers:

vim /etc/keepalived/nginx_check.sh	#在主备上都创建nginx进程检查脚本
#!/bin/bash
ps -C nginx --no-header	#查看nginx进程是否存在
if [ $? -eq 1 ];then		#如果nginx进程不存在
  /usr/sbin/nginx		#尝试重启nginx
  if [ $? -eq 0 ];then		#如果nginx重启成功
    exit 1			#返回非0结果,不跳转到备用服务器
  else
    pkill -9 keepalived	#关闭当前机器的keepalived进程,虚拟ip跳转到备用服务器
    exit 0			#返回0
  fi
fi
chmod +x nginx_check.sh	#赋予脚本可执行权限
sed -i '/SELINUX/s/enforcing/disabled/' /etc/selinux/config	#/SELINUX/为匹配包含//内的字符的行
setenforce 0	#必须要关闭selinux,keepalived才能生效
systemctl enable keepalived -now	#永久启动高可用(主从)

There is no need to start nginx after that, the keepalived detection script will automatically start nginx.

tail -f /var/log/messages|grep Keepalived	#查看日志
curl 192.168.1.100		#访问虚拟IP,为效果明显,可以修改主备服务器的网页内容以便区分

High availability - master-slave mode: Use one virtual IP, one master server and one slave server. Only the master server provides services to the outside world. The resources of the slave server will always be wasted when the master server does not fail.
High availability - active-active mode: Use two virtual IPs to enable both servers to provide services to the outside world. Both servers are bound to two virtual IPs that are mutually active and standby. When one of them When a machine fails,
requests from both machines are transferred to one machine, and can also be distributed to the two virtual IPs through the load balancing function or dns load balancing provided by nginx.
Configure nginx+keepalived master mode:
First server:

master:10.100.1.200(优先级高)
slave:10.100.1.220(优先级低)

Second server:

master:10.100.1.220(优先级高)
slave:10.100.1.200(优先级低)

Note: The router_id and virtual_router_id of the two servers cannot be the same in the master mode.
The keepalived configuration of the first server:

! Configuration Filefor keepalived  
global_defs {
    
      
    router_id nginx_node_01
}  
vrrp_script nginx_check {
    
    
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight 2
}
vrrp_instance VI_1{
    
      
   state MASTER
   interface ens33
   virtual_router_id 20
   priority 100  
   advert_int 1  
   authentication {
    
      
       auth_type PASS  
       auth_pass 1111  
   }  
   virtual_ipaddress {
    
      
       10.100.1.200/24
   }  
} 
vrrp_instance VI_2{
    
      
   state BACKUP
   interface ens33
   virtual_router_id 22
   priority 80
   advert_int 1  
   authentication {
    
      
       auth_type PASS
       auth_pass 1111  
   }
   virtual_ipaddress {
    
    
       10.100.1.220/24
   }
   track_script {
    
                         
       nginx_check
   }
}

Keepalived configuration for the second server:

! Configuration Filefor keepalived  
global_defs {
    
      
    router_id nginx_node_02
}  
vrrp_script nginx_check {
    
    
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight 2
}
vrrp_instance VI_1{
    
      
   state BACKUP
   interface ens33 
   virtual_router_id 20
   priority 80 
   advert_int 1  
   authentication {
    
      
       auth_type PASS  
       auth_pass 1111  
   }  
   virtual_ipaddress {
    
      
       10.100.1.200/24
   }  
} 
vrrp_instance VI_2{
    
      
   state MASTER
   interface ens33
   virtual_router_id 22
   priority 100
   advert_int 1  
   authentication {
    
      
       auth_type PASS
       auth_pass 1111  
   }
   virtual_ipaddress {
    
    
       10.100.1.220
   }
   track_script {
    
                         
       nginx_check
   }
}

Both servers start the keepalived service:

yum install -y keepalived	#之后keepalived会自动启动nginx服务

test:

curl 10.100.1.200
curl 10.100.1.220

In master-master mode, you can access two servers separately by accessing two virtual IPs, effectively utilizing the resources of the two servers. When one machine is down, you can still access the two virtual IPs
In order to utilize server resources more effectively, you can also add an nginx server in front to configure load balancing and distribute it to these two virtual IPs, or use the same domain name to resolve to these two virtual IPs. on

VRRP introduction:
The full name of VRRP is Virtual Router Redundancy Protocol, which is "Virtual Router Redundancy Protocol".
It can be considered as a fault-tolerant protocol to achieve high availability of routers, that is, N routers (hosts) that provide the same functions are formed into a router group (Router Group),
There is a master and multiple backups in this group, but it looks like one to the outside world, forming a virtual router.
It has a virtual IP (VIP - Virtual IP, which is the LAN where the router is located) The default route of other machines in the group),
The master that occupies this IP is actually responsible for ARP response and forwarding IP packets, and other routers in the group are on standby as backup roles.
The master will send multicast messages. When the backup cannot receive the vrrp packet within the timeout period, it will be considered that the master is down.
At this time, VRRP needs to be followed The priority is used to elect a backup as the master to ensure the high availability of the router.

In the VRRP protocol implementation, the virtual router uses 00-00-5E-00-01-XX as the virtual MAC address.
XX is the unique VRID (Virtual Router IDentifier). This address is occupied by only one physical router at a time.
In the physical router group in the virtual router, notification messages are regularly sent through the multicast IP address 224.0.0.18.
Each Router has a priority level between 1-255, and the highest priority will become the master router.
By lowering the priority of the master, the router in the backup state can preempt (pro-empt) the status of the main router.
Two IPs with the same backup priority The one with the larger address is the master and takes over the virtual IP.

Reference materials:
http://fisherworks.cn/?p=3541
http://www.cncsto.com/article/ 1984
https://zhuanlan.zhihu.com/p/166304639
https://www.jianshu.com/p/bb8cb34e0284< a i=5> https://www.zhihu.com/question/24723688 https://www.cnblogs.com/niesaisai/p/8127469.html https://www.cnblogs.com/mzhaox/p/11215036.html https://blog.csdn.net/qq_46312987/article/details/118895520< a i=9> https://blog.csdn.net/qq_26420601/article/details/110261184 https://blog.csdn.net/qq_38992249/article/details/117387083 https://www.sohu.com/a/547873141_120122487 https://blog.csdn.net/wzj_110/article/details/110142902 https://baijiahao.baidu.com/s?id=1704543670669857039&wfr=spider&for=pc http://m.bubuko.com/infodetail-3250218.html https://www.jianshu.com/p/b147a719f740 https://blog.huati365. com/922f1ad193da25a1 https://blog.csdn.net/weixin_52270081/article/details/118341576 https://blog.csdn.net/ chuanchengdabing/article/details/119727185 https://www.cnblogs.com/wuguofeng/p/15206947.html https://baijiahao.baidu.com/s?id=1672649081319142060&wfr= spider&for=pc https://blog.csdn.net/qq_41453285/article/details/106312967
















Guess you like

Origin blog.csdn.net/qq_38022367/article/details/131233884