Nginx+Keepalived 기반 고가용성 웹 클러스터 구축 및 모니터링 및 알람 구현

관련 서버 구축

IP 주소 및 클러스터 아키텍처 다이어그램을 계획하고 모든 SELINUX 및 방화벽을 끄십시오.

# 关闭SELINUX
sed -i '/^SELINUX=/ s/enforcing/disabled/' /etc/selinux/config
# 关闭防火墙
service firewalld stop
systemctl disable firewalld

여기에 이미지 설명을 삽입하세요.

웹1 192.168.40.21 백엔드웹
웹2 192.168.40.22 백엔드웹
웹3 192.168.40.23 백엔드웹
lb1 192.168.40.31 로드 밸런서 1
lb2 192.168.40.32 로드 밸런서 2
DNS, 프로메테우스 192.168.40.137 DNS 서버, 모니터링 서버
nfs 192.168.40.138 NFS 서버

DNS 서버 구성

바인드 패키지 설치

yum install bind* -y

명명된 프로세스 시작

[root@elk-node2 selinux]# service named start
Redirecting to /bin/systemctl start named.service
[root@elk-node2 selinux]# ps aux | grep named
named     44018  0.8  3.2 391060 60084 ?        Ssl  15:15   0:00 /usr/sbin/named -u named -c /etc/named.conf
root      44038  0.0  0.0 112824   980 pts/0    S+   15:15   0:00 grep --color=auto named

/etc/resolv.conf 파일을 수정하고 행을 추가한 후 도메인 이름 서버를 이 시스템으로 설정합니다.

nameserver 127.0.0.1

시험. 성공적으로 구문 분석되었습니다.

[root@elk-node2 selinux]#  nslookup 
> www.qq.com
Server:         127.0.0.1
Address:        127.0.0.1#53

Non-authoritative answer:
www.qq.com      canonical name = ins-r23tsuuf.ias.tencent-cloud.net.
Name:   ins-r23tsuuf.ias.tencent-cloud.net
Address: 121.14.77.221
Name:   ins-r23tsuuf.ias.tencent-cloud.net
Address: 121.14.77.201
Name:   ins-r23tsuuf.ias.tencent-cloud.net
Address: 240e:97c:2f:3003::77
Name:   ins-r23tsuuf.ias.tencent-cloud.net
Address: 240e:97c:2f:3003::6a

이 시스템을 다른 시스템이 액세스하고 /etc/named.conf를 수정할 수 있도록 도메인 이름 서버로 사용하십시오.

listen-on port 53 {
    
     any; };
listen-on-v6 port 53 {
    
     any; };
allow-query     {
    
     any; };

서비스 다시 시작

service named restart

이러한 방식으로 다른 시스템은 도메인 이름 확인을 위해 시스템 192.168.40.137을 사용할 수 있습니다.

웹 서버 구성

고정 IP 구성

/etc/sysconfig/network-scripts/디렉토리 입력

ifcfg-ens33 파일을 수정하여 서로 통신이 가능하도록 합니다.

web1IP 구성

BOOTPROTO="none"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.40.21
PREFIX=24
GATEWAY=192.168.40.2
DNS1=114.114.114.114                       

web2IP 구성

BOOTPROTO="none"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.40.22
PREFIX=24
GATEWAY=192.168.40.2
DNS1=114.114.114.114    

web3IP 구성

BOOTPROTO="none"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.40.23
PREFIX=24
GATEWAY=192.168.40.2
DNS1=114.114.114.114    

nginx 컴파일 및 설치

nginx를 컴파일하고 설치하려면 Nginx 설치 시작 및 중지에 대한 내 블로그를 읽어보세요 .

설치 후 브라우저 접속에 성공할 수 있습니다.

로드 밸런서 구성

로드 밸런싱을 위해 nginx 사용

lb1

고정 IP 구성

BOOTPROTO="none"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.40.31
PREFIX=24
GATEWAY=192.168.40.2
DNS1=114.114.114.114

