安装keepalive+nginx 实现 k8s apiserver高可用


  1. 绑定hosts

  2. 配置 epel 源 

    yum install -y epel-release

  3. 安装 nginx keepalived 

    yum install nginx nginx-mod-stream  keepalived -y 


  4. 修改 nginx 配置
    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 172.31.24.31:6443;   # Master1 APISERVER IP:PORT
           server 172.31.24.32:6443;   # Master2 APISERVER IP:PORT
           server 172.31.24.33:6443;   # Master3 APISERVER IP:PORT
        }
        
        server {
           listen 16443;
           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;
    
    }
  5. 修改keepalive配置
    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 eth0
        virtual_router_id 51 # VRRP 路由 ID实例,每个实例是唯一的 
        priority 90
        advert_int 1
        authentication { 
            auth_type PASS      
            auth_pass 1111 
        }  
        virtual_ipaddress { 
            172.31.24.230/24
        } 
        track_script {
            check_nginx
        } 
    }
  6. 配置nginx健康检查脚本

    vim /etc/keepalived/check_nginx.sh
    #!/bin/bash
    count=$(ps -ef |grep nginx | grep sbin | egrep -cv "grep|$$")
    if [ "$count" -eq 0 ];then
    systemctl stop keepalived
    fi

    chmod +x /etc/keepalived/check_nginx.sh

  7. 启动服务

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

  8. 测试浮动 vip