search
HomeOperation and MaintenanceNginxNginx high availability method

Preparation:

Nginx high availability method

​192.168.16.128

​192.168.16.129

Two virtual machines. Install Nginx

Install Nginx

Update yum source file:

rpm-ivhhttp://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

​wget-O/etc/yum.repos.d/CentOS-Base.repohttp://mirrors.aliyun.com/repo/Centos-7.repo

Install Nginx:

​ yum-yinstallnginx

Operation command:

systemctlstartnginx;#Start Nginx

systemctlstopnginx;#stopNginx

What is high availability?

High availability HA (HighAvailability) is one of the factors that must be considered in the design of distributed system architecture. It usually refers to reducing the time when the system cannot provide services through design. If a system can always provide services, then the availability is 100%, but there are unforeseen circumstances. So we can only try to reduce service failures as much as possible.

solved problem?

In production environments, Nginx is often used as a reverse proxy to provide external services. However, Nginx will inevitably encounter failures one day, such as server downtime. When Nginx goes down, all externally provided interfaces will become inaccessible.

Although we cannot guarantee that the server is 100% available, we must find ways to avoid this tragedy. Today we use keepalived to implement Nginx

High availability.

Dual-machine hot backup solution

This solution is the most common high-availability solution among domestic enterprises. Dual-server hot backup actually means that one server is providing services and the other is in standby state for a certain service. When one server is unavailable, the other one Will take his place.

What is keepalived?

Keepalived software was originally designed for LVS load balancing software to manage and monitor the status of each service node in the LVS cluster system. Later, it added the VRRP (Virtual Router Redundancy Protocol) function that can achieve high availability. Therefore, in addition to managing LVS software, Keepalived can also be used as a high-availability solution software for other services (such as Nginx, Haproxy, MySQL, etc.)

Failover mechanism

Failover transfer between Keepalived high-availability services is implemented through VRRP.

When the Keepalived service is working normally, the main Master node will continuously send (multicast) heartbeat messages to the backup node to tell the backup Backup node that it is still alive. When the main Master node fails, it cannot send heartbeat messages and the backup node will not be able to send heartbeat messages. Therefore, the node can no longer detect the heartbeat from the master node, so it calls its own takeover program to take over the IP resources and services of the master node. When the master node recovers, the backup node will release the IP resources and services it took over when the master node failed, and return to its original backup role.

Implementation process

Install keepalived

You can install it directly using yum. This method will automatically install dependencies:

​ yum-yinstallkeepalived

Modify the host (192.168.16.128) keepalived configuration file

If installed in yum mode, the configuration file will be produced under /etc/keepalived:

vikeepalived.conf

keepalived.conf:

​ #Detection script

vrrp_scriptchk_http_port{

Script"/usr/local/src/check_nginx_pid.sh"#Heartbeat execution script to detect whether nginx is started

interval2# (interval for detecting script execution, unit is seconds)

weight2#weight

}

​#vrrp instance definition part

vrrp_instanceVI_1{

stateMASTER#Specify the role of keepalived, MASTER is the main one, and BACKUP is the backup one

interfaceens33#The current network interface card for vrrp communication (current centos network card) uses ifconfig to check your specific network card

​virtual_router_id66#Virtual routing number, the master and slave must always be

priority100#Priority, the larger the value, the higher the priority of obtaining and processing the request

advert_int1#Checking interval, the default is 1s (vrrp multicast cycle seconds)

​#Authorized access

Authentication{

auth_typePASS#Set the authentication type and password. MASTER and BACKUP must use the same password for normal communication

auth_pass1111

}

track_script{

chk_http_port# (call detection script)

}

virtual_ipaddress{

192.168.16.130#Define virtual ip (VIP), you can set more than one, one per line

}

}

​Vip can be configured in virtual_ipaddress, and services can be accessed online through vip.

The interface needs to be set according to the server network card. The usual viewing method is ipaddr

Authentication configuration authorization access to the backup machine also requires the same configuration

Modify the backup machine (192.168.16.129) keepalived configuration file

keepalived.conf:

​ #Detection script

vrrp_scriptchk_http_port{

Script"/usr/local/src/check_nginx_pid.sh"#Heartbeat execution script to detect whether nginx is started

interval2# (detection script execution interval)

weight2#weight

}

​#vrrp instance definition part