설치 디렉터리의 파일을 수정 nginx.conf하고 다음을 추가합니다.

레이어 7 로드 -> 업스트림은 http 블록에 있으며 http 프로토콜을 기반으로 전달됩니다.

http {
    
    
   ……
    upstream lb1{
    
     # 后端真实的IP地址,在http块里
    ip_hash; # 使用ip_hash算法或least_conn;最小连接
    # 权重 192.168.40.21 weight=5;
	server 192.168.40.21;;
    server 192.168.40.22;
    server 192.168.40.23;
    }
    server {
    
    
        listen       80;
        ……
        location / {
    
    
	    #root   html; 注释掉,因为只是做代理,不是直接访问
        #index  index.html index.htm;
 		proxy_pass http://lb1; # 代理转发    
        }

레이어 4 로드 -> 스트림 블록은 http 블록과 동일한 수준에 있으며 IP+포트를 기반으로 전달됩니다.

stream {
    
    
  upstream lb1{
    
    
        
  }
    server {
    
    
        listen 80; # 基于80端口转发
        proxy_pass lb1;
  }
  upstream dns_servers {
    
    
		least_conn;
		server 192.168.40.21:53;
        server 192.168.40.22:53;
        server 192.168.40.23:53;     
        }
        server {
    
    
        listen 53 udp; # 基于53端口转发
        proxy_pass dns_servers;
   }
}

nginx 다시 로드

nginx -s reload

폴링 알고리즘은 기본적으로 사용되며 효과를 확인할 수 있습니다.

여기에 이미지 설명을 삽입하세요.

여기에 이미지 설명을 삽입하세요.
여기에 이미지 설명을 삽입하세요.

lb2

고정 IP 구성

BOOTPROTO="none"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.40.32
PREFIX=24
GATEWAY=192.168.40.2
DNS1=114.114.114.114

설치 디렉터리의 파일을 수정 nginx.conf하고 다음을 추가합니다.

레이어 7 로드 -> 업스트림은 http 블록에 있으며 http 프로토콜을 기반으로 전달됩니다.

http {
    
    
   ……
    upstream lb2{
    
     # 后端真实的IP地址,在http块里
    ip_hash; # 使用ip_hash算法或least_conn;最小连接
    # 权重 192.168.40.21 weight=5;
	server 192.168.40.21;;
    server 192.168.40.22;
    server 192.168.40.23;
    }
    server {
    
    
        listen       80;
        ……
        location / {
    
    
	    #root   html; 注释掉,因为只是做代理,不是直接访问
        #index  index.html index.htm;
 		proxy_pass http://lb2; # 代理转发    
        }

nginx 다시 로드

nginx -s reload

문제: 백엔드 서버는 실제 접속한 IP 주소는 모르고, 로드밸런서의 IP 주소만 알 수 있는데, 어떻게 해결하나요?

참고 기사

       변수를 사용하여 $remote_addr클라이언트의 IP 주소를 가져와서 X-Real-IP필드에 할당한 다음 다시 로드하세요.

nginx -s reload

여기에 이미지 설명을 삽입하세요.

이 필드의 값을 얻기 위한 모든 백엔드 서버 수정 로그
여기에 이미지 설명을 삽입하세요.

클라이언트의 실제 IP를 얻었는지 확인

여기에 이미지 설명을 삽입하세요.

질문: 레이어 4 로드와 레이어 7 로드의 차이점은 무엇입니까?

참고 기사

  1. 四层负载均衡(Layer 4 Load Balancing): 4계층 로드 밸런싱은 전송 계층(예: 네트워크 계층)에서 로드 밸런싱을 수행하는 방법입니다. 4계층 로드 밸런싱에서는 로드 밸런싱 장치가 源IP地址、目标IP地址、源端口号、目标端口号다른 정보를 바탕으로 해당 서버로 요청을 전달합니다. 기본적으로 네트워크 연결의 기본 속성에만 초점을 맞추고 요청의 내용과 프로토콜에 대한 지식은 없습니다.

    4계층 로드 밸런싱의 장점은 빠른 속도와 높은 효율성이며, TCP, UDP 프로토콜과 같은 다수의 네트워크 연결을 처리하는 데 적합합니다. 그러나 요청 내용에 대한 이해가 제한되어 있으며 특정 애플리케이션의 특정 요구 사항에 따라 전달 전략을 사용자 정의할 수 없습니다.

  2. 七层负载均衡(Layer 7 Load Balancing): 7계층 로드 밸런싱은 애플리케이션 계층에서 로드 밸런싱을 수행하는 방법입니다. 7계층 로드 밸런싱에서 로드 밸런싱 장치는 애플리케이션 계층 프로토콜(예: HTTP, HTTPS)에 깊이 들어가 요청의 내용과 특성을 이해하고 요청에 따라 지능적으로 요청을 전달할 수 있습니다 URL、请求头、会话信息等因素.

    7계층 로드 밸런싱을 통해 더욱 유연하고 맞춤화된 포워딩 전략을 달성할 수 있습니다. 예를 들어 요청은 도메인 이름, URL 경로, 요청 헤더의 특정 정보 등에 따라 다양한 백엔드 서버로 배포될 수 있습니다. 이는 특정 라우팅 규칙과 요구 사항이 있는 웹 애플리케이션, API 서비스 등을 처리할 때 유용합니다.

4계층 로드 밸런싱은 주로 전달을 위한 전송 계층의 네트워크 연결 속성을 기반으로 하며 이는 높은 동시성 및 대규모 네트워크 연결 시나리오에 적합하며, 7계층 로드 밸런싱은 애플리케이션의 요청을 깊이 이해합니다. 계층이며 요청의 내용과 특성을 기반으로 요청하는 데 적합합니다.지능형 전달을 위한 시나리오. 실제 애플리케이션에서는 특정 요구 사항 및 애플리케이션 유형에 따라 적절한 로드 밸런싱 방법을 선택하거나 두 가지를 결합하여 더 나은 성능과 확장성을 얻을 수 있습니다.

고가용성 구성

Keepalived를 사용하여 고가용성 달성

       두 로드 밸런서는 모두 keepalived로 설치되며 둘 사이의 통신은 VRRP 프로토콜을 통해 이루어집니다. VRRP 프로토콜 소개에 대한 참조 문서 입니다.

yum install keepalived

단일 VIP 구성

       구성 파일이 있는 디렉터리를 입력 /etc/keepalived/하고 구성 파일 keepalived.conf를 편집한 후 vrrp 인스턴스를 시작합니다.

lb1 구성

vrrp_instance VI_1 {
    
        #启动一个实例
    state MASTER	    #角色为master
    interface ens33     #网卡接口
    virtual_router_id 150#路由id
    priority 100        #优先级
    advert_int 1        #宣告信息 间隔1s
    authentication {
    
        #认证信息
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
     #虚拟IP,对外提供服务
        192.168.40.51
    }
}

lb2 구성

vrrp_instance VI_1 {
    
    
    state BACKUP #角色为backup
    interface ens33
    virtual_router_id 150
    priority 50  #优先级比master要低
    advert_int 1
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.51
    }
}

Keepalived를 시작하면 우선 순위가 가장 높은 로드 밸런서의 VIP를 볼 수 있습니다.

service keepalived start

더블 VIP 구성

       구성 파일이 있는 디렉터리로 들어가서 /etc/keepalived/구성 파일 keepalived.conf를 편집한 후 두 개의 vrrp를 시작하여 외부 서비스를 제공하여 활용도를 높이세요.

lb1 구성

vrrp_instance VI_1 {
    
        #启动一个实例
    state MASTER       #角色为master
    interface ens33     #网卡接口
    virtual_router_id 150#路由id
    priority 100        #优先级
    advert_int 1        #宣告信息
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.51 # 对外提供的IP
    }
}
vrrp_instance VI_2 {
    
       #启动第二个实例
    state BACKUP      #角色为backup
    interface ens33     #网卡接口
    virtual_router_id 160#路由id
    priority 50         #优先级
    advert_int 1        #宣告信息
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.52 # 对外提供的IP
    }
}

lb2 구성

vrrp_instance VI_1 {
    
    
    state BACKUP  #角色为backup
    interface ens33
    virtual_router_id 150
    priority 50
    advert_int 1
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.51
    }
}
vrrp_instance VI_2 {
    
    
    state MASTER  #角色为master
    interface ens33
    virtual_router_id 160
    priority 100
    advert_int 1
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.52
    }
}

