NGINX achieves high availability under Linux

angryTom
Release: 2019-11-25 16:01:53
Original
3383 people have browsed it

NGINX achieves high availability under Linux

1. Install NGINX on Linux

Under Centos, the yum source does not provide nginx installation, you can switch Obtain and install using the yum source method. You can also directly download the installation package. The following commands require root permissions to execute: first install the necessary libraries (the gzip module in nginx requires the zlib library, the rewrite module requires the pcre library, and the ssl function requires the openssl library). Select /usr/local as the installation directory, and the following specific version numbers will change based on actual conditions.

1.1. Install PCRE library

$ cd /usr/local/
$ wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.36.tar.gz
$ tar -zxvf pcre-8.36.tar.gz
$ cd pcre-8.36
$ ./configure
$ make
$ make install
Copy after login

./configure error reporting(recommended learning: nginx tutorial)

configure: error: You need a C++ compile
r for C++ support.
Copy after login

Solution: yum install -y gccgcc-c

1.2. Install zlib library

$ cd /usr/local/ 
$ wget http://zlib.net/zlib-1.2.8.tar.gz
$ tar -zxvf zlib-1.2.8.tar.gz
$ cd zlib-1.2.8
$ ./configure
$ make
$ make install
Copy after login

1.3. Install ssl

$ cd /usr/local/
$ wget http://www.openssl.org/source/openssl-1.0.1j.tar.gz
$ tar -zxvf openssl-1.0.1j.tar.gz
$ ./config
$ make
$ make install
Copy after login

1.3. Install NGINX

$ cd /usr/local/
$ wget http://nginx.org/download/nginx-1.8.0.tar.gz
$ tar -zxvf nginx-1.8.0.tar.gz
$ cd nginx-1.8.0  
$ ./configure --prefix=/usr/local/nginx
$ make
$ make install
Copy after login

Common installation errors:

Nginx startup prompt cannot find libpcre.so.1 solution

If it is a 32-bit system

[root@lee ~]#  ln -s /usr/local/lib/libpcre.so.1 /lib
Copy after login

If it is a 64-bit system

[root@lee ~]#  ln -s /usr/local/lib/libpcre.so.1 /lib64
Copy after login

Then start nginx It’s OK

[root@lee ~]# /usr/local/webserver/nginx/sbin/nginx
Copy after login

1.4. Start NGINX

$ /usr/local/nginx/sbin/nginx
Copy after login

Open the browser to access the IP of this machine. If the browser displays Welcome to nginx!, it means that Nginx has been installed and Run successfully.

2. Common NGINX commands

重启:
$ /usr/local/nginx/sbin/nginx 启动命令
重启:
$ /usr/local/nginx/sbin/nginx –s reload
停止:
$ /usr/local/nginx/sbin/nginx –s stop
测试配置文件是否正常:
$ /usr/local/nginx/sbin/nginx –t 
强制关闭:
$ pkillnginx
Copy after login

3. Start Nginx Keepalived

3.1. What is Keepalived

Keepalived is a free and open source software written in C similar to layer3, 4 & 7 switching mechanism. It has the functions of layer 3, layer 4 and layer 7 switches that we usually talk about. . It mainly provides loadbalancing (load balancing) and high-availability (high availability) functions. The implementation of load balancing requires relying on Linux's virtual service kernel module (ipvs), while high availability is through VRRP The protocol implements failover services between multiple machines.

 

The above picture is the functional architecture of Keepalived, which is roughly divided into two layers: user space and kernel space.

Kernel space: Mainly includes two parts: IPVS (IP virtual server, used to realize load balancing of network services) and NETLINK (providing advanced routing and other related network functions).

User Space:

  • WatchDog: Load monitoring checkers and the status of the VRRP process
  • VRRP Stack: Load between load balancers FailOver, VRRP is not necessary if only one load equalizer is used.
  • Checkers: Responsible for health checking of the real server, which is the main function of keepalived. In other words, there can be no VRRP Stack, but healthchecking is a must.
  • IPVS wrapper: The user sends the set rules to the kernel ipvs code
  • Netlink Reflector: used to set the vip address of vrrp, etc.

