[雲原生]Kubernetes - 叢集搭建(第2章)

SkyBiuBiu發表於2021-12-31

一、前置知識點

目前生產部署Kubernetes叢集主要有三種種方式:

minikube

minikube是一個工具,可以在本地快速執行一個單節點的kubernetes,僅用於嘗試K8S或日常開發的測試環境使用。

kubeadm

img

kubeadm是一個K8S部署工具,提供kubeadm init和kubeadm join,用於快速部署Kubernetes叢集。

官方地址:Kubeadm | Kubernetes

二進位制包

從github下載發行版的二進位制包,手動部署每個元件,組成Kubernetes叢集。

kubeadm降低了部署門檻,但是遮蔽了很多細節,遇到問題很難排查。如果想更容易可控,推薦使用二進位制包部署Kubernetes叢集,雖然手動部署麻煩點,期間可以學習很多工作原理,也利於後期維護。

image-20200404094800622

部署方式:

  • 一主多從:測試環境、練習環境。
  • 多主多從:生產環境推薦使用。

二、kubeadm部署方式介紹

kubeadm 是官方社群推出的一個用於快速部署kubernetes叢集的工具,這個工具能通過兩條指令完成一個kubernetes叢集的部署:

  • kubeadm init:建立一個Master節點。
  • kubeadm join <Master節點的IP和埠>:將Node節點加入到當前叢集中。

三、安裝要求

在開始之前,部署Kubernetes叢集的機器需要滿足以下幾個條件:

  • 一臺或多臺機器,作業系統CentOS7.x-86_x64(我自己復現的環境用的CentOS 8)
  • 硬體配置:2GB 或更多RAM,2 個CPU 或更多CPU,硬碟30GB 或更多
  • 叢集中所有機器之間網路互通
  • 可以訪問外網,需要拉取映象
  • 禁止swap 分割槽

四、最終目標

  • 在所有節點上安裝Docker和kubeadm
  • 部署Kubernetes Master
  • 部署容器網路外掛
  • 部署Kubernetes Node,將節點加入Kubernetes叢集中
  • 部署Dashboard Web頁面,視覺化檢視Kubernetes資源

五、準備環境

image-20210609000002940

角色 IP地址 元件
k8s-master01 192.168.9.10 docker,kubectl,kubeadm,kubelet
k8s-node01 192.168.9.20 docker,kubectl,kubeadm,kubelet
k8s-node02 192.168.9.30 docker,kubectl,kubeadm,kubelet

備註:學習環境為一個Master,兩個Node節點。

六、環境初始化

6.1 設定系統主機名以及Hosts檔案的相互解析

  • 修改主機名
hostnamectl set-hostname k8s-master01 && bash
hostnamectl set-hostname k8s-node01 && bash
hostnamectl set-hostname k8s-node02 && bash
  • 修改Master節點的/etc/hosts
192.168.9.10     k8s-master01
192.168.9.20     k8s-node01
192.168.9.30     k8s-node02
  • 拷貝到Node節點
scp /etc/hosts root@192.168.9.20:/etc/hosts
scp /etc/hosts root@192.168.9.30:/etc/hosts
  • 測試連通性
ping k8s-master01
ping k8s-node01
ping k8s-node02

6.2 安裝依賴檔案(所有節點)

yum install -y conntrack chrony ipvsadm ipset jq iptables curl sysstat libseccomp wget vim net-tools git

備註:在CentOS 8裡面,用chrony服務代替了NTP。

6.3 禁用iptables和firewalld服務(所有節點)

systemctl stop firewalld
systemctl disable firewalld

systemctl stop iptables
systemctl disable iptables

6.4 禁用Swap分割槽和SELinux(所有節點)

# 1.禁用swap分割槽
swapoff -a && sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab
# 2.禁用SELinux
setenforce 0 && sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config

6.5 調整核心引數,對於K8S(所有節點)

  • 修改Linux的核心引數/etc/sysctl.d/kubernetes.conf
# 修改Linux的核心引數,新增網橋過濾和地址轉發功能
# 編輯/etc/sysctl.d/kubernetes.conf檔案,新增如下配置:
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1

# 重新載入配置
sysctl -p

# 載入網橋過濾模組
modprobe br_netfilter

# 檢視網橋過濾模組的是否載入成功
lsmod | grep br_netfilter
  • 配置ipvs功能

在kubernetes中service有兩種代理模型,一種是基於iptables的,一種是基於ipvs的。

兩者比較的話,ipvs的效能明顯要高一些,但是如果要使用它,需要手動載入ipvs模組。

# 1.安裝ipset和ipvsadm
yum install ipset ipvsadm -y

# 2.新增需要載入的模組寫入指令碼
cat <<EOF > /etc/sysconfig/modules/ipvs.modules
#! /bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF

# 3.為指令碼檔案新增執行許可權
chmod +x /etc/sysconfig/modules/ipvs.modules

# 4.執行指令碼檔案
/bin/bash /etc/sysconfig/modules/ipvs.modules