연결 유지를 다시 시작하면 두 로드 밸런서 모두에서 VIP를 볼 수 있습니다.

service keepalived start

       Nginx가 실행 중인지 모니터링하는 스크립트를 작성하세요 check_nginx.sh. Nginx가 중단되면 연결 유지를 켤 필요가 없습니다. 리소스를 소모하고 활성 및 대기 상태를 적시에 조정해야 합니다.

#!/bin/bash
if [[ $(netstat -anplut| grep nginx|wc -l) -eq 1 ]];then
        exit 0
else
        exit 1
        # 关闭keepalived
        service keepalived stop
fi

권한 부여됨

chmod +x check_nginx.sh 

       스크립트가 성공적으로 실행되지 않았습니다. /var/log/messages 로그를 확인하는 동안 문제가 발생했습니다. 스크립트 이름과 괄호 사이에 공백이 없는 것으로 나타났습니다...

여기에 이미지 설명을 삽입하세요.

스크립트 추가 후 lb1 구성

! Configuration File for keepalived

global_defs {
    
    
   notification_email {
    
    
     [email protected]
     [email protected]
     [email protected]
   }
   notification_email_from [email protected]
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
  #vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}
vrrp_script chk_nginx {
    
    
script "/etc/keepalived/check_nginx.sh" # 外部脚本执行位置,使用绝对路径
interval 1
weight -60 # 修改后权重的优先值要小于backup
}

vrrp_instance VI_1 {
    
        #启动一个实例
    state MASTER
    interface ens33     #网卡接口
    virtual_router_id 150#路由id
    priority 100        #优先级
    advert_int 1        #宣告信息
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.51
    }
track_script {
    
     # 脚本名要有空格
chk_nginx # 调用脚本
}

}

