kubeadm 搭建 K8s

AskaJohnny發表於2022-04-17

kubeadm 搭建 K8s

本篇主要記錄一下 使用 kubeadm 搭建 k8s 詳細過程 ,環境使用 VirtualBox 構建的3臺虛擬機器

1.環境準備

  • 作業系統:Centos7 (CentOS Linux release 7.9.2009)
  • Master 主節點: 1臺 虛擬機器
  • Node 計算節點: 2臺 虛擬機器
  • K8s version:v1.23.5 (選的較新的版本)
  • Docker version:20.10.14

虛擬機器建立我就不詳細展開了

2.虛擬機器網路配置(保證能訪問外網)

虛擬機器網路卡 選擇的是 1.網路地址轉換NAT (主要用來訪問外網的) 2.僅主機網路 (主要用來宿主機訪問虛擬機器的)

把對應的 ip 設定如下

kube-master 192.168.56.20

kube-node-1 192.168.56.21

kube-node-2 192.168.56.22

2.1 3臺虛擬機器 靜態ip配置

cat /etc/sysconfig/network-scripts/ifcfg-enp0s3

TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="none" #關閉
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="enp0s3"
UUID="35eac2d4-234d-4859-848e-ed2a30a64a81"
DEVICE="enp0s3"
#新增部分 
IPADDR="10.0.2.20"
PREFIX="24"
GATEWAY="10.0.2.2"
DNS1="10.0.2.3"
DNS2="114.114.114.114"
ONBOOT="yes"

cat /etc/sysconfig/network-scripts/ifcfg-enp0s8

TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static #修改為 static 靜態ip
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp0s8
UUID=d06bac6d-294f-4bfe-bf08-5cb65c0a431f
DEVICE=enp0s8
#新增部分
IPADDR=192.168.56.20
PREFIX=24
ONBOOT=yes

2.2 虛擬機器hosts 配置

在 3臺虛擬機器 /etc/hosts 中配置 如下

192.168.56.20	kube-master
192.168.56.21	kube-node-1
192.168.56.22	kube-node-2

image-20220415170426999

3.k8s 基礎環境設定

3.1 yum 換源(可選)

yum -y install wget

cd /etc/yum.repos.d
mv CentOS-Base.repo CentOS-Base.repo.bak
wget -O CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all
yum makecache #重新生成快取

3.2 關閉 selinux

setenforce 0 #臨時關閉
sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config #永久關閉

3.3 關閉swap分割槽或禁用swap檔案

swapoff -a
# 註釋掉關於swap分割槽的行
yes | cp /etc/fstab /etc/fstab_bak
cat /etc/fstab_bak |grep -v swap > /etc/fstab

3.4 允許iptables 檢查橋接流量

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

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

sudo sysctl --system

3.5 關閉防火牆

systemctl stop firewalld
systemctl disable firewalld

3.6 /proc/sys/net/ipv4/ip_forward

echo 1 > /proc/sys/net/ipv4/ip_forward

4.kubectl、kubeadm、kubelet的安裝

注意 先換源 https://developer.aliyun.com/mirror/kubernetes?spm=a2c6h.13651102.0.0.64be1b11iddYWH 阿里換源文件

4.1 新增Kubernetes的alibaba yum源

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

yum install -y kubelet kubeadm kubectl


4.2 安裝 kubelet kubeadm kubectl

yum install -y kubelet kubeadm kubectl 
systemctl enable kubelet && systemctl start kubelet 

由於官網未開放同步方式, 可能會有索引gpg檢查失敗的情況, 這時請用 yum install -y --nogpgcheck kubelet kubeadm kubectl 安裝

4.3 啟動kubelet 服務

systemctl enable kubelet && systemctl start kubelet

此時執行systemctl status kubelet檢視服務狀態,此時肯定有錯誤(因為我們還未進行初始化操作),錯誤可使用journalctl -xe檢視錯誤資訊。

5.Docker 安裝和配置

Docker centos 安裝文件 地址 https://docs.docker.com/engine/install/centos/

5.1 Docker 安裝

sudo yum install -y yum-utils

sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
    
    
sudo yum install docker-ce docker-ce-cli containerd.io 
# 也可以安裝其他版本 yum list docker-ce --showduplicates | sort -r  
# sudo yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io

#啟動docker
sudo systemctl enable docker && systemctl start docker 

5.2 Docker 映象源更換

sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://9xxxx1clo.mirror.aliyuncs.com"] #請更換自己的 阿里雲映象地址
}
EOF

5.3 Docker 配置cgroup-driver

由於 cgroup-driver ,預設docker 是 cgroupfs ,而k8s 預設是 systemd,所以需要設定 docker 的 cgroup 為 systemd

推薦使用方式二進行修改

#檢視cgroup-driver

 docker info | grep -i cgroup
# 方式一 追加 --exec-opt native.cgroupdriver=systemd 引數
 sed -i "s#^ExecStart=/usr/bin/dockerd.*#ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --exec-opt native.cgroupdriver=systemd#g" /usr/lib/systemd/system/docker.service
 
 systemctl daemon-reload # 重新載入服務
 systemctl enable docker # 啟用docker服務(開機自起)
 systemctl restart docker # 啟動docker服務

# 方式二 修改docker配置檔案
 vim /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"]
}

5.4 拉取k8s所需映象

可以通過

kubeadm config images list 檢視 所需的映象

kubeadm config images list 

k8s.gcr.io/kube-apiserver:v1.23.5
k8s.gcr.io/kube-controller-manager:v1.23.5
k8s.gcr.io/kube-scheduler:v1.23.5
k8s.gcr.io/kube-proxy:v1.23.5
k8s.gcr.io/pause:3.6
k8s.gcr.io/etcd:3.5.1-0
k8s.gcr.io/coredns/coredns:v1.8.6

如果拉取不到映象 可以通過 去 docker hub 上查詢對應的 映象

image-20220415171557414

docker pull k8simage/kube-apiserver:v1.23.5 
 
docker tag k8simage/kube-apiserver:v1.23.5 k8s.gcr.io/kube-apiserver:v1.23.5 #重新tag改成上面所需的映象即可, 其他的都按照這樣來

image-20220415172704185

Tips: 完成上面操作後 你可以通過 docker save 匯出映象,以後再用的時候 可以通過 docker image load < 進行離線載入映象

#匯出映象 ,批量匯出所有映象

docker save $(docker images --format '{{.Repository}}:{{.Tag}}') -o k8s.images.tar 
#匯入映象 ,注意 是 < 不是 > 。。 > 後會導致tar 無法使用需要重新上傳
docker image load < ...tar/zip 

6.kube-master 節點 初始化

我這裡選的是 flannel 網路外掛,先來看看 flannel 的配置檔案

6.1 檢視flannel 網路範圍

flannel.yml https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml

不同的 網路外掛 網路範圍不同

image-20220415173212001

6.2 kubeadm init 初始化

kubeadm init --pod-network-cidr=10.244.0.0/16 \ #網路卡外掛的 網路範圍  --apiserver-advertise-address=192.168.56.20 #master 的 ip 地址

等一會就會有如下結果

image-20220415173521177

可以把 kubeadm join 命令記下來 便於後面使用 儲存輸出中的kubeadm join部分內容,用於新增node節點,或者使用kubeadm token listkubeadm token create --print-join-command檢視

執行後續步驟,可以看到提示

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

6.3 網路外掛flannel 配置

前面提到了flannel 把對應的flannel.yml檔案下載到伺服器中,可以使用wget

可以看到 在沒配置 flannel 的時候 coredns 一直是 pending 狀態

image-20220414184915596

wget https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml #可能會下載不到,文章最後我會提供內容,直接copy過去即可

#Tips: 可能需要指定一下網路卡 ,在kube-flannel.yml中 - /opt/bin/flanneld args: 後面新增
#- --iface=enp0s8 # 需要指定網路卡,否則可能k8s會導致使用錯誤的網路卡 

kubectl apply -f kube-flannel.yml #應用該檔案

image-20220414224216803

kubectl get pods --all-namespaces -o wide #檢視是否安裝成功,它會在 master 和 node 節點上都會自動部署

image-20220415175527461

最後通過 kubectl get nodes -o wide 檢視 節點

7.kube-node 節點初始化

7.1 檢視token

可以通過該命令進行檢視 token

kubeadm token create --print-join-command

#kubeadm join kube-master:6443 --token ii5xyw.mywlktar1e8f60cu --discovery-token-ca-cert-hash sha256:358f92418178342f79aa7b049e6c18a423f0fb88186189142459016fe6efb8e7

7.2 node節點上 執行 kubeadmin join

kubeadm join kube-master:6443 --token ii5xyw.mywlktar1e8f60cu --discovery-token-ca-cert-hash sha256:358f92418178342f79aa7b049e6c18a423f0fb88186189142459016fe6efb8e7

7.3 在master 上檢視結果

watch kubectl get nodes -o wide #可以通過watch 實時監聽 加入情況

image-20220415180246749

至此使用 kubeadm 已經成功搭建k8s 叢集

總結

本篇主要講解了 如何使用 kubeadm 進行搭建 k8s 叢集 ,搭建的是 k8s 較新版本 v1.23.5 版本,使用kubeadm 搭建相對來說還是比較簡單的 。

k8s官網文件

https://kubernetes.io/zh/docs/setup/production-environment/tools/kubeadm/install-kubeadm/

阿里 k8s 更換映象文件

https://developer.aliyun.com/mirror/kubernetes?spm=a2c6h.13651102.0.0.64be1b11iddYWH

