Kubernetes安装部署Master

版本查看:https://github.com/kubernetes/kubernetes/tree/v1.19.16

1、修改本地/etc/hosts文件
#将以下内容追加(>>)到 /etc/hosts文件

cat <<EOF >> /etc/hosts
172.26.48.4    k8s-master
172.26.48.5    k8s-node1
172.26.135.94  k8s-node2
EOF

2、CentOS 7 配置国内阿里云镜像源
#将以下内容替换(>)到 /etc/yum.repos.d/kubernetes.repo文件

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
# 如果改成 0,yum update 时 k8s就不会自动升级了
# enabled=0
enabled=1
gpgcheck=1
#修改repo_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

[] 中括号中的是repository id,唯一,用来标识不同仓库
name 仓库名称,自定义
baseurl 仓库地址
enable 是否启用该仓库,默认为1表示启用
gpgcheck 是否验证从该仓库获得程序包的合法性,1为验证
repo_gpgcheck 是否验证元数据的合法性 元数据就是程序包列表,1为验证
gpgkey=URL 数字签名的公钥文件所在位置,如果gpgcheck值为1,此处就需要指定gpgkey文件的位置,如果gpgcheck值为0就不需要此项了

3、关闭 SELinux,目的为了允许容器能够与本机文件系统交互。
临时关闭

setenforce 0

永久关闭

vim /etc/selinux/config

将SELINUX=enforcing改为SELINUX=disabled
设置后需要重启才能生效

systemctl daemon-reload

4、修改网络开启桥接网络支持,只针对(RHEL/CentOS 7)系统
本文的k8s网络使用flannel,该网络需要设置内核参数bridge-nf-call-iptables=1

cat <<EOF >  /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl -p /etc/sysctl.d/k8s.conf

5、关闭swap——不关闭配置节点或是配置master都会有问题
临时生效

swapoff -a

永久生效:

sed -ri 's/.*swap.*/#&/' /etc/fstab

6、安装 ebtables ethtool,否则后边执行 kubeadm init 的时候会报错

yum install ebtables ethtool -y

#然后修改当前内核状态 这个文件是在 Docker安装成功后才出现的

echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables

docker镜像加速

cat <<EOF > /etc/docker/daemon.json
{
  "registry-mirrors": ["https://43jugwwr.mirror.aliyuncs.com"]
}
EOF
systemctl daemon-reload
systemctl restart docker

7、安装kubelet、kubeadm、kubectl

yum install -y  kubelet-1.19.2 kubeadm-1.19.2 kubectl-1.19.2

systemctl enable kubelet && systemctl start kubelet && systemctl status kubelet

8、镜像准备
kubernetes 服务启动依赖很多镜像,是下载不下来的。这里我们可以去 Docker Hub 下载指定版本的镜像替代,下载完成后,通过 docker tag … 命令修改成指定名称的镜像即可。

kubeadm config images list

I0524 22:03:10.774681 19610 version.go:96] could not fetch a
Kubernetes version from the internet: unable to get URL
“https://dl.k8s.io/release/stable-1.txt”: Get
https://dl.k8s.io/release/stable-1.txt: net/http: request canceled
while waiting for connection (Client.Timeout exceeded while awaiting
headers) I0524 22:03:10.774766 19610 version.go:97] falling back to
the local client version: v1.14.2 k8s.gcr.io/kube-apiserver:v1.14.2
k8s.gcr.io/kube-controller-manager:v1.14.2
k8s.gcr.io/kube-scheduler:v1.14.2 k8s.gcr.io/kube-proxy:v1.14.2
k8s.gcr.io/pause:3.1 k8s.gcr.io/etcd:3.3.10 k8s.gcr.io/coredns:1.3.1

9、创建文件setup_image.sh 编写脚本批量下载镜像

#!/bin/bash
url=registry.aliyuncs.com/google_containers
version=v1.19.2
images=(`kubeadm config images list --kubernetes-version=$version|awk -F '/' '{print $2}'`)
for imagename in ${images[@]} ; do
  docker pull $url/$imagename
  docker tag $url/$imagename k8s.gcr.io/$imagename
  docker rmi -f $url/$imagename
done

执行setup_image.sh

./setup_images.sh

10、kubeadm 常用命令

# 启动一个 Kubernetes 主节点
[root@k8s-master deploy]# kubeadm init
# 启动一个 Kubernetes 工作节点并且将其加入到集群
[root@k8s-master deploy]# kubeadm join
# 更新一个 Kubernetes 集群到新版本
[root@k8s-master deploy]# kubeadm upgrade
# 如果使用 v1.7.x 或者更低版本的 kubeadm 初始化集群,您需要对集群做一些配置以便使用 kubeadm upgrade 命令
[root@k8s-master deploy]# kubeadm config
# 管理 kubeadm join 使用的令牌
[root@k8s-master deploy]# kubeadm token
# 重新生成链接 Token
[root@k8s-master deploy]# kubeadm token create --print-join-command
# 查看未失效的 Token列表
[root@k8s-master deploy]# kubeadm token list
# 还原 kubeadm init 或者 kubeadm join 对主机所做的任何更改
[root@k8s-master deploy]# kubeadm reset
# 查询所有 pod
[root@k8s-master deploy]# kubectl get pod -A -o wide
# 查询所有节点
[root@k8s-master deploy]# kubectl get nodes -o wide
# 查看k8s问题节点日志
[root@k8s-master deploy]# journalctl -f -u kubelet
# 查看命名空间
[root@k8s-master deploy]# kubectl get namespace

11、初始化 master (正常情况)
kubeadm init --pod-network-cidr=<pod网络IP地址/子网掩码> --kubernetes-version=<k8s版本>

