Kubeadm方式搭建K8S叢集

Teddy_boy發表於2023-09-22

Kubeadm方式搭建K8S叢集

一、搭建k8s叢集(kubeadm方式)
kubeadm部署方式介紹
kubeadm是官方社群推出的一個用於快速部署kubernetes叢集的工具,這個工具能透過兩條指令完成一個kubernetes叢集的部署:
第一,建立一個master幾點 kubeadm init
第二,將node節點加入到當前叢集中 $kubeadm join <Master 節點的IP和埠>

安裝要求
部署kubernetes叢集機器需要滿足以下幾個條件:

1. 一臺或多臺機器,作業系統CentOs7.x-86_x64
2. 硬體配置:2GB或更多RAM,2個CPU或更多CPU,硬碟30GB或更多
3. 叢集中所有機器之間網路互通
4. 可以訪問外網,需要拉取映象
5. 禁止swap分割槽

最終目標

1. 在所有節點上安裝docker 和kubeadm
2. 部署kubernetes master
3. 部署容器網路外掛
4. 部署kubernetes node,將節點加入kubernetes叢集中
5. 部署Dashboard Web頁面,視覺化檢視Kubernetes資源

二、安裝步驟

  1. 安裝三臺虛擬機器,安裝作業系統centos7.x
192.168.72.129
192.168.72.130
192.168.72.131(master)
  1. 對三個作業系統進行初始化操作
# 關閉防火牆
systemctl stop fierwalld  #臨時關閉
systemctl disable fierwalld  #永久關閉

# 關閉selinux
sed -i 's/enforcing/disabled/' /etc/selinux/config # 永久
setenforce 0 # 臨時

# 關閉swap分割槽
swapoff -a  #臨時
sed -ri 's/.*swap.*/#&/' /etc/fstab  #永久

# 根據規劃設定主機名
hostnamectl set-hostname <hostname>

# 在master新增hosts   只在master中執行
cat >> /etc/hosts << EOF
192.168.72.131 k8s-master
192.168.72.129 k8s-node1
192.168.72.130 k8s-node2
EOF

# 將橋接的 IPv4 流量傳遞到 iptables 的鏈
cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF

sysctl --system # 生效

# 時間同步
yum install ntpdate -y

ntpdate time.windows.com
  1. 所有節點安裝 Docker/kubeadm/kubelet
    安裝docker
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo 

yum -y install docker-ce-18.06.1.ce-3.el7 

systemctl enable docker && systemctl start docker 

docker --version

新增阿里雲 YUM 軟體源

# 設定倉庫地址
cat > /etc/docker/daemon.json << EOF 
{
 "registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com"] 
}
EOF
systemctl restart docker  #重啟

# 新增 yum 源
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

安裝 kubeadm,kubelet 和 kubectl

#由於版本更新頻繁,這裡指定版本
yum install -y kubelet-1.18.0 kubeadm-1.18.0 kubectl-1.18.0 

systemctl enable kubelet
  1. 部署 Kubernetes Master
    在master上執行
kubeadm init --apiserver-advertise-address=192.168.72.131 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.18.0 --service-cidr=10.96.0.0/12 --pod-network-cidr=10.244.0.0/16

由於預設拉取映象地址 k8s.gcr.io 國內無法訪問,這裡指定阿里雲映象倉庫地址。

使用 kubectl 工具:

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

kubectl get nodes
  1. 加入 Kubernetes Node
    在 Node 中執行
    向叢集新增新節點,執行在 kubeadm init 輸出的 kubeadm join 命令:
kubeadm join 192.168.72.131:6443 --token n0nyws.8j0mkjbfwk16adai \
    --discovery-token-ca-cert-hash sha256:774e4171fc2a86bff58b49aaf153276f1fff56e93f1ba72e29a4ce3df8

預設token有效期為24小時,當過期之後,該token就不可用了。這時就需要重新建立token

# master 檢視節點檢查token是否有效
kubeadm token list
# 生成新的token和命令。然後在node重新執行
kubeadm token create --print-join-command
# 在 node節點執行新的token和命令
kubeadm join 192.168.136.201:6443 --token 17wwni.taqxzqa3our1wh92 --discovery-token-ca-cert-hash sha256:1472821b3c34f13bc5d7264a737739e9854195b1856a00d2256c79d25118b2e
123456
  1. 部署CNI網路外掛
kubectl apply –f
https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kubeflannel.yml

透過以上命令,部署CNI失敗,試了好多次仍然不成功,試試下面這種辦法。

①master檔案中建立檔案,將下述內容粘到檔案中,然後進行後續安裝。
vim kube-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: rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.0
        command:
        - cp
        args:
        - -f
        - /flannel
        - /opt/cni/bin/flannel
        volumeMounts:
        - name: cni-plugin
          mountPath: /opt/cni/bin
      - name: install-cni
        image: quay.io/coreos/flannel:v0.15.1
        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: quay.io/coreos/flannel:v0.15.1
        command:
        - /opt/bin/flanneld
        args:
        - --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
        volumeMounts:
        - name: run
          mountPath: /run/flannel
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      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

②部署:

kubectl apply -f  kube-flannel.yml 

③執行如下命令,就會看到節點狀態為ready

kubectl get pods -n kube-system

kubectl get nodes
  1. 測試 kubernetes 叢集
    在 Kubernetes 叢集中建立一個 pod,驗證是否正常執行:
kubectl create deployment nginx --image=nginx 
kubectl expose deployment nginx --port=80 --type=NodePort 
kubectl get pod,svc

執行kubectl get pod,svc後,有一個埠號,在瀏覽器輸入任意一個node的IP加上這個埠號,能訪問nginx說明搭建成功。

相關文章