All functions of Keepalived are implemented by configuring the keepalived.conf file.

3.2. Install Keepalived

Download keepalived address: http://www.keepalived.org/download.html

Unzip and install:

tar -zxvf keepalived-1.2.18.tar.gz -C /usr/local/
yum install -yopensslopenssl-devel(需要安装一个软件包)
cd keepalived-1.2.18/ && ./configure --prefix=/usr/local/keepalived
make&& make install
Copy after login

3.3. Install Keepalived as a Linux system service

将keepalived安装成Linux系统服务,因为没有使用keepalived的默认安装路径(默认路径:/usr/local),安装完成之后,需要做一些修改工作:
首先创建文件夹,将keepalived配置文件进行复制:
mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf  /etc/keepalived/
然后复制keepalived脚本文件:
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived  /etc/init.d/
cp /usr/local/keepalived/etc/sysconfig/keepalived  /etc/sysconfig/
ln -s /usr/local/sbin/keepalived /usr/sbin/
ln -s /usr/local/keepalived/sbin/keepalived /sbin/
可以设置开机启动:chkconfigkeepalived on,到此我们安装完毕!
Copy after login

3.4. Common Keepalived commands

servicekeepalived start
servicekeepalived stop
Copy after login

4. Keepalived configuration

4.1. Configure NGINX’s active and backup automatic restart

1. Modify the configuration file:vim /etc /keepalived/keepalived.conf

1) Modify master NGINX configuration

<span style="color: #000000;">! Configuration File for keepalived
global_defs {
    router_id bhz005 ##标识节点的字符串,通常为hostname
}
## keepalived会定时执行脚本并且对脚本的执行结果进行分析,动态调整vrrp_instance的优先级。这里的权重weight 是与下面的优先级priority有关,如果执行了一次检查脚本成功,则权重会-20,也就是由100 - 20 <br/>变成了80,Master 的优先级为80 就低于了Backup的优先级90,那么会进行自动的主备切换。
如果脚本执行结果为0并且weight配置的值大于0,则优先级会相应增加。
如果脚本执行结果不为0 并且weight配置的值小于0,则优先级会相应减少。
vrrp_scriptchk_nginx {
    script "/etc/keepalived/nginx_check.sh" ##执行脚本位置
    interval 2 ##检测时间间隔
    weight -20 ## 如果条件成立则权重减20(-20)
}
## 定义虚拟路由 VI_1为自定义标识。
vrrp_instance VI_1 {
state MASTER   ## 主节点为MASTER,备份节点为BACKUP
## 绑定虚拟IP的网络接口(网卡),与本机IP地址所在的网络接口相同(我这里是eth6)
interface eth6  
virtual_router_id 172  ## 虚拟路由ID号
mcast_src_ip 192.168.1.172  ## 本机ip地址
priority 100  ##优先级配置(0-254的值)
Nopreempt  ## 
advert_int 1 ## 组播信息发送间隔,俩个节点必须配置一致,默认1s
authentication {  
auth_type PASS
auth_passbhz ## 真实生产环境下对密码进行匹配
    }

track_script {
chk_nginx
    }

virtual_ipaddress {
        192.168.1.170 ## 虚拟ip(vip),可以指定多个
    }
}</span>
Copy after login

2) Modify Backup NGINX configuration

! Configuration File for keepalived

global_defs {
router_id bhz006
}

vrrp_scriptchk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight -20
}

vrrp_instance VI_1 {
state BACKUP
interface eth7
virtual_router_id 173
mcast_src_ip 192.168.1.173
priority 90 ##优先级配置
advert_int 1
authentication {
auth_type PASS
auth_passbhz
    }

track_script {
chk_nginx
    }

virtual_ipaddress {
        192.168.1.170
    }
}
Copy after login

3) nginx_check.sh script

#!/bin/bash
A=`ps -C nginx–no-header |wc -l`
if [ $A -eq 0 ];then
    /usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killallkeepalived
