1.4.4.8.4 配置 kube-config 文件及网络组件

kube-config 文件中包含 kube-apiserver 地址及相关认证信息

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

配置 kube-config 文件

# 默认没有权限查看
[root@k8s-master1 ~]# kubectl get node
The connection to the server localhost:8080 was refused - did you specify the right host or port?
[root@k8s-master1 ~]# 

# 根据提示操作
[root@k8s-master1 ~]# mkdir -p $HOME/.kube
[root@k8s-master1 ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@k8s-master1 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config
[root@k8s-master1 ~]# 

# 再次执行即可成功
[root@k8s-master1 ~]# kubectl get node
NAME                     STATUS     ROLES                  AGE     VERSION
k8s-master1.waluna.top   NotReady   control-plane,master   2m41s   v1.21.1
[root@k8s-master1 ~]# 

# /etc/kubernetes/admin.conf存放是证书信息,admin账号的信息,拿到这个信息就可以有权限执行kubectl进行管理node节点

部署网路组件 flannel:

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/

flannel 地址:

https://github.com/flannel-io/flannel   # GitHub项目地址
https://github.com/flannel-io/flannel#deploying-flannel-manually    # 部署教程

安装网络组件,只需要修改一处,service网段

[root@k8s-master1 ~]# vim kube-flannel.yml
[root@k8s-master1 ~]# cat 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.10.0.0/16",    # 原先为10.244.0.0/16,需改成pod网段
      "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
[root@k8s-master1 ~]# kubectl apply -f kube-flannel.yml
Warning: policy/v1beta1 PodSecurityPolicy is deprecated in v1.21+, unavailable in v1.25+
podsecuritypolicy.policy/psp.flannel.unprivileged created
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.apps/kube-flannel-ds created
[root@k8s-master1 ~]# 

# 验证master节点状态,需要等一两分钟左右才会变成Ready
[root@k8s-master1 ~]# kubectl get node
NAME                     STATUS   ROLES                  AGE     VERSION
k8s-master1.waluna.top   Ready    control-plane,master   8m23s   v1.21.1
[root@k8s-master1 ~]# 

# 查看pod信息
[root@k8s-master1 ~]# kubectl get pod -A
NAMESPACE     NAME                                             READY   STATUS    RESTARTS   AGE
kube-system   coredns-558bd4d5db-2z2w6                         1/1     Running   0          8m10s
kube-system   coredns-558bd4d5db-m9tbs                         1/1     Running   0          8m10s
kube-system   etcd-k8s-master1.waluna.top                      1/1     Running   0          8m12s
kube-system   kube-apiserver-k8s-master1.waluna.top            1/1     Running   0          8m12s
kube-system   kube-controller-manager-k8s-master1.waluna.top   1/1     Running   0          8m12s
kube-system   kube-flannel-ds-rcqcr                            1/1     Running   0          61s
kube-system   kube-proxy-5xnhb                                 1/1     Running   0          8m11s
kube-system   kube-scheduler-k8s-master1.waluna.top            1/1     Running   0          8m12s
[root@k8s-master1 ~]# 

查看组件状态

[root@k8s-master1 ~]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS      MESSAGE                                                                                       ERROR
controller-manager   Unhealthy   Get "http://127.0.0.1:10252/healthz": dial tcp 127.0.0.1:10252: connect: connection refused   
scheduler            Unhealthy   Get "http://127.0.0.1:10251/healthz": dial tcp 127.0.0.1:10251: connect: connection refused   
etcd-0               Healthy     {"health":"true"}                                                                             
[root@k8s-master1 ~]# 

# 查看端口状态
[root@k8s-master1 ~]# ss -ntl
State     Recv-Q     Send-Q          Local Address:Port            Peer Address:Port     
LISTEN    0          128                 127.0.0.1:10248                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10249                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:40457                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:2379                 0.0.0.0:*        
LISTEN    0          128                  10.0.0.9:2379                 0.0.0.0:*        
LISTEN    0          128                  10.0.0.9:2380                 0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:2381                 0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10257                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10259                0.0.0.0:*        
LISTEN    0          128             127.0.0.53%lo:53                   0.0.0.0:*        
LISTEN    0          128                   0.0.0.0:22                   0.0.0.0:*        
LISTEN    0          128                         *:10250                      *:*        
LISTEN    0          128                         *:6443                       *:*        
LISTEN    0          128                         *:10256                      *:*        
LISTEN    0          128                      [::]:22                      [::]:*        
[root@k8s-master1 ~]# 

原因是是 /etc/kubernetes/manifests/ 下的 kube-controller-manager.yamlkube-scheduler.yaml 设置的默认端口是0导致的。解决办法是将两个文件中注释掉 - --port=0 选项即可,并重启 kubelet 服务

# 解决方法
# 在26行
[root@k8s-master1 ~]# vim /etc/kubernetes/manifests/kube-controller-manager.yaml
[root@k8s-master1 ~]# cat /etc/kubernetes/manifests/kube-controller-manager.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    component: kube-controller-manager
    tier: control-plane
  name: kube-controller-manager
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-controller-manager
    - --allocate-node-cidrs=true
    - --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf
    - --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf
    - --bind-address=127.0.0.1
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --cluster-cidr=10.10.0.0/16
    - --cluster-name=kubernetes
    - --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt
    - --cluster-signing-key-file=/etc/kubernetes/pki/ca.key
    - --controllers=*,bootstrapsigner,tokencleaner
    - --kubeconfig=/etc/kubernetes/controller-manager.conf
    - --leader-elect=true
      #- --port=0   # 注释此行
    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
    - --root-ca-file=/etc/kubernetes/pki/ca.crt
    - --service-account-private-key-file=/etc/kubernetes/pki/sa.key
    - --service-cluster-ip-range=10.20.0.0/16
    - --use-service-account-credentials=true
    image: k8s.gcr.io/kube-controller-manager:v1.21.1
    imagePullPolicy: IfNotPresent
    livenessProbe:
      failureThreshold: 8
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10257
        scheme: HTTPS
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 15
    name: kube-controller-manager
    resources:
      requests:
        cpu: 200m
    startupProbe:
      failureThreshold: 24
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10257
        scheme: HTTPS
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 15
    volumeMounts:
    - mountPath: /etc/ssl/certs
      name: ca-certs
      readOnly: true
    - mountPath: /etc/ca-certificates
      name: etc-ca-certificates
      readOnly: true
    - mountPath: /usr/libexec/kubernetes/kubelet-plugins/volume/exec
      name: flexvolume-dir
    - mountPath: /etc/kubernetes/pki
      name: k8s-certs
      readOnly: true
    - mountPath: /etc/kubernetes/controller-manager.conf
      name: kubeconfig
      readOnly: true
    - mountPath: /usr/local/share/ca-certificates
      name: usr-local-share-ca-certificates
      readOnly: true
    - mountPath: /usr/share/ca-certificates
      name: usr-share-ca-certificates
      readOnly: true
  hostNetwork: true
  priorityClassName: system-node-critical
  volumes:
  - hostPath:
      path: /etc/ssl/certs
      type: DirectoryOrCreate
    name: ca-certs
  - hostPath:
      path: /etc/ca-certificates
      type: DirectoryOrCreate
    name: etc-ca-certificates
  - hostPath:
      path: /usr/libexec/kubernetes/kubelet-plugins/volume/exec
      type: DirectoryOrCreate
    name: flexvolume-dir
  - hostPath:
      path: /etc/kubernetes/pki
      type: DirectoryOrCreate
    name: k8s-certs
  - hostPath:
      path: /etc/kubernetes/controller-manager.conf
      type: FileOrCreate
    name: kubeconfig
  - hostPath:
      path: /usr/local/share/ca-certificates
      type: DirectoryOrCreate
    name: usr-local-share-ca-certificates
  - hostPath:
      path: /usr/share/ca-certificates
      type: DirectoryOrCreate
    name: usr-share-ca-certificates
status: {}
[root@k8s-master1 ~]# 

# 在第19行
[root@k8s-master1 ~]# vim /etc/kubernetes/manifests/kube-scheduler.yaml
[root@k8s-master1 ~]# cat /etc/kubernetes/manifests/kube-scheduler.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    component: kube-scheduler
    tier: control-plane
  name: kube-scheduler
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-scheduler
    - --authentication-kubeconfig=/etc/kubernetes/scheduler.conf
    - --authorization-kubeconfig=/etc/kubernetes/scheduler.conf
    - --bind-address=127.0.0.1
    - --kubeconfig=/etc/kubernetes/scheduler.conf
    - --leader-elect=true
      #- --port=0   # 注释此行
    image: k8s.gcr.io/kube-scheduler:v1.21.1
    imagePullPolicy: IfNotPresent
    livenessProbe:
      failureThreshold: 8
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10259
        scheme: HTTPS
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 15
    name: kube-scheduler
    resources:
      requests:
        cpu: 100m
    startupProbe:
      failureThreshold: 24
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10259
        scheme: HTTPS
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 15
    volumeMounts:
    - mountPath: /etc/kubernetes/scheduler.conf
      name: kubeconfig
      readOnly: true
  hostNetwork: true
  priorityClassName: system-node-critical
  volumes:
  - hostPath:
      path: /etc/kubernetes/scheduler.conf
      type: FileOrCreate
    name: kubeconfig
status: {}
[root@k8s-master1 ~]# 

# 这里测试不需要重启服务即可生效,如果不生效需要重启kubelet服务

# 验证端口状态,打开了10251和10252端口
[root@k8s-master1 ~]# ss -ntl
State     Recv-Q     Send-Q          Local Address:Port            Peer Address:Port     
LISTEN    0          128                 127.0.0.1:10248                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10249                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:40457                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:2379                 0.0.0.0:*        
LISTEN    0          128                  10.0.0.9:2379                 0.0.0.0:*        
LISTEN    0          128                  10.0.0.9:2380                 0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:2381                 0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10257                0.0.0.0:*        
LISTEN    0          128                 127.0.0.1:10259                0.0.0.0:*        
LISTEN    0          128             127.0.0.53%lo:53                   0.0.0.0:*        
LISTEN    0          128                   0.0.0.0:22                   0.0.0.0:*        
LISTEN    0          128                         *:10250                      *:*        
LISTEN    0          128                         *:10251                      *:*        
LISTEN    0          128                         *:6443                       *:*        
LISTEN    0          128                         *:10252                      *:*        
LISTEN    0          128                         *:10256                      *:*        
LISTEN    0          128                      [::]:22                      [::]:*        
[root@k8s-master1 ~]# 

# 再次查看组件状态
[root@k8s-master1 ~]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok                  
controller-manager   Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
[root@k8s-master1 ~]#