Use keepalived as software load balancer during kubernetes installation

One of the common infrastructure requirements before installing any Kubernetes variant is to set up a load balancer in front of the controlplane nodes, which will be the entry point of the cluster. In this article, I will use keepalived software on the same three nodes to set up a software load balancer.

I will use two additional scripts to help keepalived vote correctly. One script will check for port 6443 availability, which is required for the Kubernetes API to work. The other script will add voting weights for a node that also has port 443 ingress enabled. If you don't need port 443, just comment it out.

# cat /usr/local/bin/check_443_port
#!/bin/bash
/usr/bin/curl -k --silent --max-time 2 -o /dev/null -w "%{http_code}" https://127.0.0.1:443/healthz | grep -q 200
# cat /usr/local/bin/check_6443_port
#!/bin/bash
/usr/bin/curl -k --silent --max-time 2 -o /dev/null https://127.0.0.1:6443/healthz
# cat /etc/keepalived/keepalived.conf
global_defs {
    script_user nobody
    vrrp_skip_check_adv_addr
    vrrp_garp_interval 0
    vrrp_gna_interval 0
}

vrrp_script check_6443_port {
    script /usr/local/bin/check_6443_port
    interval 2
    timeout 3
    weight 50
    rise 1
    fall 2
}

vrrp_script check_443_port {
    script /usr/local/bin/check_443_port
    interval 2
    timeout 3
    weight 25
    rise 1
    fall 2
}

vrrp_instance VIp {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 50
    advert_int 1
    virtual_ipaddress {
        10.255.255.9/24
    }
    track_script {
        check_6443_port
        check_443_port
    }
}

Description:

A virtual IP address is started on each node with a low (BACKUP) priority and tries to become the MASTER. In case of a tie, the node with the highest IP address wins and gets the VIP.

The helper script check_6443_port will add a weight of 50 for a working node or decrease it for an inactive node. The resulting votes can then be 100 or 0 respectively.

Another helper script check_433_port adjusts the priority with a smaller weight of 25. The resulting votes can be 0, 25, 75, 125 and the highest one wins.


Updated on Mon May 5 13:19:27 IDT 2025 More documentations here