# 5.檢視對應的模組是否載入成功
lsmod | grep -e ip_vs -e nf_conntrack_ipv4

6.6 調整系統時區(所有節點,選做)

# 設定系統時區為 中國/上海
timedatectl set-timezone Asia/Shanghai
# 將當前的 UTC 時間寫入硬體時鐘
timedatectl set-local-rtc 0
# 重啟依賴於系統時間的服務
systemctl restart rsyslog
systemctl restart crond

6.7 設定rsyslogd和systemd journald(所有節點,選做)

# 持久化儲存日誌的目錄
mkdir /var/log/journal 
mkdir /etc/systemd/journald.conf.d
cat > /etc/systemd/journald.conf.d/99-prophet.conf <<EOF
[Journal]
# 持久化儲存到磁碟
Storage=persistent

# 壓縮歷史日誌
Compress=yes

SyncIntervalSec=5m
RateLimitInterval=30s
RateLimitBurst=1000

# 最大佔用空間 10G
SystemMaxUse=10G

# 單日誌檔案最大 200M
SystemMaxFileSize=200M

# 日誌儲存時間 2 周
MaxRetentionSec=2week

# 不將日誌轉發到 syslog
ForwardToSyslog=no
EOF

systemctl restart systemd-journald

6.8 安裝Docker(所有節點)

# 1.切換映象源
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo

# 2.檢視當前映象源中支援的docker版本
yum list docker-ce --showduplicates

# 3.安裝特定版本的docker-ce
# 可以指定 --setopt=obsoletes=0,否則yum會自動安裝更高的版本
yum install docker-ce -y

# 4.新增一個配置檔案
# Docker在預設情況下使用的Cgroup Driver為cgroupfs,而kubernetes推薦使用systemd來代替cgroupfs
mkdir /etc/docker
cat <<EOF > /etc/docker/daemon.json
{
	"exec-opts":["native.cgroupdriver=systemd"],
	"registry-mirrors":["https://gq8usroj.mirror.aliyuncs.com"]
}
EOF

# 5.啟動Docker
systemctl restart docker
systemctl enable docker

# 6.檢查docker狀態和版本
docker version

6.9 安裝kubenetes元件(所有節點)

# 由於kubernetes的映象源在國外,速度比較慢,這裡切換成國內的映象源
# 編輯/etc/yum.repos.d/kubernetes.repo,新增下面的配置
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
	   http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

# 安裝kubeadm、kubelet和kubectl
yum install kubeadm kubelet kubectl

# 配置kubelet的cgroup
# 編輯/etc/sysconfig/kubelet,新增下面的配置
KUBELET_CGROUP_ARGS="--cgroup-driver=systemd"
KUBE_PROXY_MODE="ipvs"

# 設定kubelet開機自啟
systemctl enable kubelet

七、部署Kubernetes叢集

7.1 準備叢集映象

使用kubeadm config images list檢視所需要的映象:

[root@k8s-master01 ~]# kubeadm config images list
k8s.gcr.io/kube-apiserver:v1.23.1
k8s.gcr.io/kube-controller-manager:v1.23.1
k8s.gcr.io/kube-scheduler:v1.23.1
k8s.gcr.io/kube-proxy:v1.23.1
k8s.gcr.io/pause:3.6
k8s.gcr.io/etcd:3.5.1-0
k8s.gcr.io/coredns/coredns:v1.8.6
# 在安裝Kubernetes叢集之前,必須要提前準備號叢集需要的映象,所需映象可以通過下面命令檢視
kubeadm config images list

# 下載映象
# 此映象在kubernetes的倉庫中,由於網路原因,無法連線,下面提供了一種替代方案
images=(
	kube-apiserver:v1.23.1
	kube-controller-manager:v1.23.1
	kube-scheduler:v1.23.1
	kube-proxy:v1.23.1
	pause:3.6
	etcd:3.5.1-0
	coredns:v1.8.6
)

# 拉取所需要的映象
for imageName in ${images[@]};
do
	docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
done

# 重新給映象打標籤,如果下面kube init的時候指定倉庫,可以不需要重新tag
for imageName in ${images[@]};
do
	docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName k8s.gcr.io/$imageName
done

# 刪除掉原名字的映象
for imageName in ${images[@]};
do
	docker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
done

效果如下:

[root@k8s-master01 ~]# docker images
REPOSITORY                           TAG       IMAGE ID       CREATED        SIZE
k8s.gcr.io/kube-apiserver            v1.23.1   b6d7abedde39   2 weeks ago    135MB
k8s.gcr.io/kube-proxy                v1.23.1   b46c42588d51   2 weeks ago    112MB
k8s.gcr.io/kube-scheduler            v1.23.1   71d575efe628   2 weeks ago    53.5MB
k8s.gcr.io/kube-controller-manager   v1.23.1   f51846a4fd28   2 weeks ago    125MB
k8s.gcr.io/etcd                      3.5.1-0   25f8c7f3da61   8 weeks ago    293MB
k8s.gcr.io/coredns                   v1.8.6    a4ca41631cc7   2 months ago   46.8MB
k8s.gcr.io/pause                     3.6       6270bb605e12   4 months ago   683kB

7.2 叢集初始化

下面開始對叢集進行初始化,並將node節點加入到叢集中

下面的操作只需要在master節點上執行即可

這一步很關鍵,由於kubeadm 預設從官網k8s.gcr.io下載所需映象,國內無法訪問,因此需要通過--image-repository=指定阿里雲映象倉庫地址。

# 建立叢集
kubeadm init \
	--kubernetes-version=v1.23.1 \
	--pod-network-cidr=10.244.0.0/16 \
	--service-cidr=10.96.0.0/12 \
	--image-repository registry.aliyuncs.com/google_containers  \
	--apiserver-advertise-address=192.168.9.10
	
# 建立必要檔案
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME /.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

叢集初始化成功後返回如下資訊:

[root@k8s-master01 ~]# kubeadm init \
> --kubernetes-version=v1.23.1 \
> --pod-network-cidr=10.244.0.0/16 \
> --service-cidr=10.96.0.0/12 \
> --image-repository registry.aliyuncs.com/google_containers  \
> --apiserver-advertise-address=192.168.9.10
[init] Using Kubernetes version: v1.23.1
[preflight] Running pre-flight checks
        [WARNING FileExisting-tc]: tc not found in system path
[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 [k8s-master01 kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.9.10]
[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 [k8s-master01 localhost] and IPs [192.168.9.10 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [k8s-master01 localhost] and IPs [192.168.9.10 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.503475 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 k8s-master01 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 k8s-master01 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: 9xx9un.p2x8icgh1wxo6y45
[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/

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

kubeadm join 192.168.9.10:6443 --token 9xx9un.p2x8icgh1wxo6y45 \
        --discovery-token-ca-cert-hash sha256:797daf093fb0c4bbde161107bf297f858f76fe368ae66e789d3bd331ecc51480

然後需要在Master節點上執行如下:

#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

然後可以看到如下效果:

[root@k8s-master01 ~]# kubectl get nodes
NAME           STATUS     ROLES                  AGE    VERSION
k8s-master01   NotReady   control-plane,master   5m9s   v1.23.1

下面的操作只需要在node節點上執行即可

然後,將Node節點加入叢集中

# 在node節點中輸入
kubeadm join 192.168.9.10:6443 --token 9xx9un.p2x8icgh1wxo6y45 \
        --discovery-token-ca-cert-hash sha256:797daf093fb0c4bbde161107bf297f858f76fe368ae66e789d3bd331ecc51480

然後在Master節點看到如下效果:

[root@k8s-master01 ~]# kubectl get nodes
NAME           STATUS     ROLES                  AGE     VERSION
k8s-master01   NotReady   control-plane,master   9m43s   v1.23.1
k8s-node01     NotReady   <none>                 11s     v1.23.1
k8s-node02     NotReady   <none>                 15s     v1.23.1

但是此時,STATUS是NotReady,這是因為還沒有安裝網路外掛。

7.3 安裝網路外掛

Kubernetes支援多種網路外掛,比如flannel、calico、canal等,任選一種使用即可,本次選擇flannel。

下面操作依舊只在master節點執行即可,外掛使用的是DaemonSet的控制器,它會在每一個節點上都執行。

# 獲取fannel的配置檔案
wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
# 上面的不行的話用這個
# https://raw.fastgit.org/coreos/flannel/master/Documentation/kube-flannel.yml

# 修改檔案中quay.io倉庫為quay-mirror.qiniu.com

# 使用配置檔案啟動fannel
kubectl apply -f kube-flannel.yml
# 稍等片刻,再次檢視叢集節點的狀態
[root@k8s-master01 ~]# kubectl get nodes
NAME           STATUS   ROLES                  AGE   VERSION
k8s-master01   Ready    control-plane,master   24m   v1.23.1
k8s-node01     Ready    <none>                 14m   v1.23.1
k8s-node02     Ready    <none>                 14m   v1.23.1

至此,Kubernetes叢集環境搭建完成。

八、測試Kubernetes叢集

接下來在Kubernetes叢集中部署一個nginx程式,測試下叢集是否在正常工作。

# 部署nginx
kubectl create deployment nginx --image=nginx:latest
# 暴露埠
kubectl expose deployment nginx --port=80 --type=NodePort
# 檢視服務狀態
[root@k8s-master01 ~]# kubectl get pods,svc
NAME                         READY   STATUS              RESTARTS   AGE
pod/nginx-7c658794b9-9xwg7   0/1     ContainerCreating   0          17s

NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP        46m
service/nginx        NodePort    10.97.244.84   <none>        80:31182/TCP   11s

上面的svc = service

然後在電腦上測試訪問31182埠

image-20211231185411955

這樣子,就完成了測試!

相關文章