vrrp_instance VI_2 {
    
        #启动一个实例
    state BACKUP
    interface ens33     #网卡接口
    virtual_router_id 170#路由id
    priority 50         #优先级
    advert_int 1        #宣告信息
    authentication {
    
    
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    
    
        192.168.40.52
    }
}

lb2의 구성은 lb1과 동일하며, lb2의 마스터 부분에 스크립트에 의해 실행되는 코드를 넣기만 하면 됩니다.

       进行nginx测试,发现双vip能够在nginx关闭的状态同时关闭keepalived并进行vip漂移

       알림 사용에 대한 참조 문서 (연결 유지 종료 효과도 얻을 수 있음)

notify的用法:
  notify_master:当前节点成为master时,通知脚本执行任务(一般用于启动某服务,比如nginx,haproxy等)
  notify_backup:当前节点成为backup时,通知脚本执行任务(一般用于关闭某服务,比如nginx,haproxy等)
  notify_fault:当前节点出现故障,执行的任务; 
  例:当成为master时启动haproxy,当成为backup时关闭haproxy
  notify_master "/etc/keepalived/start_haproxy.sh start"
  notify_backup "/etc/keepalived/start_haproxy.sh stop"

질문: 분할 브레인(split-brain)이란 무엇이며 가능한 원인은 무엇입니까?

       스플릿 브레인 현상은 主备服务器之间的通信故障두 개의 노드가 동시에 마스터 노드라고 생각하고 다음과 같은 이유로 경쟁하는 상황을 말합니다.

  1. 네트워크 분할: Keepalived를 사용하는 클러스터에서 네트워크가 분할되면 마스터 노드와 백업 노드 간의 통신이 중단되어 스플릿 브레인 현상이 발생할 수 있습니다.
  2. 불일치 가상 경로 ID: 가상 경로 ID는 활성 노드와 대기 노드를 고유하게 식별하는 데 사용됩니다. 가상 경로 ID 설정이 일치하지 않으면 서로 다른 노드 간에 충돌이 발생하여 노드가 동시에 활성 노드로 선언될 수 있습니다. , 분할 뇌 현상이 발생합니다.
  3. 认证密码不一样:当认证密码不一致时,节点之间的通信将受阻,可能导致节点无法正常进行状态同步和故障切换,从而引发脑裂现象的发生。
  4. 节点运行状态不同步:当主节点和备份节点之间的状态同步过程中出现错误或延迟,导致节点状态不一致,可能会引发脑裂现象。
  5. 信号丢失:keepalived使用心跳机制检测节点状态,如果由于网络延迟或其他原因导致心跳信号丢失,可能会误判节点状态,从而引发脑裂现象。

