Set up a highly available Kubernetes cluster using kubeadm

240 words
This article documents how to build a highly available Kubernetes cluster using the kubeadm tool, primarily implementing high availability architecture for master nodes through the combination of keepalived+haproxy. The entire deployment is based on CentOS 7 system, with Kubernetes version 1.16.3.

kubeadm is the official cluster deployment tool launched by Kubernetes, which allows you to quickly set up a production-grade Kubernetes cluster with simple commands.

1. Environment Requirements

  • Operating System: CentOS 7.x-86_x64
  • Hardware Configuration: 2GB+ RAM, 2+ CPU, 30GB+ Disk
  • Network Requirements: Able to access the internet to pull images
  • Other Requirements: Disable swap partitions

2. Cluster Planning

RoleIP AddressNotes
master1192.168.44.155Primary control node
master2192.168.44.156Standby control node
node1192.168.44.157Worker node
VIP192.168.44.158Virtual IP

3. Basic Environment Configuration

Execute the following operations on all nodes:

bash
# Disable firewall and SELinux
systemctl stop firewalld && systemctl disable firewalld
sed -i 's/enforcing/disabled/' /etc/selinux/config && setenforce 0

# Disable swap
swapoff -a && sed -ri 's/.*swap.*/#&/' /etc/fstab

# Configure hostname and hosts file
hostnamectl set-hostname <corresponding hostname>
cat >> /etc/hosts << EOF
192.168.44.158    master.k8s.io
192.168.44.155    master01.k8s.io
192.168.44.156    master02.k8s.io
192.168.44.157    node01.k8s.io
EOF

# Configure kernel parameters
cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system

# Time synchronization
yum install ntpdate -y && ntpdate time.windows.com
# Disable firewall and SELinux
systemctl stop firewalld && systemctl disable firewalld
sed -i 's/enforcing/disabled/' /etc/selinux/config && setenforce 0

# Disable swap
swapoff -a && sed -ri 's/.*swap.*/#&/' /etc/fstab

# Configure hostname and hosts file
hostnamectl set-hostname <corresponding hostname>
cat >> /etc/hosts << EOF
192.168.44.158    master.k8s.io
192.168.44.155    master01.k8s.io
192.168.44.156    master02.k8s.io
192.168.44.157    node01.k8s.io
EOF

# Configure kernel parameters
cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system

# Time synchronization
yum install ntpdate -y && ntpdate time.windows.com

4. Configure High Availability Load Balancing

4.1 Install keepalived

Install keepalived on the two master nodes:

bash
yum install -y keepalived
yum install -y keepalived

master1 Configuration (/etc/keepalived/keepalived.conf):

bash
cat > /etc/keepalived/keepalived.conf <<EOF 
global_defs {
   router_id k8s
}

vrrp_script check_haproxy {
    script "killall -0 haproxy"
    interval 3
    weight -2
    fall 10
    rise 2
}

vrrp_instance VI_1 {
    state MASTER 
    interface ens33 
    virtual_router_id 51
    priority 250
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass ceb1b3ec013d66163d6ab
    }
    virtual_ipaddress {
        192.168.44.158
    }
    track_script {
        check_haproxy
    }
}
EOF
cat > /etc/keepalived/keepalived.conf <<EOF 
global_defs {
   router_id k8s
}

vrrp_script check_haproxy {
    script "killall -0 haproxy"
    interval 3
    weight -2
    fall 10
    rise 2
}

vrrp_instance VI_1 {
    state MASTER 
    interface ens33 
    virtual_router_id 51
    priority 250
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass ceb1b3ec013d66163d6ab
    }
    virtual_ipaddress {
        192.168.44.158
    }
    track_script {
        check_haproxy
    }
}
EOF

master2 Configuration: Same as master1, but change state BACKUP and priority 200.

Start keepalived:

bash
systemctl enable keepalived && systemctl start keepalived
systemctl enable keepalived && systemctl start keepalived

4.2 Install HAProxy

Install and configure HAProxy on the two master nodes:

bash
yum install -y haproxy

cat > /etc/haproxy/haproxy.cfg << EOF
global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend kubernetes-apiserver
    mode                 tcp
    bind                 *:16443
    option               tcplog
    default_backend      kubernetes-apiserver

backend kubernetes-apiserver
    mode        tcp
    balance     roundrobin
    server      master01.k8s.io   192.168.44.155:6443 check
    server      master02.k8s.io   192.168.44.156:6443 check

listen stats
    bind                 *:1080
    stats auth           admin:awesomePassword
    stats refresh        5s
    stats realm          HAProxy\ Statistics
    stats uri            /admin?stats
EOF

systemctl enable haproxy && systemctl start haproxy
yum install -y haproxy

cat > /etc/haproxy/haproxy.cfg << EOF
global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend kubernetes-apiserver
    mode                 tcp
    bind                 *:16443
    option               tcplog
    default_backend      kubernetes-apiserver

backend kubernetes-apiserver
    mode        tcp
    balance     roundrobin
    server      master01.k8s.io   192.168.44.155:6443 check
    server      master02.k8s.io   192.168.44.156:6443 check

listen stats
    bind                 *:1080
    stats auth           admin:awesomePassword
    stats refresh        5s
    stats realm          HAProxy\ Statistics
    stats uri            /admin?stats
EOF

systemctl enable haproxy && systemctl start haproxy

5. Install Container Runtime and Kubernetes Components

Execute on all nodes:

5.1 Install Docker

bash
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
yum install -y docker-ce-18.06.1.ce-3.el7

cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com"]
}
EOF

systemctl enable docker && systemctl start docker
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
yum install -y docker-ce-18.06.1.ce-3.el7

cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com"]
}
EOF

systemctl enable docker && systemctl start docker

5.2 Install kubeadm, kubelet, kubectl

bash
cat > /etc/yum.repos.d/kubernetes.repo << EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum install -y kubelet-1.16.3 kubeadm-1.16.3 kubectl-1.16.3
systemctl enable kubelet
cat > /etc/yum.repos.d/kubernetes.repo << EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum install -y kubelet-1.16.3 kubeadm-1.16.3 kubectl-1.16.3
systemctl enable kubelet

6. Initialize Kubernetes Cluster

6.1 Create Cluster Configuration File

Create kubeadm configuration file on the master1 node:

bash
mkdir -p /usr/local/kubernetes/manifests && cd /usr/local/kubernetes/manifests

cat > kubeadm-config.yaml << EOF
apiServer:
  certSANs:
    - master1
    - master2
    - master.k8s.io
    - 192.168.44.158
    - 192.168.44.155
    - 192.168.44.156
    - 127.0.0.1
  extraArgs:
    authorization-mode: Node,RBAC
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta1
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controlPlaneEndpoint: "master.k8s.io:16443"
controllerManager: {}
dns: 
  type: CoreDNS
etcd:
  local:  
    dataDir: /var/lib/etcd
imageRepository: registry.aliyuncs.com/google_containers
kind: ClusterConfiguration
kubernetesVersion: v1.16.3
networking: 
  dnsDomain: cluster.local
  podSubnet: 10.244.0.0/16
  serviceSubnet: 10.1.0.0/16
scheduler: {}
EOF
mkdir -p /usr/local/kubernetes/manifests && cd /usr/local/kubernetes/manifests

cat > kubeadm-config.yaml << EOF
apiServer:
  certSANs:
    - master1
    - master2
    - master.k8s.io
    - 192.168.44.158
    - 192.168.44.155
    - 192.168.44.156
    - 127.0.0.1
  extraArgs:
    authorization-mode: Node,RBAC
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta1
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controlPlaneEndpoint: "master.k8s.io:16443"
controllerManager: {}
dns: 
  type: CoreDNS
etcd:
  local:  
    dataDir: /var/lib/etcd
imageRepository: registry.aliyuncs.com/google_containers
kind: ClusterConfiguration
kubernetesVersion: v1.16.3
networking: 
  dnsDomain: cluster.local
  podSubnet: 10.244.0.0/16
  serviceSubnet: 10.1.0.0/16
scheduler: {}
EOF

6.2 Initialize the First Master Node

bash
kubeadm init --config kubeadm-config.yaml

# Configure kubectl
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config
kubeadm init --config kubeadm-config.yaml

# Configure kubectl
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config

Record the output join command for later use when adding nodes.

6.3 Install Network Plugin

bash
wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f kube-flannel.yml
wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f kube-flannel.yml

7. Add the Second Master Node

7.1 Copy Certificate Files

Copy necessary files from master1 to master2:

bash
ssh [email protected] mkdir -p /etc/kubernetes/pki/etcd
scp /etc/kubernetes/admin.conf [email protected]:/etc/kubernetes
scp /etc/kubernetes/pki/{ca.*,sa.*,front-proxy-ca.*} [email protected]:/etc/kubernetes/pki
scp /etc/kubernetes/pki/etcd/ca.* [email protected]:/etc/kubernetes/pki/etcd
ssh [email protected] mkdir -p /etc/kubernetes/pki/etcd
scp /etc/kubernetes/admin.conf [email protected]:/etc/kubernetes
scp /etc/kubernetes/pki/{ca.*,sa.*,front-proxy-ca.*} [email protected]:/etc/kubernetes/pki
scp /etc/kubernetes/pki/etcd/ca.* [email protected]:/etc/kubernetes/pki/etcd

7.2 Join the Cluster

Execute the join command on the master2 node (add --control-plane parameter):

bash
kubeadm join master.k8s.io:16443 --token <token> \
    --discovery-token-ca-cert-hash sha256:<hash> \
    --control-plane
kubeadm join master.k8s.io:16443 --token <token> \
    --discovery-token-ca-cert-hash sha256:<hash> \
    --control-plane

8. Add Worker Node

Execute the join command on the node1 node (no need for --control-plane parameter):

bash
kubeadm join master.k8s.io:16443 --token <token> \
    --discovery-token-ca-cert-hash sha256:<hash>
kubeadm join master.k8s.io:16443 --token <token> \
    --discovery-token-ca-cert-hash sha256:<hash>

9. Verify the Cluster

Create a test application to verify cluster functionality:

bash
kubectl create deployment nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl get pods,svc
kubectl create deployment nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl get pods,svc

Access the nginx service via http://<any node IP>:<NodePort>.

10. Common Maintenance Commands

bash
# Check cluster status
kubectl get nodes
kubectl get cs

# View all Pods
kubectl get pods --all-namespaces

# Regenerate join token
kubeadm token create --print-join-command

# View cluster information
kubectl cluster-info
# Check cluster status
kubectl get nodes
kubectl get cs

# View all Pods
kubectl get pods --all-namespaces

# Regenerate join token
kubeadm token create --print-join-command

# View cluster information
kubectl cluster-info

Comments

Pleaseto continueComments require admin approval before being visible

No comments yet. Be the first to comment!