Docker hub 地址

https://hub.docker.com/r/k8simage/

Docker 安裝地址

https://docs.docker.com/engine/install/centos/

flannel.yml 檔案

---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: psp.flannel.unprivileged
  annotations:
    seccomp.security.alpha.kubernetes.io/allowedProfileNames: docker/default
    seccomp.security.alpha.kubernetes.io/defaultProfileName: docker/default
    apparmor.security.beta.kubernetes.io/allowedProfileNames: runtime/default
    apparmor.security.beta.kubernetes.io/defaultProfileName: runtime/default
spec:
  privileged: false
  volumes:
  - configMap
  - secret
  - emptyDir
  - hostPath
  allowedHostPaths:
  - pathPrefix: "/etc/cni/net.d"
  - pathPrefix: "/etc/kube-flannel"
  - pathPrefix: "/run/flannel"
  readOnlyRootFilesystem: false
  # Users and groups
  runAsUser:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  fsGroup:
    rule: RunAsAny
  # Privilege Escalation
  allowPrivilegeEscalation: false
  defaultAllowPrivilegeEscalation: false
  # Capabilities
  allowedCapabilities: ['NET_ADMIN', 'NET_RAW']
  defaultAddCapabilities: []
  requiredDropCapabilities: []
  # Host namespaces
  hostPID: false
  hostIPC: false
  hostNetwork: true
  hostPorts:
  - min: 0
    max: 65535
  # SELinux
  seLinux:
    # SELinux is unused in CaaSP
    rule: 'RunAsAny'
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
rules:
- apiGroups: ['extensions']
  resources: ['podsecuritypolicies']
  verbs: ['use']
  resourceNames: ['psp.flannel.unprivileged']
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes/status
  verbs:
  - patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: flannel
subjects:
- kind: ServiceAccount
  name: flannel
  namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: flannel
  namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: kube-flannel-cfg
  namespace: kube-system
  labels:
    tier: node
    app: flannel
data:
  cni-conf.json: |
    {
      "name": "cbr0",
      "cniVersion": "0.3.1",
      "plugins": [
        {
          "type": "flannel",
          "delegate": {
            "hairpinMode": true,
            "isDefaultGateway": true
          }
        },
        {
          "type": "portmap",
          "capabilities": {
            "portMappings": true
          }
        }
      ]
    }
  net-conf.json: |
    {
      "Network": "10.244.0.0/16",
      "Backend": {
        "Type": "vxlan"
      }
    }
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: kube-flannel-ds
  namespace: kube-system
  labels:
    tier: node
    app: flannel
spec:
  selector:
    matchLabels:
      app: flannel
  template:
    metadata:
      labels:
        tier: node
        app: flannel
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/os
                operator: In
                values:
                - linux
      hostNetwork: true
      priorityClassName: system-node-critical
      tolerations:
      - operator: Exists
        effect: NoSchedule
      serviceAccountName: flannel
      initContainers:
      - name: install-cni-plugin
       #image: flannelcni/flannel-cni-plugin:v1.0.1 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.1
        command:
        - cp
        args:
        - -f
        - /flannel
        - /opt/cni/bin/flannel
        volumeMounts:
        - name: cni-plugin
          mountPath: /opt/cni/bin
      - name: install-cni
       #image: flannelcni/flannel:v0.17.0 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel:v0.17.0
        command:
        - cp
        args:
        - -f
        - /etc/kube-flannel/cni-conf.json
        - /etc/cni/net.d/10-flannel.conflist
        volumeMounts:
        - name: cni
          mountPath: /etc/cni/net.d
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      containers:
      - name: kube-flannel
       #image: flannelcni/flannel:v0.17.0 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel:v0.17.0
        command:
        - /opt/bin/flanneld
        args:
        #- --iface=enp0s8 # 需要指定網路卡,否則可能會導致問題
        - --ip-masq
        - --kube-subnet-mgr
        resources:
          requests:
            cpu: "100m"
            memory: "50Mi"
          limits:
            cpu: "100m"
            memory: "50Mi"
        securityContext:
          privileged: false
          capabilities:
            add: ["NET_ADMIN", "NET_RAW"]
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: EVENT_QUEUE_DEPTH
          value: "5000"
        volumeMounts:
        - name: run
          mountPath: /run/flannel
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
        - name: xtables-lock
          mountPath: /run/xtables.lock
      volumes:
      - name: run
        hostPath:
          path: /run/flannel
      - name: cni-plugin
        hostPath:
          path: /opt/cni/bin
      - name: cni
        hostPath:
          path: /etc/cni/net.d
      - name: flannel-cfg
        configMap:
          name: kube-flannel-cfg
      - name: xtables-lock
        hostPath:
          path: /run/xtables.lock
          type: FileOrCreate

歡迎大家訪問 個人部落格 Johnny小屋

相關文章