Nginx + Keepalived to build a highly available load layer method, nginxkeepalived
This article is based on the following topology:
+-------------+ | uplink | +-------------+ | + MASTER keep|alived BACKUP 192.168.1.11 192.168.1.10 192.168.1.12+-------------+ +-------------+ +-------------+| Nginx VM1 |----| virtualIP |----| Nginx VM2 |+-------------+ +-------------+ +-------------+ | +------------------+------------------+ | | |+-------------+ +-------------+ +-------------+| web01 | | web02 | | web03 |+-------------+ +-------------+ +-------------+
Two servers are configured in total:
First server: Nginx vm1 and keepalived MASTER; second server: Nginx vm2 and keepalived BACKUP;
I. Preparations 1. Prepare two independent Nginx Systems
Here, the IP addresses of the two Nginx virtual machines are:
Nginx VM1: 192.168.61.11: 80 Nginx VM2: 192.168.61.12: 80
Nginx has no configuration options, because it is not associated with keepalived. But remember, the configuration on the two nginx servers should be exactly the same (rsync synchronization), so as to be transparent to users, nginx. the server_name in conf should be replaced by a domain name, and then dns resolves the domain name to the virtual IP address 192.168.1.10.
Note that:Nginx must listen to the accessed address.
Appendix: For Nginx Server installation and configuration, see:
Nginx Server installation and configuration
Three methods for configuring Nginx virtual hosts (I) (based on IP)
Three methods for configuring Nginx virtual hosts (2) (Port-based)
Three methods for configuring Nginx virtual hosts (III) (based on domain names)
2. Install Keepalived on two virtual machines with Nginx installed.
My environment is CentOS 7.0 X86_64, which is the easiest to install directly using yum:
[root@bogon /]# yum install -y keepalived[root@bogon /]# keepalived -v[root@bogon /]# Keepalived v1.2.13 (08/03,2017)
Attachment: install and configure the Keepalived server by using the source code. For more information, see install and configure the Keepalived server.
3. Compile the nginx monitoring script
This script detects the running status of ngnix and tries to restart ngnix if the nginx process does not exist. If the startup fails, stop keepalived and prepare other machines to take over.
[root@bogon /]# vim /etc/keepalived/check_nginx.sh#!/bin/shif [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then /usr/local/nginx/sbin/nginxfisleep 2if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then service keepalived stopfi
Ii. simple configuration of Nginx + Keepalived 1. Confirm the prerequisites again.
(First, disable the firewall first to ensure that no extra problems will occur. Of course, the firewall cannot be closed in the formal environment)
Floating IP address for Nginx access over the Internet: 192.168.1.10; we use Nginx running on the server 192.168.1.11 as the main Nginx, and we set the keepalived service on it to the Master mode; we use Nginx running on 192.168.1.12 as a Backup Nginx service, and the keepalived service on it is set to Backup.
2. Set the MASTER on 192.168.1.11.
Let's take a look at the original IP address information on 192.168.1.11:
[root@localhost ~]# ifconfigens33: flags=4163
mtu 1500 inet 192.168.1.11 netmask 255.255.255.0 broadcast 192.168.1.255 inet6 fe80::2a8d:be6:a4a8:ea0 prefixlen 64 scopeid 0x20
ether 00:0c:29:1a:76:7e txqueuelen 1000 (Ethernet) RX packets 70 bytes 11009 (10.7 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 73 bytes 11927 (11.6 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73
mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10
loop txqueuelen 1 (Local Loopback) RX packets 72 bytes 6252 (6.1 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 72 bytes 6252 (6.1 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Note that the NIC device number on this 11 machine is ens33 rather than eth0. This parameter will be used when keepalived is configured.
The following is the simplest configuration of keepalived on 11:
! Configuration File for keepalived # global setting, notify email settingglobal_defs {# exists in the same network segment. Each node of a group of keepalived has a different name # in global settings, you can also set the Administrator's email information. Router_id LVS_V1} # This is the nginx check script we mentioned in the previous summary. We save it in this file (pay attention to file permissions) vrrp_script chknginx {script "/etc/keepalived/check_nginx.sh" # Check the settings of an interval 10} # keepalived instance every 10 seconds, is the most important setting information vrrp_instance VI_1 {# state MASTER indicates it is the main working node. # In a keepalived group, there is only one MASTER node at most. Of course, there can also be no Nic device bound to the state MASTER # instance. My Nic device is ens33. According to your own interface, ens33 # In the same keepalived group, the node settings must be the same so that virtual_router_id 52 # Node priority can be recognized, the BACKUP priority must be lower than the MASTER priority 100 # The interval for sending multicast information. The two nodes must be set to the same advert_int 1 # The actual fixed IP address of ens33 mcast_src_ip 192.168.1.11 # verification information, you can be added to a group only when the verification information is the same. Authentication {auth_type PASS auth_pass 1111} # virtual address and bound port. If there are multiple, bind multiple # dev is the NIC device number to be bound with the specified floating IP. virtual_ipaddress {192.168.1.10 dev ens33} # Check script # associate vrrp_script chknginx track_script {chknginx} above }}3. Set BACKUP on 192.168.1.12
Let's take a look at the keepalived settings on the slave node 192.168.1.12:
! Configuration File for keepalived # global setting, notify email settingglobal_defs {# The router_id LVS_V2} # check Your chknginx {script "/etc/keepalived/check_nginx.sh" interval 10} # instance settingvrrp_instance VI_1 {# Here And the master node different state BACKUP interface ens33 # virtual_router_id 52 must be the same here # the priority here is lower than the Master node priority 99 advert_int 1 # Here it is different from the Master node mcast_src_ip = 192.168.1.12 authentication {auth_type PASS auth_pass 1111} virtual_ipaddress {192.168.1.10 dev ens33} track_script {chknginx }}4. Start the master node and slave Node
Pay attention to the following key points in the above Configuration:
Note the location of the script for nginx status check. The specified location of the script check varies depending on the location of the file you created. Note that the priority of the MASTER node must be higher than that of all BACKUP nodes; note that the multicast address of the LAN must be available. All keepalived nodes in the LAN use multicast to find the other node. Who said that there can only be one BACKUP node !? Finally, keepalived must be registered as a service. You can imagine the situation of all the above scripts, configurations, and commands.
Next, start the Master node and Backup node. To view the log status accurately, you need to observe the system log.Location of system logs:
tail -f /var/log/messages
Start the Master node first:
[root@localhost ~]# service keepalived start
Start the Backup node again:
[root@localhost ~]# service keepalived start
If both configuration and startup are successful, you will not receive any keepalived error message in the log information. Next, you can use the IP address 192.168.1.10 to access Nginx:
In addition, the floating ip Address: 192.168.1.10 bound to 192.168.1.11 is generally invisible through the ipconfig command. You need to use the ip addr command to view it:
# The ip address configured using the ip command. ifconfig cannot view [root @ bogon system] # ip a | grep ens332: ens33:
Mtu 1500 qdisc pfifo_fast state UP qlen 1000 inet 192.168.1.11/24 brd 192.168.1.255 scope global dynamic ens33 inet 192.168.1.12/32 scope global ens33
In order to test, we take the initiative to stop the keepalived service on the Master node (note that killing the Nginx process does not work, because our check script will try to restart the Nginx process ), next we can see that the floating IP address is drifting to the 12-slave machine:
Iii. Nginx + Keepalived non-preemption Mode
Through the above detailed introduction, I believe you have a clear understanding of the Nginx + Keepalived installation method. The keepalived switchover can be automatic, but it cannot be performed in milliseconds. It takes several seconds to switch between them.
This is a problem. Although the delay is inevitable when we switch to the backup node when the master node fails, after we fix the master node, there is no need to perform another switchover immediately, therefore, Keepalived provides a non-preemption mode to meet this requirement.
Next we will introduce the configuration of Keepalived in non-preemption mode (no MASTER node, which is determined based on the priority ):
1. configuration changes of the original master node
! Configuration File for keepalived # global setting, notify email settingglobal_defs {router_id LVS_V1} vrrp_script chknginx {script "/etc/keepalived/check_nginx.sh" interval 10 # once the node fails, the priority of a node is reduced by 2 # The number of keepalived nodes is reduced. # This ensures that the priority of this node is lower than that of other nodes. weight-2 # fall indicates the number of failed checks, even if the node fails. The default 1 # fall 1} vrrp_instance VI_1 {# state status is "BACKUP", indicating that the master node is used. State BACKUP interface ens33 virtual_router_id 52 # This key configuration item, set to "non-preemptible" Mode nopreempt # the priority of each node must be different from that of priority 100 advert_int 1 mcast_src_ip = 192.168.1.11 authentication {auth_type PASS auth_pass 1111} # virtual address and bound port, if there are multiple, bind multiple # dev is the NIC device number to be bound with the specified floating IP. virtual_ipaddress {192.168.1.10 dev ens33} # Check script # associate vrrp_script chknginx track_script {chknginx} above }}
The original master node settings have been changed.
2. configuration changes of the original backup Node
Add"Non-preemptible mode keywords, MoreChange a specified priority., SetDecrease in priority after check failure.
Appendix. Problems During configuration 1. Why does Nginx stop responding? In my work experience, there are only the following situations::
All Nginx processes are forcibly terminated (or managed );
In this case, we need to check and switch. No matter what the process is terminated, if it cannot be restarted, we need to switch to the slave machine.
The mount point of the Nginx log disk crashes or the disk is full;
This is what we need to check and switch.
Nginx has reached the set maximum number of connections, and the response is temporarily stopped;
In this case, we cannot switch the backup server because there are a large number of user requests connected through VIP: 192.168.61.100 (the number of user requests can reach 65535/4 after we optimize the parameters ), once we switch the backup server, all these user requests will be abnormal. To solve this problem, you need to add the server load, rather than the Master/Slave switchover.
Abnormal shutdown of Nginx physical machine.
This must be checked and switched.
2. nginx monitoring script
#!/bin/shif [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then /usr/local/nginx/sbin/nginxfisleep 2if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then service keepalived stopfi
Explanation of the entire script:
The first judgment indicates that if the current number of nginx processes is = 0, then run the nginx startup command to restart nginx; wait for 2 seconds (this is to give nginx a certain start time), and then check the number of Nginx processes again. If it is still = 0, stop the keepalived service on this machine, so that the standby Keepalived node checks that the Keepalived event has been stopped and switches the floating IP address to the standby server.
Note that this script is related to the Nginx installation path on my machine and the Keepalived service status. If you want to use this script, make changes accordingly.
Then explain the meaning of each command in detail:
Let's take a rough look at the "ps-C nginx-no-header | wc-l" command:
The ps command is used for process-related queries in linux.-C indicates querying by process name. The query results are as follows:
[root@bogon /]# ps -C nginx PID TTY TIME CMD 3178 ? 00:00:00 nginx 3180 ? 00:00:00 nginx 3181 ? 00:00:00 nginx 3182 ? 00:00:00 nginx 3183 ? 00:00:00 nginx
If you want to remove the header of the statistical result table, you must use the-no-header parameter. After adding the parameter, the query result is as follows:
[root@bogon /]# ps -C nginx --no-header 3178 ? 00:00:00 nginx 3180 ? 00:00:00 nginx 3181 ? 00:00:00 nginx 3182 ? 00:00:00 nginx 3183 ? 00:00:00 nginx
"|", Which is the pipeline stream command in Linux. The output result of the previous command is used as the input of the next command. Wc statistics command, the-l parameter, indicates statistics by number of rows. Therefore, the output result of the entire command is:
[root@bogon /]# ps -C nginx --no-header | wc -l5
3. Description of configuration options
Global_defs
Notification_email: Keepalived needs to send an email notification address in case of a switchover, And the smtp_server later knows that it is the mail server address. You can also trigger alarms in other ways. After all, emails are not notified in real time;
Router_id: Machine ID, which can be set to hostname. When a fault occurs, email notification will be used.
Vrrp_instance
State: Specifies the Initial state of the instance (Initial), that is, after the configuration, the Initial state of this server is specified here, but not here, you still have to determine the priority of the campaign. If this parameter is set to MASTER, but if the priority is lower than that of the other instance, this instance will send its own priority when sending the notification, and the other instance will find that the priority is lower than its own, then he will seize it as the MASTER;
Interface: Network card bound to the instance, because the virtual IP address must be added to the existing network card;
Mcast_src_ip: Source IP address used to send multicast data packets. Note that VRRP notifications are actually sent on that address. This is very important. You must select a stable Nic port for sending, this is equivalent to heartbeat's heartbeat port. If it is not set, use the default bound Nic IP address, that is, the IP address specified by the interface;
Virtual_router_id: VRID is set here. It is very important here. If the same VRID is a group, it determines the multicast MAC address;
Priority: Set the priority of the current node. The priority is higher than that of the master node;
Advert_int: Check Interval. The default value is 1 second. This is the VRRP timer. The MASTER sends an advertisement message every other time interval to notify other routers in the group to work normally;
Authentication: Defines the authentication method and password. The master and slave must be the same;
Virtual_ipaddress: The VIP is set here, that is, the virtual IP address. It is added and deleted as the state changes. It is added when the state is master and deleted when the state is backup, priority is mainly determined here, and it has little to do with the value set by state. Multiple IP addresses can be set here;
Track_script: Reference the VRRP script, that is, the name specified in the vrrp_script section. Run them regularly to change the priority and eventually lead to master-slave switchover.
Vrrp_script
It is especially important to tell keepalived when to switch. Multiple vrrp_scripts
Script: a self-written detection script. It can also be a line of command such as killall-0 nginx; interval 2: Detection once every 2 S; weight-5: detection failure (the script returns a non-0), priority-5; fall 2: if the detection fails for two consecutive times, it is a true failure. Weight will be used to reduce the priority (between 1-); rise 1: Once detected successfully, it will be successful. But the priority is not modified.
There are two methods to write a script:
The returned results of script execution change the priority. keepalived continues to send the notification message, and the backup priority is determined after comparison. if an exception is detected in the script, the keepalived process is directly disabled, if the backup machine fails to receive the advertisement, it will seize the IP address.
In the configuration section of vrrp_script above,Killall-0 nginxThere are 1st cases,/Etc/keepalived/check_nginx.shIn 2nd cases (keepalived is disabled in the script ). Individuals tend to use shell scripts to determine whether to seize the VIP. If an exception occurs, exit 1 and exit 0 normally. Then, keepalived determines whether to seize the VIP Based on the dynamically adjusted vrrp_instance priority election:
If the script execution result is 0 and the weight configuration value is greater than 0, the priority increases accordingly. If the script execution result is not 0 and the weight configuration value is less than 0, the priority is reduced accordingly.
In other cases, the priority of the original configuration remains unchanged, that is, the value of priority in the configuration file.
Tip:
The priority will not be continuously increased or decreased; you can write multiple detection scripts and set different weight values for each detection script (just list them in configuration); no matter whether the priority is increased or decreased, the final priority is in the range of [1,254], so there will be no situations where the priority is less than or equal to 0 or the priority is greater than or equal to 255. In the vrrp_instance of the MASTER node, configure nopreempt. When the exception recovers, it won't be preemptible even if its prio is higher, which can avoid unnecessary switching under normal circumstances.
You can use scripts to check the status of business processes and dynamically adjust the priority to implement master-slave switchover.
Configuration complete
In the default keepalive. conf file, there are also configurations such as virtual_server and real_server. We cannot use them, but they are prepared for lvs. Notify can define the script executed when switching to MASTER or BACKUP. If you need it, google it on your own.