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


一、前置知識點

目前生產部署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

這樣子,就完成了測試!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM