通過kubeadm工具部署k8s叢集

一就是一發表於2022-01-25

1、概述

kubeadm是一工具箱,通過kubeadm工具,可以快速的建立一個最小的、可用的,並且符合最佳實踐的k8s叢集。

本文件介紹如何通過kubeadm工具快速部署一個k8s叢集。

2、主機規劃及環境準備

此處的主機配置要在所有的節點進行操作。

2.1、主機規劃

IP

主機名

CPU/MEM

作業系統版本

角色

資料磁碟目錄

172.20.58.83

nccztsjb-node-23

8c/16g

CentOS 7.5.1804

master

/data

172.20.58.65

nccztsjb-node-24

8c/16g

CentOS 7.5.1804

worker node

/data

172.20.58.18

nccztsjb-node-25

8c/16g

CentOS 7.5.1804

worker node

/data

本次安裝的架構為1 master節點 2 node節點叢集。後續也逐步會介紹如何通過kubeadm工具部署多master的高可用叢集。

資料磁碟目錄/data用於存放docker映象及容器資料。

2.2、網路卡MAC地址、主機UUID一致性檢查

要確保各個主機的主機名、MAC地址和product_uuid是唯一的。k8s使用這些值來作為叢集中節點的唯一標識。如果這些值不唯一,安裝過程會失敗。

主機名檢查

hostname

MAC地址檢查

ip link


product_uuid檢查

cat /sys/class/dmi/id/product_uuid

2.3、載入br_netfilter模組

為了讓ipables可以看到橋接的流量,需要載入br_netfilter模組。

通過以下的命令檢查,是否載入了br_netfilter模組:

lsmod | grep br_netfilter

如果沒有,可以通過以下的命令手動載入:

modprobe br_netfilter

載入後,查詢模組顯示結果如下:

[root@nccztsjb-node-23 ~]#  lsmod | grep br_netfilter
br_netfilter           22256  0 
bridge                146976  1 br_netfilter

配置模組載入永久生效

cat <<EOF | tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF

這樣重啟主機之後,模組會自動的進行載入。

核心引數設定

cat <<EOF | tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF

sysctl --system

以上配置主要是網路外掛的部署對與系統的要求。

2.4、關閉swap交換分割槽

為了使得kubelet正確的執行,必須要禁止掉swap交換分割槽

# 臨時關閉
swapoff -a

# 永久關閉
sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

3、部署容器執行時(docker)

為了在pod中執行容器,需要使用容器執行時,本次安裝使用docker執行時。kubelet通過內建的dockershim CRI與docker進行整合。

3.1、安裝docker

# 1、安裝必要的一些系統工具
yum install -y yum-utils device-mapper-persistent-data lvm2

# 2、新增軟體源資訊
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 3、修改映象源地址
sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo

# 4、更新並安裝Docker-CE
yum makecache fast
yum -y install docker-ce

# 5、開啟Docker服務並設定為開機啟動
systemctl enable --now docker 

檢視docker版本及執行狀態

docker version

systemctl status docker

3.2、配置docker

對docker進行配置,主要是配置cgroup driver和資料儲存目錄。

將docker的cgroup driver設定為systemd

cat <<EOF | tee /etc/docker/daemon.json 
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-level": "warn",
  "storage-driver": "overlay2",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
    },
  "data-root": "/data/docker",
  "insecure-registries": ["0.0.0.0/0"],
  "features": {
      "buildkit": true
  }
}
EOF

重啟docker,檢視docker配置

systemctl restart docker

docker info |grep -iE "cgroup Driver|Docker Root"

4、安裝kubeadm,kubelet,kubectl工具

在所有的機器上執行以下的安裝操作。

通過yum的方式安裝kubeadm kubelet,kubectl命令,當然也可以通過到github上下載的方式進行安裝。

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

# 關閉selinux
setenforce 0
sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config

# 安裝kubeadm,kubelet,kubectl
yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes

# 啟動並設定為開機啟動
systemctl enable --now kubelet

注意:此時kubelet服務是不正常的,後續當通過kubeadm引導叢集、提供kubelet具體的配置時,kubelet服務才會正常。

5、建立kubeadm的配置檔案

在通過kubeadm工具初始化叢集時,可以提供各種引數對叢集、元件進行配置

cat <<EOF | tee kubeadm-config.yaml
kind: ClusterConfiguration
apiVersion: kubeadm.k8s.io/v1beta3
kubernetesVersion: v1.23.1  #此處為要安裝的k8s的版本
imageRepository: gotok8s    #拉取映象的庫,預設從k8s.gcr.io拉取,網路上訪問會有問題,使用其他包含映象的站點
controlPlaneEndpoint: "172.20.58.83:6443" #apiserver對外地址,也是master的IP:443,後續如果要設定為高可用叢集會用到
networking:
  podSubnet: "172.39.0.0/16" #pod所在的子網
---
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
cgroupDriver: systemd #配置kubelet的cgroup,要和docker保持一致
EOF

6、初始化及配置控制平面(master)

6.1、初始化

在master節點上進行初始化的操作。

kubeadm init --config kubeadm-config.yaml

安裝過程拉取映象比較慢。可以考慮將映象拉取放到本地的harbor倉庫中。

安裝過程:

[root@nccztsjb-node-23 ~]# kubeadm init --config kubeadm-config.yaml 
[init] Using Kubernetes version: v1.23.1
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local nccztsjb-node-23] and IPs [10.96.0.1 172.20.58.83]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [localhost nccztsjb-node-23] and IPs [172.20.58.83 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [localhost nccztsjb-node-23] and IPs [172.20.58.83 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 7.514116 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.23" in namespace kube-system with the configuration for the kubelets in the cluster
NOTE: The "kubelet-config-1.23" naming of the kubelet ConfigMap is deprecated. Once the UnversionedKubeletConfigMap feature gate graduates to Beta the default name will become just "kubelet-config". Kubeadm upgrade will handle this transition transparently.
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node nccztsjb-node-23 as control-plane by adding the labels: [node-role.kubernetes.io/master(deprecated) node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers]
[mark-control-plane] Marking the node nccztsjb-node-23 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: nmc6sr.okga4v88tdanm4be
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

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

Alternatively, if you are the root user, you can run:

  export KUBECONFIG=/etc/kubernetes/admin.conf

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

You can now join any number of control-plane nodes by copying certificate authorities
and service account keys on each node and then running the following as root:

  kubeadm join 172.20.58.83:6443 --token nmc6sr.okga4v88tdanm4be \
	--discovery-token-ca-cert-hash sha256:53bb18482396f7f52e58061df6ce669169143f7e00b248e429f0ce2d7b1cc34e \
	--control-plane 

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 172.20.58.83:6443 --token nmc6sr.okga4v88tdanm4be \
	--discovery-token-ca-cert-hash sha256:53bb18482396f7f52e58061df6ce669169143f7e00b248e429f0ce2d7b1cc34e

6.2、配置kubeconfig

當kubectl需要和叢集通訊,需要用到kubeconfig檔案,執行以下的命令配置kubeconfig

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

執行kubectl命令,進行驗證

[root@nccztsjb-node-23 ~]# kubectl get nodes
NAME               STATUS     ROLES                  AGE     VERSION
nccztsjb-node-23   NotReady   control-plane,master   2m36s   v1.23.2
[root@nccztsjb-node-23 ~]# 
[root@nccztsjb-node-23 ~]# kubectl get pods -A
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE
kube-system   coredns-7fc76f876d-9bwnp                   0/1     Pending   0          2m53s
kube-system   coredns-7fc76f876d-kpfgn                   0/1     Pending   0          2m53s
kube-system   etcd-nccztsjb-node-23                      1/1     Running   0          3m7s
kube-system   kube-apiserver-nccztsjb-node-23            1/1     Running   0          3m6s
kube-system   kube-controller-manager-nccztsjb-node-23   1/1     Running   0          3m6s
kube-system   kube-proxy-6xpf2                           1/1     Running   0          2m53s
kube-system   kube-scheduler-nccztsjb-node-23            1/1     Running   0          3m6s
[root@nccztsjb-node-23 ~]# 

各個元件已經安裝,coredns外掛需要安裝網路外掛之後,才可正常。

7、部署容器網路外掛(calico)

安裝calico網路外掛,用於容器間的通訊

kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml 

待容器執行正常

[root@nccztsjb-node-23 ~]# kubectl get pod -A
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE
kube-system   calico-kube-controllers-85b5b5888d-lzdb5   1/1     Running   0          2m11s
kube-system   calico-node-7rjcq                          1/1     Running   0          2m11s
kube-system   coredns-7fc76f876d-9bwnp                   1/1     Running   0          8m48s
kube-system   coredns-7fc76f876d-kpfgn                   1/1     Running   0          8m48s
kube-system   etcd-nccztsjb-node-23                      1/1     Running   0          9m2s
kube-system   kube-apiserver-nccztsjb-node-23            1/1     Running   0          9m1s
kube-system   kube-controller-manager-nccztsjb-node-23   1/1     Running   0          9m1s
kube-system   kube-proxy-6xpf2                           1/1     Running   0          8m48s
kube-system   kube-scheduler-nccztsjb-node-23            1/1     Running   0          9m1s

檢視節點狀態

[root@nccztsjb-node-23 ~]# kubectl get nodes
NAME               STATUS   ROLES                  AGE     VERSION
nccztsjb-node-23   Ready    control-plane,master   9m40s   v1.23.2
[root@nccztsjb-node-23 ~]# 

節點狀態也正常了,OK,現在只有一個master節點的k8s叢集部署完成。

注意:master上配置了taint即工作負載不可以排程上,也是符合最佳實踐的。

8、加入node節點

通過以上初始化過程中提到的命令將其他的2個節點以node節點加入到叢集中

kubeadm join 172.20.58.83:6443 --token nmc6sr.okga4v88tdanm4be \
	--discovery-token-ca-cert-hash sha256:53bb18482396f7f52e58061df6ce669169143f7e00b248e429f0ce2d7b1cc34e

執行過程

[root@nccztsjb-node-24 ~]# kubeadm join 172.20.58.83:6443 --token nmc6sr.okga4v88tdanm4be \
> --discovery-token-ca-cert-hash sha256:53bb18482396f7f52e58061df6ce669169143f7e00b248e429f0ce2d7b1cc34e
[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

[root@nccztsjb-node-24 ~]# 

注意:加入節點也有個拉取映象的過程,需要等些時間。

在master節點檢視node狀態

[root@nccztsjb-node-23 ~]# kubectl get nodes
NAME               STATUS   ROLES                  AGE    VERSION
nccztsjb-node-23   Ready    control-plane,master   14m    v1.23.2
nccztsjb-node-24   Ready    <none>                 2m5s   v1.23.2
nccztsjb-node-25   Ready    <none>                 87s    v1.23.2
[root@nccztsjb-node-23 ~]# 

檢視pod的狀態

[root@nccztsjb-node-23 ~]# kubectl get pod -A
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE
kube-system   calico-kube-controllers-85b5b5888d-lzdb5   1/1     Running   0          8m51s
kube-system   calico-node-5ndlp                          1/1     Running   0          3m2s
kube-system   calico-node-7rjcq                          1/1     Running   0          8m51s
kube-system   calico-node-9hm4q                          1/1     Running   0          2m24s
kube-system   coredns-7fc76f876d-9bwnp                   1/1     Running   0          15m
kube-system   coredns-7fc76f876d-kpfgn                   1/1     Running   0          15m
kube-system   etcd-nccztsjb-node-23                      1/1     Running   0          15m
kube-system   kube-apiserver-nccztsjb-node-23            1/1     Running   0          15m
kube-system   kube-controller-manager-nccztsjb-node-23   1/1     Running   0          15m
kube-system   kube-proxy-6xpf2                           1/1     Running   0          15m
kube-system   kube-proxy-j6tr8                           1/1     Running   0          2m24s
kube-system   kube-proxy-kjv9w                           1/1     Running   0          3m2s
kube-system   kube-scheduler-nccztsjb-node-23            1/1     Running   0          15m
[root@nccztsjb-node-23 ~]# 

在新加的節點上也啟動了calico-node的節點。

9、部署pod、測試節點間網路訪問

kubectl create deployment nginx-test --image=172.20.58.152/middleware/nginx:1.21.4 --replicas=4

本次建立4個副本。

[root@nccztsjb-node-23 ~]# kubectl get pod -o wide 
NAME                         READY   STATUS    RESTARTS   AGE   IP               NODE               NOMINATED NODE   READINESS GATES
nginx-test-b76c7cb54-28j4l   1/1     Running   0          28s   172.39.21.66     nccztsjb-node-25   <none>           <none>
nginx-test-b76c7cb54-pkpw2   1/1     Running   0          28s   172.39.157.194   nccztsjb-node-24   <none>           <none>
nginx-test-b76c7cb54-rbfz8   1/1     Running   0          28s   172.39.157.193   nccztsjb-node-24   <none>           <none>
nginx-test-b76c7cb54-wtch5   1/1     Running   0          28s   172.39.21.65     nccztsjb-node-25   <none>           <none>
[root@nccztsjb-node-23 ~]# 

測試主機和pod間的訪問:

[root@nccztsjb-node-23 ~]# ping 172.39.21.66
PING 172.39.21.66 (172.39.21.66) 56(84) bytes of data.
64 bytes from 172.39.21.66: icmp_seq=1 ttl=63 time=0.652 ms
64 bytes from 172.39.21.66: icmp_seq=2 ttl=63 time=0.492 ms
^C
--- 172.39.21.66 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.492/0.572/0.652/0.080 ms
[root@nccztsjb-node-23 ~]# ping 172.39.157.194
PING 172.39.157.194 (172.39.157.194) 56(84) bytes of data.
64 bytes from 172.39.157.194: icmp_seq=1 ttl=63 time=0.557 ms
64 bytes from 172.39.157.194: icmp_seq=2 ttl=63 time=0.422 ms
^C
--- 172.39.157.194 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.422/0.489/0.557/0.071 ms
[root@nccztsjb-node-23 ~]# 

測試容器間的訪問

[root@nccztsjb-node-23 ~]# kubectl exec -it nginx-test-b76c7cb54-28j4l -- bash
root@nginx-test-b76c7cb54-28j4l:/# wget 172.39.157.194
bash: wget: command not found
root@nginx-test-b76c7cb54-28j4l:/# curl 172.39.157.194
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

是可以通過curl訪問到的。

說明,節點和容器、容器和容器之間的網路都是通的。

OK,至此通過kubeadm工具部署k8s叢集完成。

相關文章