k8s-部署Nginx+Keepalived高可用负载均衡器

本文章是 k8s二进制高可用集群部署 的分支。详细步骤请参考目录。

Kubernetes集群高可用性包含以下两个层面的考虑:

  Etcd数据库的高可用性

  Kubernetes Master组件的高可用性

  Master节点扮演着总控中心的角色,通过不断与工作节点上的Kubelet和kube-proxy进行通信来维护整个集群的健康工作状态。如果Master节点故障,将无法使用kubectl工具或者API做任何集群管理。

  Master节点主要有三个服务kube-apiserver、kube-controller-manager和kube-scheduler,其中kube-controller-manager和kube-scheduler组件自身通过选择机制已经实现了高可用,所以Master高可用主要针对kube-apiserver组件,而该组件是以HTTP API提供服务,因此对他高可用与Web服务器类似,增加负载均衡器对其负载均衡即可,并且可水平扩容。

 

  Nginx是一个主流Web服务和反向代理服务器,这里用四层实现对apiserver实现负载均衡。

  Keepalived是一个主流高可用软件,基于VIP绑定实现服务器双机热备,在上述拓扑中,Keepalived主要根据Nginx运行状态判断是否需要故障转移(漂移VIP),例如当Nginx主节点挂掉,VIP会自动绑定在Nginx备节点,从而保证VIP一直可用,实现Nginx高可用。

  注1:为了节省机器,这里与K8s Master节点机器复用。也可以独立于k8s集群之外部署,只要nginx与apiserver能通信就行。

  注2:如果你是在公有云上,一般都不支持keepalived,那么你可以直接用它们的负载均衡器产品,直接负载均衡多台Master kube-apiserver,架构与上面一样。

在两台Master节点操作:

1.安装软件包(主/备)

yum install epel-release -y
yum install nginx keepalived -y
yum -y install nginx-all-modules.noarch

2.Nginx配置文件(主备一样)

cat > /etc/nginx/nginx.conf << "EOF"
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

# 四层负载均衡,为两台Master apiserver组件提供负载均衡
stream {

    log_format  main  '$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent';

    access_log  /var/log/nginx/k8s-access.log  main;

    upstream k8s-apiserver {
       server 192.168.64.130:6443;   # Master1 APISERVER IP:PORT
       server 192.168.64.131:6443;   # Master2 APISERVER IP:PORT
    }
    
    server {
       listen 16443; # 由于nginx与master节点复用,这个监听端口不能是6443,否则会冲突
       proxy_pass k8s-apiserver;
    }
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    server {
        listen       80 default_server;
        server_name  _;

        location / {
        }
    }
}
EOF

3.keepalived配置文件(Nginx Master)

cat > /etc/keepalived/keepalived.conf << EOF
global_defs { 
   notification_email { 
     acassen@firewall.loc 
     failover@firewall.loc 
     sysadmin@firewall.loc 
   } 
   notification_email_from Alexandre.Cassen@firewall.loc  
   smtp_server 127.0.0.1 
   smtp_connect_timeout 30 
   router_id NGINX_MASTER
} 

vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx.sh"
}

vrrp_instance VI_1 { 
    state MASTER 
    interface ens160 # 修改为实际网卡名
    virtual_router_id 51 # VRRP 路由 ID实例,每个实例是唯一的 
    priority 100    # 优先级,备服务器设置 90 
    advert_int 1    # 指定VRRP 心跳包通告间隔时间,默认1秒 
    authentication { 
        auth_type PASS      
        auth_pass 1111 
    }  
    # 虚拟IP
    virtual_ipaddress { 
        192.168.64.134/24
    } 
    track_script {
        check_nginx
    } 
}
EOF

  参数说明:

    vrrp_script:指定检查nginx工作状态脚本(根据nginx状态判断是否故障转移)

    virtual_ipaddress:虚拟IP(VIP节点IP地址)

准备上述配置文件中检查nginx运行状态的脚本:

cat > /etc/keepalived/check_nginx.sh  << "EOF"
#!/bin/bash
count=$(ss -antp |grep 16443 |egrep -cv "grep|$$")

if [ "$count" -eq 0 ];then
    exit 1
else
    exit 0
fi
EOF
chmod +x /etc/keepalived/check_nginx.sh

  注:keepalived根据脚本返回状态码(0为工作正常,非0不正常)判断是否故障转移

4.keepalived配置文件(Nginx Backup)

cat > /etc/keepalived/keepalived.conf << EOF
global_defs { 
   notification_email { 
     acassen@firewall.loc 
     failover@firewall.loc 
     sysadmin@firewall.loc 
   } 
   notification_email_from Alexandre.Cassen@firewall.loc  
   smtp_server 127.0.0.1 
   smtp_connect_timeout 30 
   router_id NGINX_BACKUP
} 

vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx.sh"
}

vrrp_instance VI_1 { 
    state BACKUP 
    interface ens160
    virtual_router_id 51 # VRRP 路由 ID实例,每个实例是唯一的 
    priority 90
    advert_int 1
    authentication { 
        auth_type PASS      
        auth_pass 1111 
    }  
    virtual_ipaddress { 
        192.168.64.134/24
    } 
    track_script {
        check_nginx
    } 
}
EOF