vrrp_instanceVI_1{

stateBACKUP#Specify the role of keepalived, MASTER is the main one and BACKUP is the backup one

interfaceens33#The current network interface card for vrrp communication (current centos network card) uses ifconfig to check your specific network card

​virtual_router_id66#Virtual routing number, the master and slave must always be

priority99#Priority, the larger the value, the higher the priority of obtaining and processing the request

advert_int1#Checking interval, the default is 1s (vrrp multicast cycle seconds)

​#Authorized access

Authentication{

auth_typePASS#Set the authentication type and password. MASTER and BACKUP must use the same password for normal communication

auth_pass1111

}

track_script{

chk_http_port# (call detection script)

}

virtual_ipaddress{

192.168.16.130#Define virtual ip (VIP), you can set more than one, one per line

}

}

Detection script:

​ #!/bin/bash

​#Detect whether nginx is started

A=`ps-Cnginx--no-header|wc-l`

​if[$A-eq0];then#If nginx is not started, start nginx

systemctlstartnginx#restart nginx

​if[`ps-Cnginx--no-header|wc-l`-eq0];then#nginx fails to restart, stop the keepalived service and perform VIP transfer

killallkeepalived

fi

fi

Script authorization: chmod775check_nginx_pid.sh

Note: The script must be authorized, otherwise it will not have permission to access. Here we have two servers executing, VIP (virtual_ipaddress:192.168.16.130), we access the service directly through VIP in the production environment.

Simulate nginx failure:

Modify the Nginx html page that the two servers access by default as a difference.

First, access 192.168.16.130 through VIP. The page displays 192.168.16.128; indicating that it is currently a service provided by the main server.

At this time, the 192.168.16.128 main server executes the command:

systemctlstopnginx;#stop nginx

When I visited VIP (192.168.16.130) again, I found that the page still displayed: 192.168.16.128. This was an automatic restart in the script.

Now directly close the 192.168.16.128 server, visit VIP here (192.168.16.130) and now find that the page shows 192.168.16.129. At this time, keepalived will automatically fail over, and a high-availability solution for an enterprise-level production environment has been established.

There are many functions in keepalived, such as email reminders, etc., but they are not available. You can go to the official website to read the documentation.

The above is the detailed content of Nginx high availability method. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

Using NGINX Unit: Deploying and Managing ApplicationsUsing NGINX Unit: Deploying and Managing ApplicationsApr 22, 2025 am 12:06 AM

NGINXUnit can be used to deploy and manage applications in multiple languages. 1) Install NGINXUnit. 2) Configure it to run different types of applications such as Python and PHP. 3) Use its dynamic configuration function for application management. Through these steps, you can efficiently deploy and manage applications and improve project efficiency.

NGINX vs. Apache: A Comparative Analysis of Web ServersNGINX vs. Apache: A Comparative Analysis of Web ServersApr 21, 2025 am 12:08 AM

NGINX is more suitable for handling high concurrent connections, while Apache is more suitable for scenarios where complex configurations and module extensions are required. 1.NGINX is known for its high performance and low resource consumption, and is suitable for high concurrency. 2.Apache is known for its stability and rich module extensions, which are suitable for complex configuration needs.

NGINX Unit's Advantages: Flexibility and PerformanceNGINX Unit's Advantages: Flexibility and PerformanceApr 20, 2025 am 12:07 AM

NGINXUnit improves application flexibility and performance with its dynamic configuration and high-performance architecture. 1. Dynamic configuration allows the application configuration to be adjusted without restarting the server. 2. High performance is reflected in event-driven and non-blocking architectures and multi-process models, and can efficiently handle concurrent connections and utilize multi-core CPUs.

NGINX vs. Apache: Performance, Scalability, and EfficiencyNGINX vs. Apache: Performance, Scalability, and EfficiencyApr 19, 2025 am 12:05 AM

NGINX and Apache are both powerful web servers, each with unique advantages and disadvantages in terms of performance, scalability and efficiency. 1) NGINX performs well when handling static content and reverse proxying, suitable for high concurrency scenarios. 2) Apache performs better when processing dynamic content and is suitable for projects that require rich module support. The selection of a server should be decided based on project requirements and scenarios.

The Ultimate Showdown: NGINX vs. ApacheThe Ultimate Showdown: NGINX vs. ApacheApr 18, 2025 am 12:02 AM

NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

NGINX in Action: Examples and Real-World ApplicationsNGINX in Action: Examples and Real-World ApplicationsApr 17, 2025 am 12:18 AM

NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!