Before we get started, let’s understand: what is Nginx? What is NGINx high availability? What is nginx reverse proxy? How does nGINx high availability work? With a series of questions and so on, we have to start the environment today.

Nginx is introduced

Nginx (Engine X) is a high-performance HTTP and reverse proxy Web server that also provides IMAP/POP3/SMTP services. It is known for its stability, rich feature set, simple configuration files, and low system resource consumption. Nginx is a lightweight Web server/reverse proxy server and email (IMAP/POP3) proxy server, which is featured by less memory, strong concurrency, in fact, Nginx concurrency in the same type of Web server performance is better, mainland China using Nginx website users are: Baidu, JINGdong, Sina, netease, Tencent, Taobao and so on.

1. Preparation before the opening:

1.1 Server:

192.168.177.134 192.168.177.136

Two virtual machines are prepared and nginx is installed

Nginx version 1.2

Nginx version: nginx / 1.20.1

2, Nginx installation

2.1 Nginx download address

Wget nginx.org/download/ng…

2.2 Decompress nginx and install it
-- Go to the service installation package directory, where you put home/servercd/home/server/ -- Decompress the tar package tar -zxvf nginx-1.20.1.tar.gz -- Go to the nginx directorycd/configure --prefix=/usr/./configure --prefix=/usr/local/nginx --with-http_ssl_module -- make && make installCopy the code
2.3 Compilation Installation failed to execute the./configure step because environment variables are missing
checking forC compiler... not found ./configure: error: C compiler cc is not foundCopy the code
The solution
yum -y install gcc
yum -y install gcc-c++
Copy the code
2.4 PCRE error
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre= option.
Copy the code
The solution
yum -y install openssl openssl-devel
Copy the code
Nginx installation process requires the installation of dependencies, installation error can be seen in another blog, nginx installation tutorial, which has a detailed installation process, this is not the subject of this article, after the installation of the above operation will begin our next high availability tour.

3 What is high availability?

HighAvailability (HA) is one of the factors that must be considered in the architecture design of distributed systems. It usually refers to the design to reduce the time when the system cannot provide services. If a system can provide service all the time, then the availability is 100 percent, but the weather can change. So we can only minimize service failures as much as possible.

3.1 Problems to be solved in this tutorial

In the production environment, Nginx is often used as the reverse proxy to provide external services. During service running, Nginx will inevitably encounter faults, such as server downtime and service unavailability. When Nginx goes down, all external interfaces become inaccessible. Although we can’t guarantee 100% availability of the server, we have to find ways to avoid this kind of tragedy. Today we are using Keepalived to implement high availability of Nginx.

3.2 Dual-system hot Backup

Dual-system hot backup is one of the most common high availability solutions in Domestic enterprises. Dual-system hot backup actually means that one server is providing services while the other server is in the standby state of a certain service. When one server is unavailable, the other server will replace it.

3.3 keepalived is introduced

Keepalived is the next lightweight high availability solution for Linux. High Avalilability (HA) has two different meanings: HeartBeat RoseHA has the same functionality as HeartBeat RoseHA, which enables high availability of services or networks, but is different. HeartBeat is a professional, fully functional high availability software. It provides the basic functions required by HA software, such as heartbeat detection, resource takeover, detection of services in the cluster, transfer of owners of shared IP addresses among cluster nodes, and so on. Keepalived is very powerful, but it is relatively difficult to deploy and use. Compared to HeartBeat, Keepalived mainly uses virtual route redundancy to achieve high availability. Although it is not as powerful as HeartBeat, Keepalived is very simple to deploy and use. All configuration is done with a single configuration file

3.4 What is Keepalived?

Keepalived was originally designed for LVS to monitor the state of each server node in a clustered system. Keepalived detects the state of each server node based on layer 3, 4, and 5 switching mechanisms of the TCP/IP reference model. If a server node is abnormal, or fails to work, Keepalived will detect it. And will appear the failure of the server node from the cluster system to eliminate, all these work is completed automatically, do not need manual intervention, need manual completion is only repair the failure of the service node. Later, Keepalived was added to the function of VRRP. VRRP (Vritrual Router Redundancy Protocol) was created to solve the single point of failure problem of static routes. Through VRRP, the network can operate continuously and stably. Therefore, Keepalvied on the one hand has the function of server status detection and fault isolation, on the other hand also has the HA cluster function, about the process of VRRP protocol implementation. Check out keepalived’s official documentation

3.5 Failover mechanism

