安装前准备

这里部署K8S 一主两从,需要三台虚拟机
分别是

192.168.31.100
192.168.31.101
192.168.31.102

192.168.31.100 部署为主节点,其他两台部署为工作节点
每台虚拟机都需要2核2G,这是最低要求
每台虚拟机都需要安装docker

安装docker

对三台虚拟机安装docker

yum install -y yum-utils device-mapper-persistent-data lvm2
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum install docker-ce -y

启动docker并设置开机启动

systemctl start docker
systemctl enable docker

测试docker安装情况

docker version

在这里插入图片描述
安装成功

安装K8S

三台虚拟机都需要配置

1、关闭防火墙

systemctl stop firewalld
systemctl disable firewalld

2、关闭 selinux

永久关闭

sed -i 's/enforcing/disabled/' /etc/selinux/config

临时关闭

setenforce 0

因为永久关闭需要重启才有效,所以这里两步都要执行

3、关闭 swap

永久关闭

vi /etc/fstab
# 注释掉swap这行
# /dev/mapper/centos-swap swap swap defaults 0 0

临时关闭

swapoff -a

同上,两步都要执行

4、给三台机器分别设置主机名

192.168.31.100 虚拟机上

hostnamectl set-hostname k8s-master

192.168.31.101 虚拟机上

hostnamectl set-hostname k8s-worker1

192.168.31.102 虚拟机上

hostnamectl set-hostname k8s-worker2

5、在 k8s-master机器添加hosts,执行如下命令,ip需要修改成你自己机器的ip

cat >> /etc/hosts << EOF
192.168.31.100 k8s-master
192.168.31.101 k8s-worker1
192.168.31.102 k8s-worker2
EOF

6、将桥接的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  # 生效

7、设置时间同步

yum install ntpdate -y
ntpdate time.windows.com

8、添加k8s 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

9、如果之前安装过k8s,先卸载旧版本

yum remove -y kubelet kubeadm kubectl

10、安装kubelet、kubeadm、kubectl 指定版本为1.23.6

yum install kubectl-1.23.6 kubeadm-1.23.6 kubelet-1.23.6 -y

启动kubelet 并且设置开机启动

systemctl start kubelet
systemctl enable kubelet

11、主节点上进行初始化

第一个IP要写自己的主节点IP,其他的不变

kubeadm init --apiserver-advertise-address=192.168.31.100 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.23.6 --service-cidr=10.96.0.0/12 --pod-network-cidr=10.244.0.0/16 --v=5

在这里插入图片描述
初始化报错
按照提示执行命令
在这里插入图片描述
这里说明kubelet没有启动

journalctl -xeu kubelet

查看日志
在这里插入图片描述
这里需要将docker设置为 systemd

vi /etc/docker/daemon.json

输入内容
这里顺便把docker源也配置了

{
  "registry-mirrors": [
    "https://registry.docker-cn.com"
  ],
  "dns": ["8.8.8.8", "8.8.4.4"],
  "exec-opts": ["native.cgroupdriver=systemd"]
}

重启docker 和 kubelet

systemctl restart docker
systemctl restart kubelet

重新运行

systemctl status kubelet

在这里插入图片描述
启动完毕

重新初始化

kubeadm init --apiserver-advertise-address=192.168.31.99 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.23.6 --service-cidr=10.96.0.0/12 --pod-network-cidr=10.244.0.0/16 --ignore-preflight-errors=all --v=5

这里忽略错误运行,因为前面第一次初始化过程中已经有启动部分服务了

看到这段代码,说明已经初始化成功了

[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.31.100:6443 --token uc8655.kje89tanxx58lyh6 \
	--discovery-token-ca-cert-hash sha256:5a42a369fbb783bfc5bd73c9746e4c2d74c96440af8be8feae31bae2fa2f8c7a 

这里按照提示在master执行命令

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

这一段表示将节点加入到192.168.31.100这个master的集群,两台从节点执行这段代码。
执行这段代码,代表作为这台机器的从节点,需要参与运行部署的服务,主节点可以执行,也可以不执行,执行代表主节点也要做部署工作,这里推荐主节点不执行

kubeadm join 192.168.31.100:6443 --token uc8655.kje89tanxx58lyh6 \
	--discovery-token-ca-cert-hash sha256:5a42a369fbb783bfc5bd73c9746e4c2d74c96440af8be8feae31bae2fa2f8c7a

执行kubectl get nodes
在这里插入图片描述
这里我们看到所有节点状态都是NotReady,说明集群不正常

kubectl describe nodes

查看集群状态,这里可以看到报错信息

在这里插入图片描述

container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady 
message:docker: network plugin is not ready: cni config uninitialized

这里需要下载flannel镜像
在k8s主节点上运行

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

如果无法访问https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
可以新建一个文件 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.2
        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.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: quay.io/coreos/flannel:v0.15.0
        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

稍等片刻
自动生成 /etc/cni/net.d/10-flannel.conflist 之后,即可正常使用
在这里插入图片描述
看到3个节点都已经是Ready


这里就安装完成了

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