fi
fi
Copy after login

4) Then copy the master's keepalived configuration file to the /etc/keepalived/ folder of the master machine (172), and then copy the backup's keepalived configuration file to the /etc/keepalived/ of the backup machine (173). folder, and finally copy the nginx_check.sh script to the /etc/keepalived/ folder of the two machines.

5) nginx_check.sh script authorization. Grant executable permissions: chmod x /etc/keepalived/nginx_check.sh

6) After starting nginx on 2 machines. Let’s start keepalived

/usr/local/nginx/sbin/nginx
servicekeepalived start
ps -ef | grepnginx
ps -ef | grepkeepalived
Copy after login

7 on both machines. Take a look at the IP addresses of the two machines. A virtual IP will appear under the a command. Test without closing Keepalived, kill NGINX, and then observe whether it restarts. Turn off Keepalived, kill NGINX, and then check whether it restarts.

5. Session sharing solution in cluster situation

5.1. What causes session in cluster situation?

Due to session storage On the server side, users in the cluster may access different servers, so sessions may not be shared.

5.2, Session sharing solution

1)NGINX做的负载均衡可以绑定ip_hash,从而使同一个IP访问同一个服务器 ------------------该方案使得集群失去意义。

2)利用数据库同步session----------------------太过复杂

3)利用cookie同步session(保存一个session到本地,再次访问将其带到服务器端)----------------------安全性差、http请求都需要带参数增加了带宽消耗

4)使用session集群,存放到redis中(spring-session)

5.3、spring-session项目,解决session共享问题

<!--spring boot 与redis应用基本环境配置 -->
<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>
    <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
    <dependency>  
    <groupId>org.springframework.session</groupId>  
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
Copy after login

创建SessionConfig

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
//这个类用配置redis服务器的连接
//maxInactiveIntervalInSeconds为SpringSession的过期时间(单位:秒)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
Public class SessionConfig {    
// 冒号后的值为没有配置文件时,制动装载的默认值
    @Value("${redis.hostname:localhost}")
    String HostName;
    @Value("${redis.port:6379}")    int Port;
    @Bean
    Public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory connection = new JedisConnectionFactory();
        connection.setPort(Port);
        connection.setHostName(HostName);        return connection;
    }
}
Copy after login

初始化Session

//初始化Session配置Public class SessionInitializer extends AbstractHttpSessionApplicationInitializer{
  Public SessionInitializer() {
    super(SessionConfig.class);
    }
}
Copy after login

控制层代码

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestControllerpublic class SessionController {

    @Value("${server.port}")    
    private String PORT;

    @RequestMapping("/index")    
    public String index() {        
        return "index:" + PORT;
    }    
    /**
     * @methodDesc: 功能描述:(往session存放值)     
     */
    @RequestMapping("/setSession")    
    public String setSession(HttpServletRequest request, String sessionKey, String sessionValue) {
        HttpSession session = request.getSession(true);
        session.setAttribute(sessionKey, sessionValue);        
        return "success,port:" + PORT;
    }    
    /**
     * @methodDesc: 功能描述:(从Session获取值)     
     */
    @RequestMapping("/getSession")    
    public String getSession(HttpServletRequest request, String sessionKey) {
        HttpSession session =null;        
        try {
         session = request.getSession(false);
        } catch (Exception e) {
        e.printStackTrace();
        }
        String value=null;        
        if(session!=null){
            value = (String) session.getAttribute(sessionKey);
        }        
        return "sessionValue:" + value + ",port:" + PORT;
    }

}
Copy after login

 六、高并发解决方案

   业务数据库  -》 数据水平分割(分区分表分库)、读写分离

  业务应用 -》 逻辑代码优化(算法优化)、公共数据缓存

  应用服务器 -》 反向静态代理、配置优化、负载均衡(apache分发,多tomcat实例)

  系统环境 -》 JVM调优

  页面优化 -》 减少页面连接数、页面尺寸瘦身

  动态资源和静态资源分离

  CDN加速

  服务分布式部署

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

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!