kubeadm init  --pod-network-cidr=10.244.0.0/16 --kubernetes-version=v1.19.2

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

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 172.26.48.4:6443 --token yx9yza.rcb08m1giup70y63 \
    --discovery-token-ca-cert-hash sha256:f6548aa3508014ac5dab129231b54f5085f37fe8e6fc5d362f787be70a1a8a6e
[root@k8s-master deploy]#

12、好了初始化 Master 完成后,我们使用命令 kubectl get node 查看集群节点信息,但是你会发现并没有出现 Node 信息,反而报错如下:

[root@k8s-master deploy]# kubectl get pods
The connection to the server localhost:8080 was refused - did you specify the right host or port?

13、出现上步原因是没有执行init中日志提示的那一步
或者出现如下错误:

[root@dev15 .kube]# kubeadm config images list
could not convert cfg to an internal cfg: unable to get URL "https://dl.k8s.io/release/stable-1.11.txt": Get https://dl.k8s.io/release/stable-1.11.txt: dial tcp 35.201.71.162:443: i/o timeout

每个用户若要执行kubectl命令,需要添加权限,如下操作

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

然后所有命令都可运行了,效果如下:

[root@k8s-master deploy]# kubectl get node
NAME         STATUS     ROLES    AGE    VERSION
k8s-master   NotReady   master   9m8s   v1.14.2
[root@k8s-master deploy]#
[root@k8s-master deploy]# kubectl get pod -a
NAMESPACE     NAME                      READY   STATUS    RESTARTS   AGE
kube-system   coredns-fb8b8dccf-8xbcf   0/1     Pending   0          10s
kube-system   coredns-fb8b8dccf-ztxxg   0/1     Pending   0          10s
kube-system   kube-proxy-kcvph          1/1     Running   0          9s
[root@k8s-master deploy]#

14、安装 pod 网络附加组件(flannel网络配置详见 kubernetes网络介绍)
kubernetes 提供了很多种网络组件选择,有 Calia、Canal、Flannel、Kube-router、Romana、Weave Net 可以使用,这里我们选择 Flannel 作为网络组件。
注意: 为了使Flannel正常工作,执行kubeadm init命令时需要增加–pod-network-cidr=10.244.0.0/16参数,与kube-flannel.yml文件中的地址相同。Flannel适用于amd64,arm,arm64和ppc64le上工作,但使用除amd64平台得其他平台,你必须手动下载并替换amd64。

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",
        "Directrouting": true
      }
    }
---
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
        image: quay.io/coreos/flannel:v0.13.1-rc1
        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.13.1-rc1
        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
        hostPath:
          path: /etc/cni/net.d
      - name: flannel-cfg
        configMap:
          name: kube-flannel-cfg

# 查看当前系统的发行版信息
[root@k8s-master deploy]# lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.5.1804 (Core)
Release:        7.5.1804
Codename:       Core
[root@k8s-master deploy]#
[root@k8s-master deploy]# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
[root@k8s-master deploy]#
# 需要等待一小会儿,在查看运行状态就都是 Running 了
[root@k8s-master deploy]# kubectl get pod
NAMESPACE     NAME                                 READY   STATUS    RESTARTS   AGE
kube-system   coredns-fb8b8dccf-8xbcf              1/1     Running   0          2m8s
kube-system   coredns-fb8b8dccf-ztxxg              1/1     Running   0          2m8s
kube-system   etcd-k8s-master                      1/1     Running   0          81s
kube-system   kube-apiserver-k8s-master            1/1     Running   0          81s
kube-system   kube-controller-manager-k8s-master   1/1     Running   0          74s
kube-system   kube-flannel-ds-amd64-hk4wt          1/1     Running   0          51s
kube-system   kube-proxy-kcvph                     1/1     Running   0          2m7s
kube-system   kube-scheduler-k8s-master            1/1     Running   0          69s
[root@k8s-master deploy]#

Kubernetes安装部署Node

1、重复安装master的前9步。
2、将node节点挂载到master上(这个是master生成的token)

kubeadm join 172.26.48.4:6443 --token qc1eie.tviq9mcibgdssqgm \
    --discovery-token-ca-cert-hash sha256:4502298f771b00714e6f65e9a34a8f5651094aac917f1d42e9bcaf20658525bf

3、如果 token 失效或者没有token,请在master机器上运行如下命令获得token

kubeadm token create --print-join-command

4、如果 K8s装错了 可以重置

kubeadm reset

彻底删除Kubernetes

1 彻底删除 k8s
kubeadm reset -f

yum remove -y kubelet kubeadm kubectl kubernetes-cni

systemctl daemon-reload

rm -rf ~/.kube/
rm -rf /etc/kubernetes/
rm -rf /etc/systemd/system/kubelet.service.d
rm -rf /etc/systemd/system/kubelet.service
rm -rf /usr/bin/kube*
rm -rf /etc/cni
rm -rf /opt/cni
rm -rf /var/lib/etcd
rm -rf /var/etcd

##清除网络
rm -rf /var/lib/cni/
rm -rf /etc/cni/net.d/*
rm -rf /var/lib/kubelet/*
ifconfig cni0 down
ifconfig flannel.1 down
ifconfig docker0 down
ip link delete cni0
ip link delete flannel.1

systemctl restart docker
2 重新下载
yum install -y kubelet-1.19.2 kubeadm-1.19.2 kubectl-1.19.2 kubernetes-cni-0.8.7

systemctl enable kubelet && systemctl start kubelet && systemctl status kubelet

注意:安装完成后,如果不能启动kubelet, 重启操作系统即可

Logo

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

更多推荐