准备上述配置文件中检查nginx运行状态的脚本:

cat > /etc/keepalived/check_nginx.sh  << "EOF"
#!/bin/bash
count=$(ss -antp |grep 16443 |egrep -cv "grep|$$")

if [ "$count" -eq 0 ];then
    exit 1
else
    exit 0
fi
EOF
chmod +x /etc/keepalived/check_nginx.sh

5.启动并设置开机启动

systemctl daemon-reload
systemctl start nginx keepalived
systemctl enable nginx keepalived

6.查看keepalived工作状态

可以看到,在ens160网卡绑定了192.168.64.135 虚拟IP,说明工作正常。

ip a

ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:2e:e4:57 brd ff:ff:ff:ff:ff:ff
altname enp3s0
inet 192.168.64.130/24 brd 192.168.64.255 scope global dynamic noprefixroute ens160
valid_lft 1313sec preferred_lft 1313sec
inet 192.168.64.134/24 scope global secondary ens160
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe2e:e457/64 scope link noprefixroute
valid_lft forever preferred_lft forever

 7.Nginx+Keepalived高可用测试

关闭主节点Nginx,测试VIP是否漂移到备节点服务器。

在Nginx Master执行systemctl stop nginx;

在Nginx Backup,ip addr命令查看已成功绑定VIP。

8.访问负载均衡器测试

找K8s集群中任意一个节点,使用curl查看K8s版本测试,使用VIP访问:

获取一个用户的请求token

#获取访问Token
kubectl -n kubernetes-dashboard create token admin-user

发送请求

curl -k https://192.168.64.134:16443/version  --header 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjhaRFBfWU5nVDh0M1VEcmJhSnh5MGtIeXB6cnpndWFuY2M4Wmx6NHhFR1EifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxNjc3MzM0NzI3LCJpYXQiOjE2NzczMzExMjcsImlzcyI6Imh0dHBzOi8va3ViZXJuZXRlcy5kZWZhdWx0LnN2Yy5jbHVzdGVyLmxvY2FsIiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsInNlcnZpY2VhY2NvdW50Ijp7Im5hbWUiOiJhZG1pbi11c2VyIiwidWlkIjoiMWNkOTMxNjktMjBiOC00MzliLWE0NzktMGI4ODE5MzE3ODkyIn19LCJuYmYiOjE2NzczMzExMjcsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDprdWJlcm5ldGVzLWRhc2hib2FyZDphZG1pbi11c2VyIn0.tUX9yCtFqYow-7-XpT9GNU3SLTFUJOWjIhJ0K-hPM8Jf8vkwRltfinYgDaqvLvgLibmMi7tGMm3sT0hbhnEF-pFLPQ8zuWfoRohCfhebJ8_sgzNYRHwn3sVBvcaHAOjdeXy2_SX62pijm7HG0jfYvRdYzbKiif397fdmwwkqBGZKHNI1LiGW9TkBEipWrceUCkCB1szbIlh9xQpLUpPtHHhHoHCOXArV3v-e5uT7YSheDuanRtH5dvhbaoGlkVK0PmpZxoTKQWgkug65INagEx6NwxEZX2ztWGpCzKgONHW-kYfOB8z1ARACvMc5jjt10FJ13IMeDYCwxJPsgwM6GQ'

得到响应

{
  "major": "1",
  "minor": "26",
  "gitVersion": "v1.26.1",
  "gitCommit": "8f94681cd294aa8cfd3407b8191f6c70214973a4",
  "gitTreeState": "clean",
  "buildDate": "2023-01-18T15:51:25Z",
  "goVersion": "go1.19.5",
  "compiler": "gc",
  "platform": "linux/amd64"
}

可以正确获取到K8s版本信息,说明负载均衡器搭建正常。该请求数据流程:curl -> vip(nginx) -> apiserver

通过查看Nginx日志也可以看到转发apiserver IP:

tail -f /var/log/nginx/k8s-access.log

192.168.64.132 192.168.64.130:6443 - [25/Feb/2023:21:15:12 +0800] 200 869
192.168.64.132 192.168.64.131:6443 - [25/Feb/2023:21:16:00 +0800] 200 869

9.修改所有Worker Node连接LB VIP

试想下,虽然我们增加了Master02 Node和负载均衡器,但是我们是从单Master架构扩容的,也就是说目前所有的Worker Node组件连接都还是Master01 Node,如果不改为连接VIP走负载均衡器,那么Master还是单点故障。

因此接下来就是要改所有Worker Node(kubectl get node命令查看到的节点)组件配置文件,由原来192.168.64.130修改为192.168.64.134(VIP)。

在所有Worker Node执行:

sed -i 's#192.168.64.130:6443#192.168.64.134:16443#' /opt/kubernetes/cfg/*
systemctl restart kubelet kube-proxy

检查节点状态:

kubectl get node 

 

posted @ 2023-02-24 21:48  SpringCore  阅读(2138)  评论(0编辑  收藏  举报