问题:keepalived的三个进程?

  1. Keepalived 主进程:负责加载并解析 Keepalived 配置文件,创建和管理 VRRP 实例,并监控实例状态。它还处理与其他 Keepalived 进程之间的通信。
  2. Keepalived VRRP 进程:这是负责实现虚拟路由冗余协议功能的进程。每个启动的 VRRP 实例都会有一个对应的 VRRP 进程。它负责定期发送 VRRP 通告消息,监听其他节点发送的通告消息,并根据配置的优先级进行故障转移。
  3. Keepalived Check Script 进程:这个进程用于执行用户定义的健康检查脚本。通过此进程,可以执行自定义的脚本来检测服务器的健康状态,并根据脚本的返回结果来更改 VRRP 实例的状态或触发故障转移。

NFS服务器配置

       使用nfs,让后端服务器到nfs服务器里获取数据,将nfs的服务器挂载到web服务器上,保证数据一致性

配置静态IP

BOOTPROTO="none"
IPADDR=192.168.40.138
GATEWAY=192.168.40.2
DNS2=114.114.114.114
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"       

安装软件包

yum -y install rpcbind nfs-utils


启动服务,先启动rpc服务,再启动nfs服务

# 启动rpc服务
[root@nfs ~]# service rpcbind start
Redirecting to /bin/systemctl start rpcbind.service
[root@nfs ~]# systemctl enable rpcbind
# 启动nfs服务
[root@nfs ~]# service nfs-server start
Redirecting to /bin/systemctl start nfs-server.service
[root@nfs ~]# systemctl enable nfs-server

新建共享目录

新建/data/share/,自己写一个index.html查看效果

mkdir -p /data/share/

编辑配置文件vim /etc/exports

/data/share/ 192.168.40.0/24(rw,no_root_squash,all_squash,sync)

其中:

  • /data/share/:共享文件目录
  • 192.168.40.0/24:表示接受来自以 192.168.40.0 开头的IP地址范围的请求。
  • (rw):指定允许对目录进行读写操作。
  • no_root_squash:指定不对root用户进行权限限制。它意味着在客户端上以root用户身份访问时,在服务器上也将以root用户身份进行访问。
  • all_squash:指定将所有用户映射为匿名用户。它意味着在客户端上以任何用户身份访问时,在服务器上都将以匿名用户身份进行访问。
  • sync:指定文件系统同步方式。sync 表示在写入操作完成之前,将数据同步到磁盘上。保障数据的一致性和可靠性,但可能会对性能产生影响。

重新加载nfs,让配置文件生效

