search
HomeOperation and MaintenanceNginxHow to implement Nginx high availability in production environment

Preparation work:

192.168.16.128

192.168.16.129

Two virtual machines. Install nginx

Install nginx

Update yum source file:

rpm -ivh http://nginx.org/packages/centos/7/noarch/rpms/nginx-release-centos-7-0.el7.ngx.noarch.rpm
wget -o /etc/yum.repos.d/centos-base.repo http://mirrors.aliyun.com/repo/centos-7.repo

Install nginx:

yum -y install nginx

Operation command:

systemctl start nginx; #启动nginx
systemctl stop nginx; #停止nginx

What is high availability?

High availability HA (high availability) 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 achieve high availability of nginx

.

Dual-machine hot backup solution

This solution is the most common high-availability solution among domestic enterprises. Dual-machine hot backup actually refers to a 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 its 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, vrrp (virtual router) was added to achieve high availability. redundancy protocol, virtual router redundancy protocol) function. Therefore, in addition to being able to manage LVS software, keepalived can also be used as a high-availability solution software for other services (such as: nginx, haproxy, mysql, etc.)

failover mechanism

keepalived Failover transfer between 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 node that it is still alive. When the main master node fails , it cannot send heartbeat messages, and the standby node cannot continue to 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 primary master node recovers, the backup node will release the IP resources and services it took over when the primary node failed, and return to its original backup role.

Implementation process

Install keepalived

You can install it directly with yum, which will automatically install dependencies:

yum -y install keepalived

Modify the host (192.168.16.128) keepalived configuration file

The yum installation will produce the configuration file under /etc/keepalived:

vi keepalived.conf

keepalived.conf:

#检测脚本
vrrp_script chk_http_port {
 script "/usr/local/src/check_nginx_pid.sh" #心跳执行的脚本,检测nginx是否启动
 interval 2       #(检测脚本执行的间隔,单位是秒)
 weight 2       #权重
}
#vrrp 实例定义部分
vrrp_instance vi_1 {
 state master   # 指定keepalived的角色,master为主,backup为备
 interface ens33   # 当前进行vrrp通讯的网络接口卡(当前centos的网卡) 用ifconfig查看你具体的网卡
 virtual_router_id 66 # 虚拟路由编号,主从要一直
 priority 100   # 优先级,数值越大,获取处理请求的优先级越高
 advert_int 1   # 检查间隔,默认为1s(vrrp组播周期秒数)
 #授权访问
 authentication {
  auth_type pass #设置验证类型和密码,master和backup必须使用相同的密码才能正常通信
  auth_pass 1111
 }
 track_script {
  chk_http_port   #(调用检测脚本)
 }
 virtual_ipaddress {
  192.168.16.130   # 定义虚拟ip(vip),可多设,每行一个
 }
}


Virtual_ipaddress can be configured with vip, 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 ip addr

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:

#检测脚本
vrrp_script chk_http_port {
 script "/usr/local/src/check_nginx_pid.sh" #心跳执行的脚本,检测nginx是否启动
 interval 2       #(检测脚本执行的间隔)
 weight 2       #权重
}
#vrrp 实例定义部分
vrrp_instance vi_1 {
 state backup      # 指定keepalived的角色,master为主,backup为备
 interface ens33      # 当前进行vrrp通讯的网络接口卡(当前centos的网卡) 用ifconfig查看你具体的网卡
 virtual_router_id 66    # 虚拟路由编号,主从要一直
 priority 99       # 优先级,数值越大,获取处理请求的优先级越高
 advert_int 1      # 检查间隔,默认为1s(vrrp组播周期秒数)
 #授权访问
 authentication {
  auth_type pass #设置验证类型和密码,master和backup必须使用相同的密码才能正常通信
  auth_pass 1111
 }
 track_script {
  chk_http_port     #(调用检测脚本)
 }
 virtual_ipaddress {
  192.168.16.130     # 定义虚拟ip(vip),可多设,每行一个
 }
}

Detection script:

#!/bin/bash
#检测nginx是否启动了
a=`ps -c nginx --no-header |wc -l`  
if [ $a -eq 0 ];then #如果nginx没有启动就启动nginx      
  systemctl start nginx    #重启nginx
  if [ `ps -c nginx --no-header |wc -l` -eq 0 ];then #nginx重启失败,则停掉keepalived服务,进行vip转移
    killall keepalived     
  fi
fi

Script authorization:chmod 775 check_nginx_pid.sh

Description: The script must be authorized, otherwise There is no 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 visit 192.168.16.130, access through VIP, the page displays 192.168.16.128; indicating that the service is currently provided by the main server.

At this time192.168.16.128The main server executes the command:

systemctl stop nginx; #停止nginx

Visit vip again (192.168.16.130) and find that the page still displays at this time : 192.168.16.128, this is 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 displays 192.168.16.129 At that time, keepalived will automatically failover, 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 How to implement Nginx high availability in production environment. 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
The Advantages of NGINX: Speed, Efficiency, and ControlThe Advantages of NGINX: Speed, Efficiency, and ControlMay 12, 2025 am 12:13 AM

The reason why NGINX is popular is its advantages in speed, efficiency and control. 1) Speed: Adopt asynchronous and non-blocking processing, supports high concurrent connections, and has strong static file service capabilities. 2) Efficiency: Low memory usage and powerful load balancing function. 3) Control: Through flexible configuration file management behavior, modular design facilitates expansion.

NGINX vs. Apache: Community, Support, and ResourcesNGINX vs. Apache: Community, Support, and ResourcesMay 11, 2025 am 12:19 AM

The differences between NGINX and Apache in terms of community, support and resources are as follows: 1. Although the NGINX community is small, it is active and professional, and official support provides advanced features and professional services through NGINXPlus. 2.Apache has a huge and active community, and official support is mainly provided through rich documentation and community resources.

NGINX Unit: An Introduction to the Application ServerNGINX Unit: An Introduction to the Application ServerMay 10, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports a variety of programming languages ​​and frameworks, such as Python, PHP, Java, Go, etc. 1. It supports dynamic configuration and can adjust application configuration without restarting the server. 2.NGINXUnit supports multi-language applications, simplifying the management of multi-language environments. 3. With configuration files, you can easily deploy and manage applications, such as running Python and PHP applications. 4. It also supports advanced configurations such as routing and load balancing to help manage and scale applications.

Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.