Keepalived Failover between high availability services is implemented through VRRP. While Keepalived is working correctly, the Master node sends heartbeat messages to the standby node continuously (in multicast mode) to tell the standby node that it is still alive. When the Master node fails, it cannot send heartbeat messages. Therefore, the standby node cannot detect the heartbeat of the Master node and invokes its own takeover program to take over the IP resources and services of the Master node. When the active Master node recovers, the standby Backup node releases the IP resources and services that the active Master node takes over when the active Master node fails and restores to the original standby role.

3.6 Keepalived official documentation

The document address: www.keepalived.org/manpage.htm…

3.7 keepalived installation

yum -y install keepalived
Copy the code

3.7.1 Modifying the Keepalived Configuration File of host (192.168.177.134

/etc/keepalived: /etc/keepalived:

vi keepalived.conf
Copy the code
# check script
vrrp_script check_http_port {
    script "/usr/local/src/check_nginx_pid.sh" # heartbeat execute script to check if nginx is started
    interval 2                          # check the interval between script execution, in seconds
    weight 2                            # weights
}
# VRRP instance definition section
vrrp_instance VI_1 {
    state MASTER            Keepalived specifies a keepalived role, MASTER as primary, BACKUP as BACKUP
    interface ens33         Use ifconfig to check which network interface card you are using
    virtual_router_id 66    # Indicates the number of the virtual route
    priority 100            # priority, the higher the value, the higher the priority of obtaining and processing requests
    advert_int 1            Check interval, default is 1s(VRRP multicast cycle seconds)
    # Authorized access
    authentication {
        auth_type PASS MASTER and BACKUP must use the same password to communicate
        auth_pass 1111
    }
    track_script {
        check_http_port            # (call detection script)} virtual_ipaddress {192.168.177.135/32# Define virtual IP (VIP), can be set more than one, each line one}}Copy the code

Virtual_ipaddress allows you to configure viPs to access services online. Interface The value must be set based on the server nic. Common View Method IP Addr Authentication Configure the same configuration for authorized access to the standby host

3.7.2 Modifying the Keepalived Configuration File of the standby HOST (192.168.177.135)

vi keepalived.conf
Copy the code

keepalived.conf:

# check script
vrrp_script check_http_port {
    script "/usr/local/src/check_nginx_pid.sh" # heartbeat execute script to check if nginx is started
    interval 2                          # check the interval between script execution, in seconds
    weight 2                            # weights
}
# VRRP instance definition section
vrrp_instance VI_1 {
    state BACKUP Keepalived specifies a keepalived role, MASTER as primary, BACKUP as BACKUP
    interface ens33         Use ifconfig to check which network interface card you are using
    virtual_router_id 66    # Indicates the number of the virtual route
    priority 99            # priority, the higher the value, the higher the priority of obtaining and processing requests
    advert_int 1            Check interval, default is 1s(VRRP multicast cycle seconds)
    # Authorized access
    authentication {
        auth_type PASS MASTER and BACKUP must use the same password to communicate
        auth_pass 1111
    }
    track_script {
        check_http_port            # (call detection script)} virtual_ipaddress {192.168.177.135/32# Define virtual IP (VIP), can be set more than one, each line one}}Copy the code

3.7.3 Detection Script:

#! /bin/bash

A=`ps -C nginx --no-header |wc -l`        
if [ $A -eq 0 ];then                    
      /usr/local/nginx/sbin/nginx
      if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
              killall keepalived                    
      fi
fi
Copy the code

After creating a script, run the chmod 775 check_nginx_pid.sh command to grant authorization

Note: check_nginx_PID script needs authorization, otherwise there is no permission to call, here we two servers to execute, we in the production environment is directly through VIP access to the service.

3.8 starting keepalived

systemctl start keepalived.service
Copy the code

4. Simulate an Nginx server failure

Test the success of setup by simulating nginx server failure

4.1 Simulating nginx failures:

4.1.1 In the first step, we tested by modifying the HTML pages of two servers: 4.1.2 Access192.168.177.134To see the effect:4.1.3 access192.168.177.136To see the effect:4.1.4 through192.168.177.135VIP access to view the effect:

Access 192.168.177.135. Access 192.168.177.136 through VIP. The page displays 192.168.177.136. This indicates that server 136 provides services externally.

4.1.5 Logging In to the 192.168.177.136 Server Run the following command:

/usr/local/nginx/sbin/nginx -s stop
Copy the code

To visit again192.168.177.135At this time, the page still displays:192.168.177.136This is the automatic restart in the script. 4.1.6 Will now directly192.168.177.136Server ShutdownWhen you visit 192.168.177.135 again and the page says 192.168.177.134, Keepalived automatically fails over and a high availability solution for an enterprise production environment is set up.

That’s all for today’s tutorial. If this article is helpful to you, please share it with your friends. Your encouragement is the biggest motivation for me.