systemctl reload nfs
exportfs -rv

web服务器挂载

       3台web服务器只需要安装rpcbind服务即可,无需安装nfs或开启nfs服务。

yum install rpcbind -y

web服务器端查看nfs服务器共享目录

[root@web1 ~]# showmount -e 192.168.40.138
Export list for 192.168.40.138:
/data/share 192.168.40.0/24
[root@web2 ~]# showmount -e 192.168.40.138
Export list for 192.168.40.138:
/data/share 192.168.40.0/24
[root@web3 ~]# showmount -e 192.168.40.138
Export list for 192.168.40.138:
/data/share 192.168.40.0/24

进行挂载,挂载到Nginx网页目录下

[root@web1 ~]# mount 192.168.40.138:/data/share /usr/local/shengxia/html
[root@web2 ~]# mount 192.168.40.138:/data/share /usr/local/shengxia/html
[root@web3 ~]# mount 192.168.40.138:/data/share /usr/local/shengxia/html

设置开机自动挂载nfs文件系统

vim /etc/rc.local
# 将这行直接接入/etc/rc.local文件末尾
mount -t nfs 192.168.40.138:/data/share /usr/local/shengxia/html

同时给/etc/rc.d/rc.local可执行权限

chmod /etc/rc.d/rc.local

看到这个效果就表示成功了
여기에 이미지 설명을 삽입하세요.

监控服务器配置

       下载prometheus和exporter进行监控,安装可以看我这篇博客
Prometheus、Grafana、cAdvisor的介绍、安装和使用

安装node-exporter

       prometheus安装好之后,在每个服务器都安装node-exporter,监控服务器状态 下载

       除了本机192.168.40.137以外,所有的服务器都下载,演示一个案例。其他服务器相同操作

解压文件

[root@web1 exporter]# ls
node_exporter-1.5.0.linux-amd64.tar.gz
[root@web1 exporter]# tar xf node_exporter-1.5.0.linux-amd64.tar.gz 
[root@web1 exporter]# ls
node_exporter-1.5.0.linux-amd64  node_exporter-1.5.0.linux-amd64.tar.gz

新建目录

[root@web1 exporter]# mkdir -p /node_exporter

复制node_exporter下的文件到指定的目录

[root@web1 exporter]# cp node_exporter-1.5.0.linux-amd64/* /node_exporter

/root/.bashrc文件下修改PATH环境变量,将这行加到文件末尾,刷新一下

PATH=/node_exporter/:$PATH
source /root/.bashrc

放到后台启动运行

[root@web1 exporter]# nohup node_exporter --web.listen-address 192.168.40.21:8899 &

出现这个页面即成功

여기에 이미지 설명을 삽입하세요.

编写prometheus.yml

scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["192.168.40.137:9090"]
  - job_name: "nfs"
    static_configs:
      - targets: ["192.168.40.138:8899"]
  - job_name: "lb1"
    static_configs:
      - targets: ["192.168.40.31:8899"]
  - job_name: "lb2"
    static_configs:
      - targets: ["192.168.40.32:8899"]
  - job_name: "web1"
    static_configs:
      - targets: ["192.168.40.21:8899"]
  - job_name: "web2"
    static_configs:
      - targets: ["192.168.40.22:8899"]
  - job_name: "web3"
    static_configs:
      - targets: ["192.168.40.23:8899"]

重新启动prometheus

[root@dns-prom prometheus]# service prometheus restart

看到这个页面就表示监控成功了

여기에 이미지 설명을 삽입하세요.

安装alertmanager和钉钉插件

下载

[root@dns-prom prometheus]# wget https://github.com/prometheus/alertmanager/releases/download/v0.25.0/alertmanager-0.25.0.linux-amd64.tar.gz
[root@dns-prom prometheus]# wget https://github.com/timonwong/prometheus-webhook-dingtalk/releases/download/v1.4.0/prometheus-webhook-dingtalk-1.4.0.linux-amd64.tar.gz

解压

[root@dns-prom prometheus]# tar xf alertmanager-0.23.0-rc.0.linux-amd64.tar.gz 
[root@dns-prom prometheus]# mv alertmanager-0.23.0-rc.0.linux-amd64 alertmanager
[root@dns-prom prometheus]# tar xf prometheus-webhook-dingtalk-1.4.0.linux-amd64.tar.gz 
[root@dns-prom prometheus]# mv prometheus-webhook-dingtalk-1.4.0.linux-amd64 prometheus-webhook-dingtalk

获取机器人webhook

여기에 이미지 설명을 삽입하세요.

获取允许访问的IP,使用curl ifconfig.me可以获得

[root@dns-prom alertmanager]# curl ifconfig.me
222.244.215.17

여기에 이미지 설명을 삽입하세요.

DingTalk 알림 템플릿 수정

#位置:/lianxi/prometheus/prometheus-webhook-dingtalk/contrib/templates/legacy/template.tmpl
[root@dns-prom legacy]# cat template.tmpl
{
    
    {
    
     define "ding.link.title" }}{
    
    {
    
     template "legacy.title" . }}{
    
    {
    
     end }}
{
    
    {
    
     define "ding.link.content" }}
{
    
    {
    
     if gt (len .Alerts.Firing) 0 -}}
告警列表:
{
    
    {
    
     template "__text_alert_list" .Alerts.Firing }}
{
    
    {
    
    - end }}
{
    
    {
    
     if gt (len .Alerts.Resolved) 0 -}}
恢复列表:
{
    
    {
    
     template "__text_resolve_list" .Alerts.Resolved }}
{
    
    {
    
    - end }}
{
    
    {
    
    - end }}

cofig 및 yml 파일 수정, 로봇의 웹훅 토큰 추가, 템플릿 파일 지정

[root@dns-prom prometheus-webhook-dingtalk]# cat config.yml 
templates:
  - /lianxi/prometheus/prometheus-webhook-dingtalk/contrib/templates/legacy/template.tmpl # 模板路径

targets:
  webhook2:
    url: https://oapi.dingtalk.com/robot/send?access_token=你自己的token

prometheus-webhook-dingtalk서비스로 등록 됩니다

[root@dns-prom system]# pwd
/usr/lib/systemd/system
[root@dns-prom system]# cat webhook-dingtalk
[Unit]
Description=prometheus-webhook-dingtalk
Documentation=https://github.com/timonwong/prometheus-webhook-dingtalk
After=network.target

[Service]
ExecStart=/lianxi/prometheus/prometheus-webhook-dingtalk/prometheus-webhook-dingtalk  --config.file=/lianxi/prometheus/prometheus-webhook-dingtalk/config.yml
Restart=on-failure

[Install]
WantedBy=multi-user.target

서비스 로드 중

[root@dns-prom system]# systemctl daemon-reload

서비스 시작

[root@dns-prom system]# service webhook-dingtalk start
Redirecting to /bin/systemctl start webhook-dingtalk.service

경고 관리자 작성

alertmanager.yml파일 수정

global:
  resolve_timeout: 5m

route: # 告警路由配置,定义如何处理和发送告警
  receiver: webhook
  group_wait: 30s
  group_interval: 1m
  repeat_interval: 4h
  group_by: [alertname]
  routes:
  - receiver: webhook
    group_wait: 10s

receivers: # 告警接收者配置,定义如何处理和发送告警
- name: webhook 
  webhook_configs:
   ### 注意注意,我在dingtalk的配置文件里用的是webhook2,要对上
  - url: http://192.168.40.137:8060/dingtalk/webhook2/send  # 告警 Webhook URL
    send_resolved: true # 是否发送已解决的告警。如果设置为 true,则在告警解决时发送通知

alertmanager서비스로 등록 됩니다

[Unit]
Description=alertmanager
Documentation=https://prometheus.io/
After=network.target

[Service]
ExecStart=/lianxi/prometheus/alertmanager/alertmanager --config.file=/lianxi/prometheus/alertmanager/alertmanager.yml 
Restart=on-failure

[Install]
WantedBy=multi-user.target

서비스 로드 중

[root@dns-prom system]# systemctl daemon-reload

확인하다

여기에 이미지 설명을 삽입하세요.

알람 파일 설정

prometheus 디렉터리의 rule.yml 파일에 경보 규칙을 생성합니다.

[root@dns-prom prometheus]# pwd
/lianxi/prometheus/prometheus
[root@dns-prom prometheus]# cat rules.yml 
groups:
  - name: host_monitoring
    rules:
      - alert: 内存报警
        expr: netdata_system_ram_MiB_average{
    
    chart="system.ram",dimension="free",family="ram"} < 800
        for: 2m
        labels:
          team: node
        annotations:
          Alert_type: 内存报警
          Server: '{
    
    {$labels.instance}}'
          explain: "内存使用量超过90%,目前剩余量为:{
    
    { $value }}M"
      - alert: CPU报警
        expr: netdata_system_cpu_percentage_average{
    
    chart="system.cpu",dimension="idle",family="cpu"} < 20
        for: 2m
        labels:
          team: node
        annotations:
          Alert_type: CPU报警
          Server: '{
    
    {$labels.instance}}'
          explain: "CPU使用量超过80%,目前剩余量为:{
    
    { $value }}"
      - alert: 磁盘报警
        expr: netdata_disk_space_GiB_average{
    
    chart="disk_space._",dimension="avail",family="/"} < 4
        for: 2m
        labels:
          team: node
        annotations:
          Alert_type: 磁盘报警
          Server: '{
    
    {$labels.instance}}'
          explain: "磁盘使用量超过90%,目前剩余量为:{
    
    { $value }}G"
      - alert: 服务告警
        expr: up == 0
        for: 2m
        labels:
          team: node
        annotations:
          Alert_type: 服务报警
          Server: '{
    
    {$labels.instance}}'
          explain: "netdata服务已关闭"

prometheus.yml 파일을 수정하고 alertmanager이를 다음과 연결합니다.

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["192.168.40.137:9093"]

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  - "/lianxi/prometheus/prometheus/rules.yml" # 告警模板路径
  # - "first_rules.yml"
  # - "second_rules.yml"

프로메테우스 서비스 다시 시작

[root@dns-prom prometheus]# service prometheus restart

모니터링 데이터를 볼 수 있습니다.

여기에 이미지 설명을 삽입하세요.

서버 다운타임을 시뮬레이션하고, web1을 닫고, 알람을 울립니다.

여기에 이미지 설명을 삽입하세요.

딩톡이 경고를 받았습니다

여기에 이미지 설명을 삽입하세요.

그라파나 설치

Grafana 공식 웹사이트에서 Grafana 소프트웨어 패키지를 다운로드하고 공식 문서에 따라 설치하십시오.

root@dns-prom grafana]# yum install -y https://dl.grafana.com/enterprise/release/grafana-enterprise-9.5.1-1.x86_64.rpm

그라파나 시작

[root@dns-prom grafana]# service grafana-server restart
Restarting grafana-server (via systemctl):                 [  确定  ]

구체적인 운영 프로세스는 Prometheus, Grafana 및 cAdvisor의 소개, 설치 및 사용 문서를 참조하세요.

좋은 템플릿을 선택하면 표시할 수 있습니다.

여기에 이미지 설명을 삽입하세요.

여기에 이미지 설명을 삽입하세요.

스트레스 테스트 실시

ab 소프트웨어 설치 및 요청 시뮬레이션

yum install ab -y

클러스터 동시성 수를 이해하기 위해 요청을 지속적으로 시뮬레이션합니다.

추천

출처blog.csdn.net/qq_52589631/article/details/131837458