zoukankan      html  css  js  c++  java
  • Kubernetes全栈架构师(二进制高可用安装k8s集群部署篇)--学习笔记

    目录

    • 二进制高可用基本配置
    • 二进制系统和内核升级
    • 二进制基本组件安装
    • 二进制生成证书详解
    • 二进制高可用及etcd配置
    • 二进制K8s组件配置
    • 二进制使用Bootstrapping自动颁发证书
    • 二进制Node节点及Calico配置

    二进制高可用基本配置

    k8s高可用架构解析,高可用Kubernetes集群规划,设置静态ip,请参考上一篇文章

    配置所有节点hosts文件(发送键输到入所有会话)

    vi /etc/hosts
    
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    
    192.168.232.128 k8s-master01
    192.168.232.129 k8s-master02
    192.168.232.130 k8s-master03
    192.168.232.236 k8s-master-lb # 如果不是高可用集群,该IP为Master01的IP
    192.168.232.131 k8s-node01
    192.168.232.132 k8s-node02
    

    host节点主要是控制节点使用,控制节点下载一些文件,然后通过sskey传到其他的节点上面

    CentOS 7安装yum源如下:

    curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
    yum install -y yum-utils device-mapper-persistent-data lvm2
    yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
    

    必备工具安装

    yum install wget jq psmisc vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 git -y
    

    所有节点关闭firewalld 、dnsmasq、selinux(CentOS7需要关闭NetworkManager,CentOS8不需要)

    systemctl disable --now firewalld 
    systemctl disable --now dnsmasq
    systemctl disable --now NetworkManager
    
    setenforce 0
    sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/sysconfig/selinux
    sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
    

    所有节点关闭swap分区,fstab注释swap

    swapoff -a && sysctl -w vm.swappiness=0
    sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab
    

    所有节点同步时间

    安装ntpdate

    rpm -ivh http://mirrors.wlnmp.com/centos/wlnmp-release-centos.noarch.rpm
    yum install ntpdate -y
    

    所有节点同步时间。时间同步配置如下:

    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    echo 'Asia/Shanghai' >/etc/timezone
    ntpdate time2.aliyun.com
    

    检查时间

    date
    

    加入到crontab

    crontab -e
    
    # 添加以下内容
    */5 * * * * /usr/sbin/ntpdate time2.aliyun.com
    

    所有节点配置limit:

    ulimit -SHn 65535
    
    vim /etc/security/limits.conf
    # 末尾添加如下内容
    * soft nofile 655360
    * hard nofile 131072
    * soft nproc 655350
    * hard nproc 655350
    * soft memlock unlimited
    * hard memlock unlimited 
    

    Master01节点(取消发送键输到入所有会话)免密钥登录其他节点,安装过程中生成配置文件和证书均在Master01上操作,集群管理也在Master01上操作,阿里云或者AWS上需要单独一台kubectl服务器。密钥配置如下:

    ssh-keygen -t rsa
    

    Master01配置免密码登录其他节点

    for i in k8s-master01 k8s-master02 k8s-master03 k8s-node01 k8s-node02;do ssh-copy-id -i .ssh/id_rsa.pub $i;done
    

    所有节点安装基本工具(发送键输到入所有会话)

    yum install wget jq psmisc vim net-tools yum-utils device-mapper-persistent-data lvm2 git -y
    

    Master01下载安装文件(取消发送键输到入所有会话)

    cd /root/ ; git clone https://github.com/dotbalo/k8s-ha-install.git
    

    无法下载的可以通过本地拉取压缩再上传到服务器

    yum安装zip

    yum install -y unzip zip
    

    解压文件

    unzip k8s-ha-install.zip
    

    所有节点(发送键输到入所有会话)升级系统并重启,此处升级没有升级内核,下节会单独升级内核:

    yum update -y --exclude=kernel* && reboot #CentOS7需要升级,CentOS8可以按需升级系统
    

    二进制系统和内核升级

    CentOS7 需要升级内核至4.18+,本地升级的版本为4.19

    在master01节点(取消发送键输入到所有会话)下载内核:

    cd /root
    wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-devel-4.19.12-1.el7.elrepo.x86_64.rpm
    wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-4.19.12-1.el7.elrepo.x86_64.rpm
    

    从master01节点传到其他节点:

    for i in k8s-master02 k8s-master03 k8s-node01 k8s-node02;do scp kernel-ml-4.19.12-1.el7.elrepo.x86_64.rpm kernel-ml-devel-4.19.12-1.el7.elrepo.x86_64.rpm $i:/root/ ; done
    

    所有节点安装内核(发送键输到入所有会话)

    cd /root && yum localinstall -y kernel-ml*
    

    所有节点更改内核启动顺序

    grub2-set-default  0 && grub2-mkconfig -o /etc/grub2.cfg
    
    grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"
    

    检查默认内核是不是4.19

    grubby --default-kernel
    

    所有节点重启,然后检查内核是不是4.19

    reboot
    
    uname -a
    

    所有节点安装ipvsadm(实现负载均衡):

    yum install ipvsadm ipset sysstat conntrack libseccomp -y
    

    所有节点配置ipvs模块,在内核4.19+版本nf_conntrack_ipv4已经改为nf_conntrack, 4.18以下使用nf_conntrack_ipv4即可:

    modprobe -- ip_vs
    modprobe -- ip_vs_rr
    modprobe -- ip_vs_wrr
    modprobe -- ip_vs_sh
    modprobe -- nf_conntrack
    vim /etc/modules-load.d/ipvs.conf 
    	# 加入以下内容
    ip_vs
    ip_vs_lc
    ip_vs_wlc
    ip_vs_rr
    ip_vs_wrr
    ip_vs_lblc
    ip_vs_lblcr
    ip_vs_dh
    ip_vs_sh
    ip_vs_fo
    ip_vs_nq
    ip_vs_sed
    ip_vs_ftp
    ip_vs_sh
    nf_conntrack
    ip_tables
    ip_set
    xt_set
    ipt_set
    ipt_rpfilter
    ipt_REJECT
    ipip
    

    然后执行

    systemctl enable --now systemd-modules-load.service
    

    检查是否加载(需要重启后才可以加载):

    lsmod | grep -e ip_vs -e nf_conntrack
    

    开启一些k8s集群中必须的内核参数,所有节点配置k8s内核:

    cat <<EOF > /etc/sysctl.d/k8s.conf
    net.ipv4.ip_forward = 1
    net.bridge.bridge-nf-call-iptables = 1
    net.bridge.bridge-nf-call-ip6tables = 1
    fs.may_detach_mounts = 1
    vm.overcommit_memory=1
    vm.panic_on_oom=0
    fs.inotify.max_user_watches=89100
    fs.file-max=52706963
    fs.nr_open=52706963
    net.netfilter.nf_conntrack_max=2310720
    
    net.ipv4.tcp_keepalive_time = 600
    net.ipv4.tcp_keepalive_probes = 3
    net.ipv4.tcp_keepalive_intvl =15
    net.ipv4.tcp_max_tw_buckets = 36000
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_max_orphans = 327680
    net.ipv4.tcp_orphan_retries = 3
    net.ipv4.tcp_syncookies = 1
    net.ipv4.tcp_max_syn_backlog = 16384
    net.ipv4.ip_conntrack_max = 65536
    net.ipv4.tcp_max_syn_backlog = 16384
    net.ipv4.tcp_timestamps = 0
    net.core.somaxconn = 16384
    EOF
    sysctl --system
    

    net.ipv4.ip_forward 不打开的话跨主机通讯不了

    所有节点配置完内核后,重启服务器,保证重启后内核依旧加载

    reboot
    
    lsmod | grep --color=auto -e ip_vs -e nf_conntrack
    

    二进制基本组件安装

    • Docker安装
    • K8s及etcd安装

    Docker安装

    所有节点安装Docker-ce 19.03(官方推荐)

    yum install docker-ce-19.03.* -y
    

    由于新版kubelet建议使用systemd,所以可以把docker的CgroupDriver改成systemd

    mkdir /etc/docker
    cat > /etc/docker/daemon.json <<EOF
    {
      "exec-opts": ["native.cgroupdriver=systemd"]
    }
    EOF
    

    所有节点设置开机自启动Docker:

    systemctl daemon-reload && systemctl enable --now docker
    

    K8s及etcd安装

    Master01(取消发送键输入到所有的会话)下载kubernetes安装包

    访问官网获取最新版本:https://github.com/kubernetes/kubernetes

    进入CHANGELOG目录,点击 CHANGELOG-1.20.md,再点击 Server Binaries,可以看到目前最新的是1.20.9,点击 kubernetes-server-linux-amd64.tar.gz 进行下载,如果有更新的版本需要下载最新的 1.20.x 版本

    wget https://dl.k8s.io/v1.20.9/kubernetes-server-linux-amd64.tar.gz
    

    如果下载不了可以通过本地下载再上传到服务器

    下载etcd安装包(3.4.13是官方推荐版本,已经经过验证)

    wget https://github.com/etcd-io/etcd/releases/download/v3.4.13/etcd-v3.4.13-linux-amd64.tar.gz
    

    如果下载不了可以通过本地下载再上传到服务器

    二进制的安装其实解压之后就安装完成了

    解压kubernetes安装文件

    tar -xf kubernetes-server-linux-amd64.tar.gz  --strip-components=3 -C /usr/local/bin kubernetes/server/bin/kube{let,ctl,-apiserver,-controller-manager,-scheduler,-proxy}
    

    解压etcd安装文件

    tar -zxvf etcd-v3.4.13-linux-amd64.tar.gz --strip-components=1 -C /usr/local/bin etcd-v3.4.13-linux-amd64/etcd{,ctl}
    

    版本查看

    kubelet --version
    
    etcdctl version
    

    将组件发送到其他节点

    MasterNodes='k8s-master02 k8s-master03'
    WorkNodes='k8s-node01 k8s-node02'
    for NODE in $MasterNodes; do echo $NODE; scp /usr/local/bin/kube{let,ctl,-apiserver,-controller-manager,-scheduler,-proxy} $NODE:/usr/local/bin/; scp /usr/local/bin/etcd* $NODE:/usr/local/bin/; done
    for NODE in $WorkNodes; do     scp /usr/local/bin/kube{let,-proxy} $NODE:/usr/local/bin/ ; done
    

    所有节点创建/opt/cni/bin目录(发送键输入到所有的会话)

    mkdir -p /opt/cni/bin
    

    查看分支(取消发送键输入到所有的会话)

    cd k8s-ha-install/
    
    git branch -a
    

    Master01切换到1.20.x分支(其他版本可以切换到其他分支)

    git checkout manual-installation-v1.20.x
    

    二进制生成证书详解

    • etcd证书
    • k8s组件证书

    二进制安装最关键步骤,一步错误全盘皆输,一定要注意每个步骤都要是正确的

    Master01下载生成证书工具

    wget "https://pkg.cfssl.org/R1.2/cfssl_linux-amd64" -O /usr/local/bin/cfssl
    
    wget "https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64" -O /usr/local/bin/cfssljson
    
    chmod +x /usr/local/bin/cfssl /usr/local/bin/cfssljson
    

    etcd证书

    所有Master节点创建etcd证书目录(发送键输入到所有的会话,取消node节点)

    mkdir /etc/etcd/ssl -p
    

    所有节点创建kubernetes相关目录(发送键输入到所有的会话)

    mkdir -p /etc/kubernetes/pki
    

    Master01节点生成etcd证书(取消发送键输入到所有的会话)

    生成证书的CSR文件:证书签名请求文件,配置了一些域名、公司、单位

    # 这个目录有我们生成证书需要用到的csr文件
    cd /root/k8s-ha-install/pki
    
    # 生成etcd CA证书和CA证书的key
    cfssl gencert -initca etcd-ca-csr.json | cfssljson -bare /etc/etcd/ssl/etcd-ca
    

    查看生成的key

    ls /etc/etcd/ssl/
    

    颁发证书

    cfssl gencert 
       -ca=/etc/etcd/ssl/etcd-ca.pem 
       -ca-key=/etc/etcd/ssl/etcd-ca-key.pem 
       -config=ca-config.json 
       -hostname=127.0.0.1,k8s-master01,k8s-master02,k8s-master03,192.168.232.128,192.168.232.129,192.168.232.130 
       -profile=kubernetes 
       etcd-csr.json | cfssljson -bare /etc/etcd/ssl/etcd
    

    查看生成证书

    ls /etc/etcd/ssl/
    

    生成内容

    etcd-ca.csr  etcd-ca-key.pem  etcd-ca.pem  etcd.csr  etcd-key.pem  etcd.pem
    

    将证书复制到其他节点

    MasterNodes='k8s-master02 k8s-master03'
    WorkNodes='k8s-node01 k8s-node02'
    
    for NODE in $MasterNodes; do
         ssh $NODE "mkdir -p /etc/etcd/ssl"
         for FILE in etcd-ca-key.pem  etcd-ca.pem  etcd-key.pem  etcd.pem; do
           scp /etc/etcd/ssl/${FILE} $NODE:/etc/etcd/ssl/${FILE}
         done
     done
    

    k8s组件证书

    Master01生成kubernetes证书

    cd /root/k8s-ha-install/pki
    
    cfssl gencert -initca ca-csr.json | cfssljson -bare /etc/kubernetes/pki/ca
    

    查看生成的key

    ls /etc/kubernetes/pki
    

    生成apiserver的客户端证书

    10.96.0.是k8s service的网段,如果说需要更改k8s service网段,那就需要更改10.96.0.1,如果不是高可用集群,192.168.232.236为Master01的IP

    cfssl gencert   -ca=/etc/kubernetes/pki/ca.pem   -ca-key=/etc/kubernetes/pki/ca-key.pem   -config=ca-config.json   -hostname=10.96.0.1,192.168.232.236,127.0.0.1,kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster,kubernetes.default.svc.cluster.local,192.168.232.128,192.168.232.129,192.168.232.130   -profile=kubernetes   apiserver-csr.json | cfssljson -bare /etc/kubernetes/pki/apiserver
    

    查看生成的证书

    ls /etc/kubernetes/pki
    

    生成apiserver的聚合证书。Requestheader-client-xxx requestheader-allowwd-xxx:aggerator

    cfssl gencert   -initca front-proxy-ca-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-ca 
    
    cfssl gencert   -ca=/etc/kubernetes/pki/front-proxy-ca.pem   -ca-key=/etc/kubernetes/pki/front-proxy-ca-key.pem   -config=ca-config.json   -profile=kubernetes   front-proxy-client-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-client
    

    生成 controller-manage 的证书

    cfssl gencert 
       -ca=/etc/kubernetes/pki/ca.pem 
       -ca-key=/etc/kubernetes/pki/ca-key.pem 
       -config=ca-config.json 
       -profile=kubernetes 
       manager-csr.json | cfssljson -bare /etc/kubernetes/pki/controller-manager
    
    # 注意,如果不是高可用集群,192.168.232.236:8443改为master01的地址,8443改为apiserver的端口,默认是6443
    # set-cluster:设置一个集群项
    kubectl config set-cluster kubernetes 
         --certificate-authority=/etc/kubernetes/pki/ca.pem 
         --embed-certs=true 
         --server=https://192.168.232.236:8443 
         --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
    
    # set-credentials 设置一个用户项
    kubectl config set-credentials system:kube-controller-manager 
         --client-certificate=/etc/kubernetes/pki/controller-manager.pem 
         --client-key=/etc/kubernetes/pki/controller-manager-key.pem 
         --embed-certs=true 
         --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
    
    # 设置一个环境项,一个上下文
    kubectl config set-context system:kube-controller-manager@kubernetes 
        --cluster=kubernetes 
        --user=system:kube-controller-manager 
        --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
    
    # 使用某个环境当做默认环境
    kubectl config use-context system:kube-controller-manager@kubernetes 
         --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
    

    生成 scheduler 的证书

    cfssl gencert 
       -ca=/etc/kubernetes/pki/ca.pem 
       -ca-key=/etc/kubernetes/pki/ca-key.pem 
       -config=ca-config.json 
       -profile=kubernetes 
       scheduler-csr.json | cfssljson -bare /etc/kubernetes/pki/scheduler
    
    # 注意,如果不是高可用集群,192.168.232.236:8443改为master01的地址,8443改为apiserver的端口,默认是6443
    kubectl config set-cluster kubernetes 
         --certificate-authority=/etc/kubernetes/pki/ca.pem 
         --embed-certs=true 
         --server=https://192.168.232.236:8443 
         --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
    
    kubectl config set-credentials system:kube-scheduler 
         --client-certificate=/etc/kubernetes/pki/scheduler.pem 
         --client-key=/etc/kubernetes/pki/scheduler-key.pem 
         --embed-certs=true 
         --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
    
    kubectl config set-context system:kube-scheduler@kubernetes 
         --cluster=kubernetes 
         --user=system:kube-scheduler 
         --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
    
    kubectl config use-context system:kube-scheduler@kubernetes 
         --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
    

    生成admin的证书

    cfssl gencert 
       -ca=/etc/kubernetes/pki/ca.pem 
       -ca-key=/etc/kubernetes/pki/ca-key.pem 
       -config=ca-config.json 
       -profile=kubernetes 
       admin-csr.json | cfssljson -bare /etc/kubernetes/pki/admin
    
    # 注意,如果不是高可用集群,192.168.232.236:8443改为master01的地址,8443改为apiserver的端口,默认是6443
    kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.232.236:8443     --kubeconfig=/etc/kubernetes/admin.kubeconfig
    
    kubectl config set-credentials kubernetes-admin     --client-certificate=/etc/kubernetes/pki/admin.pem     --client-key=/etc/kubernetes/pki/admin-key.pem     --embed-certs=true     --kubeconfig=/etc/kubernetes/admin.kubeconfig
    
    kubectl config set-context kubernetes-admin@kubernetes     --cluster=kubernetes     --user=kubernetes-admin     --kubeconfig=/etc/kubernetes/admin.kubeconfig
    
    kubectl config use-context kubernetes-admin@kubernetes     --kubeconfig=/etc/kubernetes/admin.kubeconfig
    

    我们用同样的命令生成了 admin.kubeconfig,scheduler.kubeconfig,controller-manager.kubeconfig,它们之间是如何区分的?

    查看 admin-csr.json

    cat admin-csr.json
    
    {
      "CN": "admin", # 域名
      "key": {
        "algo": "rsa",
        "size": 2048
      },
      "names": [
        {
          "C": "CN",
          "ST": "Beijing",
          "L": "Beijing",
          "O": "system:masters", # 部门,相当于admin是属于哪个组的
          "OU": "Kubernetes-manual"
        }
      ]
    }
    

    我们生成的证书会定义一个用户 admin,它是属于 system:masters 这个组,k8s 安装的时候会有一个 clusterrole,它是一个集群角色,相当于一个配置,它有着集群最高的管理权限,同时会创建一个 clusterrolebinding,它会把 admin 绑到 system:masters 这个组上,然后这个组上的所有用户都会有这个集群的权限

    创建ServiceAccount Key -> secret

    openssl genrsa -out /etc/kubernetes/pki/sa.key 2048
    
    openssl rsa -in /etc/kubernetes/pki/sa.key -pubout -out /etc/kubernetes/pki/sa.pub
    

    ServiceAccount 是 k8s 一种认证方式,创建 ServiceAccount 的时候会创建一个与之绑定的 secret,这个 secret 会生成一个 token

    发送证书至其他节点

    for NODE in k8s-master02 k8s-master03; do 
    for FILE in $(ls /etc/kubernetes/pki | grep -v etcd); do 
    scp /etc/kubernetes/pki/${FILE} $NODE:/etc/kubernetes/pki/${FILE};
    done; 
    for FILE in admin.kubeconfig controller-manager.kubeconfig scheduler.kubeconfig; do 
    scp /etc/kubernetes/${FILE} $NODE:/etc/kubernetes/${FILE};
    done;
    done
    

    查看证书文件(一共23个文件)

    ls /etc/kubernetes/pki/
    
    ls /etc/kubernetes/pki/ |wc -l
    

    查看证书过期时间(expiry 过期时间100年)

    cat ca-config.json
    
    {
      "signing": {
        "default": {
          "expiry": "876000h"
        },
        "profiles": {
          "kubernetes": {
            "usages": [
                "signing",
                "key encipherment",
                "server auth",
                "client auth"
            ],
            "expiry": "876000h"
          }
        }
      }
    }
    

    二进制高可用及etcd配置

    • Etcd配置
    • 高可用配置

    Etcd配置

    etcd生产环境中一定要启动奇数个节点,不然容易产生脑裂

    etcd配置大致相同,注意修改每个Master节点的etcd配置的主机名和IP地址

    注意三个节点的配置是不同的

    Master01

    vim /etc/etcd/etcd.config.yml
    
    name: 'k8s-master01'
    data-dir: /var/lib/etcd
    wal-dir: /var/lib/etcd/wal
    snapshot-count: 5000
    heartbeat-interval: 100
    election-timeout: 1000
    quota-backend-bytes: 0
    listen-peer-urls: 'https://192.168.232.128:2380'
    listen-client-urls: 'https://192.168.232.128:2379,http://127.0.0.1:2379'
    max-snapshots: 3
    max-wals: 5
    cors:
    initial-advertise-peer-urls: 'https://192.168.232.128:2380'
    advertise-client-urls: 'https://192.168.232.128:2379'
    discovery:
    discovery-fallback: 'proxy'
    discovery-proxy:
    discovery-srv:
    initial-cluster: 'k8s-master01=https://192.168.232.128:2380,k8s-master02=https://192.168.232.129:2380,k8s-master03=https://192.168.232.130:2380'
    initial-cluster-token: 'etcd-k8s-cluster'
    initial-cluster-state: 'new'
    strict-reconfig-check: false
    enable-v2: true
    enable-pprof: true
    proxy: 'off'
    proxy-failure-wait: 5000
    proxy-refresh-interval: 30000
    proxy-dial-timeout: 1000
    proxy-write-timeout: 5000
    proxy-read-timeout: 0
    client-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    peer-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      peer-client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    debug: false
    log-package-levels:
    log-outputs: [default]
    force-new-cluster: false
    

    Master02

    vim /etc/etcd/etcd.config.yml
    
    name: 'k8s-master02'
    data-dir: /var/lib/etcd
    wal-dir: /var/lib/etcd/wal
    snapshot-count: 5000
    heartbeat-interval: 100
    election-timeout: 1000
    quota-backend-bytes: 0
    listen-peer-urls: 'https://192.168.232.129:2380'
    listen-client-urls: 'https://192.168.232.129:2379,http://127.0.0.1:2379'
    max-snapshots: 3
    max-wals: 5
    cors:
    initial-advertise-peer-urls: 'https://192.168.232.129:2380'
    advertise-client-urls: 'https://192.168.232.129:2379'
    discovery:
    discovery-fallback: 'proxy'
    discovery-proxy:
    discovery-srv:
    initial-cluster: 'k8s-master01=https://192.168.232.128:2380,k8s-master02=https://192.168.232.129:2380,k8s-master03=https://192.168.232.130:2380'
    initial-cluster-token: 'etcd-k8s-cluster'
    initial-cluster-state: 'new'
    strict-reconfig-check: false
    enable-v2: true
    enable-pprof: true
    proxy: 'off'
    proxy-failure-wait: 5000
    proxy-refresh-interval: 30000
    proxy-dial-timeout: 1000
    proxy-write-timeout: 5000
    proxy-read-timeout: 0
    client-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    peer-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      peer-client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    debug: false
    log-package-levels:
    log-outputs: [default]
    force-new-cluster: false
    

    Master03

    vim /etc/etcd/etcd.config.yml
    
    name: 'k8s-master03'
    data-dir: /var/lib/etcd
    wal-dir: /var/lib/etcd/wal
    snapshot-count: 5000
    heartbeat-interval: 100
    election-timeout: 1000
    quota-backend-bytes: 0
    listen-peer-urls: 'https://192.168.232.130:2380'
    listen-client-urls: 'https://192.168.232.130:2379,http://127.0.0.1:2379'
    max-snapshots: 3
    max-wals: 5
    cors:
    initial-advertise-peer-urls: 'https://192.168.232.130:2380'
    advertise-client-urls: 'https://192.168.232.130:2379'
    discovery:
    discovery-fallback: 'proxy'
    discovery-proxy:
    discovery-srv:
    initial-cluster: 'k8s-master01=https://192.168.232.128:2380,k8s-master02=https://192.168.232.129:2380,k8s-master03=https://192.168.232.130:2380'
    initial-cluster-token: 'etcd-k8s-cluster'
    initial-cluster-state: 'new'
    strict-reconfig-check: false
    enable-v2: true
    enable-pprof: true
    proxy: 'off'
    proxy-failure-wait: 5000
    proxy-refresh-interval: 30000
    proxy-dial-timeout: 1000
    proxy-write-timeout: 5000
    proxy-read-timeout: 0
    client-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    peer-transport-security:
      cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
      key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
      peer-client-cert-auth: true
      trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
      auto-tls: true
    debug: false
    log-package-levels:
    log-outputs: [default]
    force-new-cluster: false
    

    所有Master节点创建etcd service并启动(发送键输入到所有的会话,取消node节点)

    vim /usr/lib/systemd/system/etcd.service
    
    [Unit]
    Description=Etcd Service
    Documentation=https://coreos.com/etcd/docs/latest/
    After=network.target
    
    [Service]
    Type=notify
    ExecStart=/usr/local/bin/etcd --config-file=/etc/etcd/etcd.config.yml
    Restart=on-failure
    RestartSec=10
    LimitNOFILE=65536
    
    [Install]
    WantedBy=multi-user.target
    Alias=etcd3.service
    

    所有Master节点创建etcd的证书目录

    mkdir /etc/kubernetes/pki/etcd
    ln -s /etc/etcd/ssl/* /etc/kubernetes/pki/etcd/
    systemctl daemon-reload
    systemctl enable --now etcd
    

    查看etcd状态

    export ETCDCTL_API=3
    etcdctl --endpoints="192.168.232.130:2379,192.168.232.129:2379,192.168.232.128:2379" --cacert=/etc/kubernetes/pki/etcd/etcd-ca.pem --cert=/etc/kubernetes/pki/etcd/etcd.pem --key=/etc/kubernetes/pki/etcd/etcd-key.pem  endpoint status --write-out=table
    

    状态

    +----------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
    |       ENDPOINT       |        ID        | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS |
    +----------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
    | 192.168.232.130:2379 | 8fa642cec63e074b |  3.4.13 |   20 kB |     false |      false |         2 |          8 |                  8 |        |
    | 192.168.232.129:2379 | b23932e50da8a0ea |  3.4.13 |   25 kB |     false |      false |         2 |          8 |                  8 |        |
    | 192.168.232.128:2379 | d79600c132f4ccdb |  3.4.13 |   20 kB |      true |      false |         2 |          8 |                  8 |        |
    +----------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
    

    高可用配置

    高可用配置(注意:如果不是高可用集群,haproxy和keepalived无需安装)

    如果在云上安装也无需执行此章节的步骤,可以直接使用云上的lb,比如阿里云slb,腾讯云elb等

    公有云要用公有云自带的负载均衡,比如阿里云的SLB,腾讯云的ELB,用来替代haproxy和keepalived,因为公有云大部分都是不支持keepalived的,另外如果用阿里云的话,kubectl控制端不能放在master节点,推荐使用腾讯云,因为阿里云的slb有回环的问题,也就是slb代理的服务器不能反向访问SLB,但是腾讯云修复了这个问题。

    Slb -> haproxy -> apiserver

    所有Master节点安装keepalived和haproxy

    yum install keepalived haproxy -y
    

    所有Master配置HAProxy,配置一样(删除默认配置 ggdG 回车)

    vim /etc/haproxy/haproxy.cfg 
    
    global
      maxconn  2000
      ulimit-n  16384
      log  127.0.0.1 local0 err
      stats timeout 30s
    
    defaults
      log global
      mode  http
      option  httplog
      timeout connect 5000
      timeout client  50000
      timeout server  50000
      timeout http-request 15s
      timeout http-keep-alive 15s
    
    frontend k8s-master
      bind 0.0.0.0:8443
      bind 127.0.0.1:8443
      mode tcp
      option tcplog
      tcp-request inspect-delay 5s
      default_backend k8s-master
    
    backend k8s-master
      mode tcp
      option tcplog
      option tcp-check
      balance roundrobin
      default-server inter 10s downinter 5s rise 2 fall 2 slowstart 60s maxconn 250 maxqueue 256 weight 100
      server k8s-master01    192.168.232.128:6443  check
      server k8s-master02    192.168.232.129:6443  check
      server k8s-master03    192.168.232.130:6443  check
    

    keepalived

    所有Master节点配置KeepAlived,配置不一样,注意区分

    注意每个节点的IP和网卡(interface参数),查看网卡(ens33)并修改配置文件

    ip a
    

    如果公司有其他 keepalived ,注意 virtual_router_id 51 不能重复,它是一个广播

    Master01 keepalived(删除默认配置 ggdG 回车)

    vim /etc/keepalived/keepalived.conf
    
    ! Configuration File for keepalived
    global_defs {
        router_id LVS_DEVEL
    }
    vrrp_script chk_apiserver {
        script "/etc/keepalived/check_apiserver.sh"
        interval 5 
        weight -5
        fall 2
        rise 1
    }
    vrrp_instance VI_1 {
        state MASTER
        interface ens33
        mcast_src_ip 192.168.232.128
        virtual_router_id 51
        priority 101
        nopreempt
        advert_int 2
        authentication {
            auth_type PASS
            auth_pass K8SHA_KA_AUTH
        }
        virtual_ipaddress {
            192.168.232.236
        }
        track_script {
          chk_apiserver 
    } }
    

    Master02 keepalived(删除默认配置 ggdG 回车)

    vim /etc/keepalived/keepalived.conf
    
    ! Configuration File for keepalived
    global_defs {
        router_id LVS_DEVEL
    }
    vrrp_script chk_apiserver {
        script "/etc/keepalived/check_apiserver.sh"
        interval 5 
        weight -5
        fall 2
        rise 1
     
    }
    vrrp_instance VI_1 {
        state BACKUP
        interface ens33
        mcast_src_ip 192.168.232.129
        virtual_router_id 51
        priority 100
        nopreempt
        advert_int 2
        authentication {
            auth_type PASS
            auth_pass K8SHA_KA_AUTH
        }
        virtual_ipaddress {
            192.168.232.236
        }
        track_script {
          chk_apiserver 
    } }
    

    Master03 keepalived(删除默认配置 ggdG 回车)

    vim /etc/keepalived/keepalived.conf
    
    ! Configuration File for keepalived
    global_defs {
        router_id LVS_DEVEL
    }
    vrrp_script chk_apiserver {
        script "/etc/keepalived/check_apiserver.sh"
        interval 5
        weight -5
        fall 2  
        rise 1
    }
    vrrp_instance VI_1 {
        state BACKUP
        interface ens33
        mcast_src_ip 192.168.232.130
        virtual_router_id 51
        priority 100
        nopreempt
        advert_int 2
        authentication {
            auth_type PASS
            auth_pass K8SHA_KA_AUTH
        }
        virtual_ipaddress {
            192.168.232.236
        }
        track_script {
          chk_apiserver 
    } }
    

    所有master节点健康检查配置(发送键输入到所有的会话,取消node节点)

    vim /etc/keepalived/check_apiserver.sh
    
    #!/bin/bash
    
    err=0
    for k in $(seq 1 3)
    do
        check_code=$(pgrep haproxy)
        if [[ $check_code == "" ]]; then
            err=$(expr $err + 1)
            sleep 1
            continue
        else
            err=0
            break
        fi
    done
    
    if [[ $err != "0" ]]; then
        echo "systemctl stop keepalived"
        /usr/bin/systemctl stop keepalived
        exit 1
    else
        exit 0
    fi
    
    chmod +x /etc/keepalived/check_apiserver.sh
    

    所有master节点启动haproxy和keepalived

    systemctl daemon-reload
    systemctl enable --now haproxy
    systemctl enable --now keepalived
    

    它会有一个选主的过程,然后绑定,这就是 VIP 的作用,它会在三个主节点之间选择一个进行绑定,当这个节点出现问题的时候,VIP 会绑定到其他节点

    查看 192.168.232.236 绑定情况

    ip a
    

    VIP测试

    ping 192.168.232.236
    

    重要:如果安装了keepalived和haproxy,需要测试keepalived是否是正常的

    telnet 192.168.232.236 8443
    

    如果ping不通且telnet没有出现 ],则认为VIP不可以,不可在继续往下执行,需要排查keepalived的问题,比如防火墙和selinux,haproxy和keepalived的状态,监听端口等

    所有节点查看防火墙状态必须为disable和inactive

    systemctl status firewalld
    

    所有节点查看selinux状态,必须为disable:getenforce

    master节点查看haproxy和keepalived状态:

    systemctl status keepalived haproxy
    

    master节点查看监听端口:

    netstat -lntp 
    

    二进制K8s组件配置

    • Apiserver
    • ControllerManager
    • Scheduler

    所有节点创建相关目录(发送键输入到所有的会话)

    mkdir -p /etc/kubernetes/manifests/ /etc/systemd/system/kubelet.service.d /var/lib/kubelet /var/log/kubernetes
    

    Apiserver

    所有Master节点创建kube-apiserver service,# 注意,如果不是高可用集群,192.168.232.236改为master01的地址

    Master01配置(取消发送键输入到所有的会话)

    注意k8s service网段为10.96.0.0/12,该网段不能和宿主机的网段、Pod网段的重复,请按需修改

    vim /usr/lib/systemd/system/kube-apiserver.service
    
    [Unit]
    Description=Kubernetes API Server
    Documentation=https://github.com/kubernetes/kubernetes
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/kube-apiserver 
          --v=2  
          --logtostderr=true  
          --allow-privileged=true  
          --bind-address=0.0.0.0  
          --secure-port=6443  
          --insecure-port=0  
          --advertise-address=192.168.232.128 
          --service-cluster-ip-range=10.96.0.0/12  
          --service-node-port-range=30000-32767  
          --etcd-servers=https://192.168.232.128:2379,https://192.168.232.129:2379,https://192.168.232.130:2379 
          --etcd-cafile=/etc/etcd/ssl/etcd-ca.pem  
          --etcd-certfile=/etc/etcd/ssl/etcd.pem  
          --etcd-keyfile=/etc/etcd/ssl/etcd-key.pem  
          --client-ca-file=/etc/kubernetes/pki/ca.pem  
          --tls-cert-file=/etc/kubernetes/pki/apiserver.pem  
          --tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem  
          --kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem  
          --kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem  
          --service-account-key-file=/etc/kubernetes/pki/sa.pub  
          --service-account-signing-key-file=/etc/kubernetes/pki/sa.key  
          --service-account-issuer=https://kubernetes.default.svc.cluster.local 
          --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname  
          --enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota  
          --authorization-mode=Node,RBAC  
          --enable-bootstrap-token-auth=true  
          --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem  
          --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem  
          --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem  
          --requestheader-allowed-names=aggregator  
          --requestheader-group-headers=X-Remote-Group  
          --requestheader-extra-headers-prefix=X-Remote-Extra-  
          --requestheader-username-headers=X-Remote-User
          # --token-auth-file=/etc/kubernetes/token.csv
    
    Restart=on-failure
    RestartSec=10s
    LimitNOFILE=65535
    
    [Install]
    WantedBy=multi-user.target
    

    Master02配置

    注意k8s service网段为10.96.0.0/12,该网段不能和宿主机的网段、Pod网段的重复,请按需修改

    vim /usr/lib/systemd/system/kube-apiserver.service
    
    [Unit]
    Description=Kubernetes API Server
    Documentation=https://github.com/kubernetes/kubernetes
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/kube-apiserver 
          --v=2  
          --logtostderr=true  
          --allow-privileged=true  
          --bind-address=0.0.0.0  
          --secure-port=6443  
          --insecure-port=0  
          --advertise-address=192.168.232.129 
          --service-cluster-ip-range=10.96.0.0/12  
          --service-node-port-range=30000-32767  
          --etcd-servers=https://192.168.232.128:2379,https://192.168.232.129:2379,https://192.168.232.130:2379 
          --etcd-cafile=/etc/etcd/ssl/etcd-ca.pem  
          --etcd-certfile=/etc/etcd/ssl/etcd.pem  
          --etcd-keyfile=/etc/etcd/ssl/etcd-key.pem  
          --client-ca-file=/etc/kubernetes/pki/ca.pem  
          --tls-cert-file=/etc/kubernetes/pki/apiserver.pem  
          --tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem  
          --kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem  
          --kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem  
          --service-account-key-file=/etc/kubernetes/pki/sa.pub  
          --service-account-signing-key-file=/etc/kubernetes/pki/sa.key  
          --service-account-issuer=https://kubernetes.default.svc.cluster.local 
          --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname  
          --enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota  
          --authorization-mode=Node,RBAC  
          --enable-bootstrap-token-auth=true  
          --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem  
          --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem  
          --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem  
          --requestheader-allowed-names=aggregator  
          --requestheader-group-headers=X-Remote-Group  
          --requestheader-extra-headers-prefix=X-Remote-Extra-  
          --requestheader-username-headers=X-Remote-User
          # --token-auth-file=/etc/kubernetes/token.csv
    
    Restart=on-failure
    RestartSec=10s
    LimitNOFILE=65535
    
    [Install]
    WantedBy=multi-user.target
    

    Master03配置

    注意k8s service网段为10.96.0.0/12,该网段不能和宿主机的网段、Pod网段的重复,请按需修改

    vim /usr/lib/systemd/system/kube-apiserver.service
    
    [Unit]
    Description=Kubernetes API Server
    Documentation=https://github.com/kubernetes/kubernetes
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/kube-apiserver 
          --v=2  
          --logtostderr=true  
          --allow-privileged=true  
          --bind-address=0.0.0.0  
          --secure-port=6443  
          --insecure-port=0  
          --advertise-address=192.168.232.130 
          --service-cluster-ip-range=10.96.0.0/12  
          --service-node-port-range=30000-32767  
          --etcd-servers=https://192.168.232.128:2379,https://192.168.232.129:2379,https://192.168.232.130:2379 
          --etcd-cafile=/etc/etcd/ssl/etcd-ca.pem  
          --etcd-certfile=/etc/etcd/ssl/etcd.pem  
          --etcd-keyfile=/etc/etcd/ssl/etcd-key.pem  
          --client-ca-file=/etc/kubernetes/pki/ca.pem  
          --tls-cert-file=/etc/kubernetes/pki/apiserver.pem  
          --tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem  
          --kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem  
          --kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem  
          --service-account-key-file=/etc/kubernetes/pki/sa.pub  
          --service-account-signing-key-file=/etc/kubernetes/pki/sa.key  
          --service-account-issuer=https://kubernetes.default.svc.cluster.local 
          --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname  
          --enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota  
          --authorization-mode=Node,RBAC  
          --enable-bootstrap-token-auth=true  
          --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem  
          --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem  
          --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem  
          --requestheader-allowed-names=aggregator  
          --requestheader-group-headers=X-Remote-Group  
          --requestheader-extra-headers-prefix=X-Remote-Extra-  
          --requestheader-username-headers=X-Remote-User
          # --token-auth-file=/etc/kubernetes/token.csv
    
    Restart=on-failure
    RestartSec=10s
    LimitNOFILE=65535
    
    [Install]
    WantedBy=multi-user.target
    

    所有Master节点开启kube-apiserver(发送键输入到所有的会话,取消node节点)

    systemctl daemon-reload && systemctl enable --now kube-apiserver
    

    检测kube-server状态

    systemctl status kube-apiserver
    

    ControllerManager

    所有Master节点配置kube-controller-manager service

    注意k8s Pod网段为172.16.0.0/12,该网段不能和宿主机的网段、k8s Service网段的重复,请按需修改

    vim /usr/lib/systemd/system/kube-controller-manager.service
    
    [Unit]
    Description=Kubernetes Controller Manager
    Documentation=https://github.com/kubernetes/kubernetes
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/kube-controller-manager 
          --v=2 
          --logtostderr=true 
          --address=127.0.0.1 
          --root-ca-file=/etc/kubernetes/pki/ca.pem 
          --cluster-signing-cert-file=/etc/kubernetes/pki/ca.pem 
          --cluster-signing-key-file=/etc/kubernetes/pki/ca-key.pem 
          --service-account-private-key-file=/etc/kubernetes/pki/sa.key 
          --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig 
          --leader-elect=true 
          --use-service-account-credentials=true 
          --node-monitor-grace-period=40s 
          --node-monitor-period=5s 
          --pod-eviction-timeout=2m0s 
          --controllers=*,bootstrapsigner,tokencleaner 
          --allocate-node-cidrs=true 
          --cluster-cidr=172.16.0.0/12 
          --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem 
          --node-cidr-mask-size=24
          
    Restart=always
    RestartSec=10s
    
    [Install]
    WantedBy=multi-user.target
    

    所有Master节点启动kube-controller-manager

    systemctl daemon-reload
    
    systemctl enable --now kube-controller-manager
    

    查看启动状态

    systemctl  status kube-controller-manager
    

    Scheduler

    所有Master节点配置kube-scheduler service

    vim /usr/lib/systemd/system/kube-scheduler.service 
    
    [Unit]
    Description=Kubernetes Scheduler
    Documentation=https://github.com/kubernetes/kubernetes
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/kube-scheduler 
          --v=2 
          --logtostderr=true 
          --address=127.0.0.1 
          --leader-elect=true 
          --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
    
    Restart=always
    RestartSec=10s
    
    [Install]
    WantedBy=multi-user.target
    

    启动

    systemctl daemon-reload
    
    systemctl enable --now kube-scheduler
    

    查看启动状态

    systemctl  status kube-scheduler
    

    二进制使用Bootstrapping自动颁发证书

    它可以给 node 节点自动颁发证书,也就是给 keepalived 颁发证书

    为什么这个证书不是手动管理?因为 k8s 主节点可能是固定的,创建好之后一直就是那几台,但是 node 节点可能变化比较多,如果添加,删除,故障维护节点的时候手动添加会比较麻烦,keepalived 证书和主机名是有绑定的,而我们的主机名又是不一样的,所以需要有一种机制自动颁发 keepalived 发来的证书请求

    在Master01创建bootstrap(取消发送键输入到所有的会话)

    注意,如果不是高可用集群,192.168.232.236:8443改为master01的地址,8443改为apiserver的端口,默认是6443

    cd /root/k8s-ha-install/bootstrap
    kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.232.236:8443     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
    kubectl config set-credentials tls-bootstrap-token-user     --token=c8ad9c.2e4d610cf3e7426e --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
    kubectl config set-context tls-bootstrap-token-user@kubernetes     --cluster=kubernetes     --user=tls-bootstrap-token-user     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
    kubectl config use-context tls-bootstrap-token-user@kubernetes     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
    

    bootstrap-kubelet.kubeconfig 是一个 keepalived 用来向 apiserver 申请证书的文件

    注意:如果要修改bootstrap.secret.yaml的token-id和token-secret,需要保证 c8ad9c 字符串一致的,并且位数是一样的。还要保证上个命令的黄色字体:c8ad9c.2e4d610cf3e7426e与你修改的字符串要一致

    cat bootstrap.secret.yaml
    
    apiVersion: v1
    kind: Secret
    metadata:
      name: bootstrap-token-c8ad9c
      namespace: kube-system
    type: bootstrap.kubernetes.io/token
    stringData:
      description: "The default bootstrap token generated by 'kubelet '."
      token-id: c8ad9c
      token-secret: 2e4d610cf3e7426e
      usage-bootstrap-authentication: "true"
      usage-bootstrap-signing: "true"
      auth-extra-groups:  system:bootstrappers:default-node-token,system:bootstrappers:worker,system:bootstrappers:ingress
    

    创建配置文件,缺乏此文件无法执行 kubectl get node(The connection to the server localhost:8080 was refused),需要将证书复制过来

    mkdir -p /root/.kube ; cp /etc/kubernetes/admin.kubeconfig /root/.kube/config
    

    kubectl 命令只需要一个节点拥有就可以,这是控制节点,不可以让每个节点都拥有,这样非常危险,可以把他放到集群之外的任何一个节点都可以,并不一定是我们的 k8s 节点,任何一台服务器与 k8s 相通即可,需要把这个文件复制过去,就可以访问到我们这个集群

    创建 bootstrap

    kubectl create -f bootstrap.secret.yaml
    

    二进制Node节点及Calico配置

    二进制Node节点

    • 复制证书
    • Kubelet配置
    • kube-proxy配置

    复制证书

    node节点使用自动颁发证书的形式配置

    Master01节点复制证书至Node节点

    cd /etc/kubernetes/
    
    for NODE in k8s-master02 k8s-master03 k8s-node01 k8s-node02; do
         ssh $NODE mkdir -p /etc/kubernetes/pki /etc/etcd/ssl /etc/etcd/ssl
         for FILE in etcd-ca.pem etcd.pem etcd-key.pem; do
           scp /etc/etcd/ssl/$FILE $NODE:/etc/etcd/ssl/
         done
         for FILE in pki/ca.pem pki/ca-key.pem pki/front-proxy-ca.pem bootstrap-kubelet.kubeconfig; do
           scp /etc/kubernetes/$FILE $NODE:/etc/kubernetes/${FILE}
     done
     done
    

    Kubelet配置

    所有节点创建相关目录(发送键输入到所有的会话)

    mkdir -p /var/lib/kubelet /var/log/kubernetes /etc/systemd/system/kubelet.service.d /etc/kubernetes/manifests/
    

    所有节点配置kubelet service

    vim  /usr/lib/systemd/system/kubelet.service
    # 添加以下内容
    [Unit]
    Description=Kubernetes Kubelet
    Documentation=https://github.com/kubernetes/kubernetes
    After=docker.service
    Requires=docker.service
    
    [Service]
    ExecStart=/usr/local/bin/kubelet
    
    Restart=always
    StartLimitInterval=0
    RestartSec=10
    
    [Install]
    WantedBy=multi-user.target
    

    所有节点配置kubelet service的配置文件

    vim /etc/systemd/system/kubelet.service.d/10-kubelet.conf
    # 添加以下内容
    [Service]
    Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig --kubeconfig=/etc/kubernetes/kubelet.kubeconfig"
    Environment="KUBELET_SYSTEM_ARGS=--network-plugin=cni --cni-conf-dir=/etc/cni/net.d --cni-bin-dir=/opt/cni/bin"
    Environment="KUBELET_CONFIG_ARGS=--config=/etc/kubernetes/kubelet-conf.yml --pod-infra-container-image=registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2"
    Environment="KUBELET_EXTRA_ARGS=--node-labels=node.kubernetes.io/node='' "
    ExecStart=
    ExecStart=/usr/local/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_SYSTEM_ARGS $KUBELET_EXTRA_ARGS
    

    创建kubelet的配置文件

    注意:如果更改了k8s的service网段,需要更改kubelet-conf.yml 的clusterDNS:配置,改成k8s Service网段的第十个地址,比如10.96.0.10

    vim /etc/kubernetes/kubelet-conf.yml
    # 添加以下内容
    apiVersion: kubelet.config.k8s.io/v1beta1
    kind: KubeletConfiguration
    address: 0.0.0.0
    port: 10250
    readOnlyPort: 10255
    authentication:
      anonymous:
        enabled: false
      webhook:
        cacheTTL: 2m0s
        enabled: true
      x509:
        clientCAFile: /etc/kubernetes/pki/ca.pem
    authorization:
      mode: Webhook
      webhook:
        cacheAuthorizedTTL: 5m0s
        cacheUnauthorizedTTL: 30s
    cgroupDriver: systemd
    cgroupsPerQOS: true
    clusterDNS:
    - 10.96.0.10
    clusterDomain: cluster.local
    containerLogMaxFiles: 5
    containerLogMaxSize: 10Mi
    contentType: application/vnd.kubernetes.protobuf
    cpuCFSQuota: true
    cpuManagerPolicy: none
    cpuManagerReconcilePeriod: 10s
    enableControllerAttachDetach: true
    enableDebuggingHandlers: true
    enforceNodeAllocatable:
    - pods
    eventBurst: 10
    eventRecordQPS: 5
    evictionHard:
      imagefs.available: 15%
      memory.available: 100Mi
      nodefs.available: 10%
      nodefs.inodesFree: 5%
    evictionPressureTransitionPeriod: 5m0s
    failSwapOn: true
    fileCheckFrequency: 20s
    hairpinMode: promiscuous-bridge
    healthzBindAddress: 127.0.0.1
    healthzPort: 10248
    httpCheckFrequency: 20s
    imageGCHighThresholdPercent: 85
    imageGCLowThresholdPercent: 80
    imageMinimumGCAge: 2m0s
    iptablesDropBit: 15
    iptablesMasqueradeBit: 14
    kubeAPIBurst: 10
    kubeAPIQPS: 5
    makeIPTablesUtilChains: true
    maxOpenFiles: 1000000
    maxPods: 110
    nodeStatusUpdateFrequency: 10s
    oomScoreAdj: -999
    podPidsLimit: -1
    registryBurst: 10
    registryPullQPS: 5
    resolvConf: /etc/resolv.conf
    rotateCertificates: true
    runtimeRequestTimeout: 2m0s
    serializeImagePulls: true
    staticPodPath: /etc/kubernetes/manifests
    streamingConnectionIdleTimeout: 4h0m0s
    syncFrequency: 1m0s
    volumeStatsAggPeriod: 1m0s
    

    启动所有节点kubelet

    systemctl daemon-reload
    systemctl enable --now kubelet
    

    查看系统日志

    tail -f /var/log/messages
    

    显示只有如下信息为正常,因为Calico还没安装

    Unable to update cni config" err="no networks found in /etc/cni/net.d
    

    查看集群状态

    kubectl get node
    

    集群状态NotReady,因为Calico还没安装

    NAME           STATUS     ROLES    AGE   VERSION
    k8s-master01   NotReady   <none>   6s    v1.20.9
    k8s-master02   NotReady   <none>   6s    v1.20.9
    k8s-master03   NotReady   <none>   6s    v1.20.9
    k8s-node01     NotReady   <none>   6s    v1.20.9
    k8s-node02     NotReady   <none>   6s    v1.20.9
    

    kube-proxy配置

    注意,如果不是高可用集群,192.168.232.236:8443改为master01的地址,8443改为apiserver的端口,默认是6443

    在Master01执行(取消发送键输入到所有的会话)

    cd /root/k8s-ha-install
    kubectl -n kube-system create serviceaccount kube-proxy
    kubectl create clusterrolebinding system:kube-proxy         --clusterrole system:node-proxier         --serviceaccount kube-system:kube-proxy
    SECRET=$(kubectl -n kube-system get sa/kube-proxy 
        --output=jsonpath='{.secrets[0].name}')
    JWT_TOKEN=$(kubectl -n kube-system get secret/$SECRET 
    --output=jsonpath='{.data.token}' | base64 -d)
    PKI_DIR=/etc/kubernetes/pki
    K8S_DIR=/etc/kubernetes
    kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.232.236:8443     --kubeconfig=${K8S_DIR}/kube-proxy.kubeconfig
    kubectl config set-credentials kubernetes     --token=${JWT_TOKEN}     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    kubectl config set-context kubernetes     --cluster=kubernetes     --user=kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    kubectl config use-context kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    

    如果更改了集群Pod的网段,需要更改kube-proxy/kube-proxy.conf的clusterCIDR: 172.16.0.0/12参数为pod的网段。

    [root@k8s-master01 k8s-ha-install]# vim kube-proxy/kube-proxy.conf 
    # 修改以下内容
    clusterCIDR: 172.16.0.0/12
    

    在master01将kube-proxy的systemd Service文件发送到其他节点

    for NODE in k8s-master01 k8s-master02 k8s-master03; do
         scp ${K8S_DIR}/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig
         scp kube-proxy/kube-proxy.conf $NODE:/etc/kubernetes/kube-proxy.conf
         scp kube-proxy/kube-proxy.service $NODE:/usr/lib/systemd/system/kube-proxy.service
     done
    
    for NODE in k8s-node01 k8s-node02; do
         scp /etc/kubernetes/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig
         scp kube-proxy/kube-proxy.conf $NODE:/etc/kubernetes/kube-proxy.conf
         scp kube-proxy/kube-proxy.service $NODE:/usr/lib/systemd/system/kube-proxy.service
     done
    

    所有节点启动kube-proxy(发送键输入到所有的会话)

    systemctl daemon-reload
    
    systemctl enable --now kube-proxy
    

    查看状态

    systemctl status kube-proxy
    

    如果出现如下报错需要调整一下配置文件

    [root@k8s-master01 k8s-ha-install]# systemctl status kube-proxy
    ● kube-proxy.service - Kubernetes Kube Proxy
       Loaded: error (Reason: Invalid argument)
       Active: inactive (dead)
         Docs: https://github.com/kubernetes/kubernetes
    
    Aug 05 15:00:02 localhost.localdomain systemd[1]: kube-proxy.service lacks both ExecStart= and ExecStop= setting. Refusing.
    Aug 05 15:00:02 localhost.localdomain systemd[1]: Cannot add dependency job for unit kube-proxy.service, ignoring: Unit is not loaded properly: Invalid argument.
    Aug 05 15:23:18 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:7] Trailing garbage, ignoring.
    Aug 05 15:23:18 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:8] Unknown lvalue '--config' in section 'Service'
    Aug 05 15:23:18 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:9] Unknown lvalue '--v' in section 'Service'
    Aug 05 15:23:18 k8s-master01 systemd[1]: kube-proxy.service lacks both ExecStart= and ExecStop= setting. Refusing.
    Aug 05 15:23:26 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:7] Trailing garbage, ignoring.
    Aug 05 15:23:26 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:8] Unknown lvalue '--config' in section 'Service'
    Aug 05 15:23:26 k8s-master01 systemd[1]: [/usr/lib/systemd/system/kube-proxy.service:9] Unknown lvalue '--v' in section 'Service'
    Aug 05 15:23:26 k8s-master01 systemd[1]: kube-proxy.service lacks both ExecStart= and ExecStop= setting. Refusing.
    

    删除kube-proxy

    [root@k8s-master01 k8s-ha-install]# kubectl -n kube-system delete serviceaccount kube-proxy
    serviceaccount "kube-proxy" deleted
    

    修改配置

    [root@k8s-master01 k8s-ha-install]# vim kube-proxy/kube-proxy.service
    # 取消换行
    ExecStart=/usr/local/bin/kube-proxy --config=/etc/kubernetes/kube-proxy.conf --v=2
    

    再次执行创建

    cd /root/k8s-ha-install
    kubectl -n kube-system create serviceaccount kube-proxy
    kubectl create clusterrolebinding system:kube-proxy         --clusterrole system:node-proxier         --serviceaccount kube-system:kube-proxy
    SECRET=$(kubectl -n kube-system get sa/kube-proxy 
        --output=jsonpath='{.secrets[0].name}')
    JWT_TOKEN=$(kubectl -n kube-system get secret/$SECRET 
    --output=jsonpath='{.data.token}' | base64 -d)
    PKI_DIR=/etc/kubernetes/pki
    K8S_DIR=/etc/kubernetes
    kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.232.236:8443     --kubeconfig=${K8S_DIR}/kube-proxy.kubeconfig
    kubectl config set-credentials kubernetes     --token=${JWT_TOKEN}     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    kubectl config set-context kubernetes     --cluster=kubernetes     --user=kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    kubectl config use-context kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
    

    修改配置

    [root@k8s-master01 k8s-ha-install]# vim /usr/lib/systemd/system/kube-proxy.service
    # 取消换行
    ExecStart=/usr/local/bin/kube-proxy --config=/etc/kubernetes/kube-proxy.conf --v=2
    

    如果更改了集群Pod的网段,需要更改kube-proxy/kube-proxy.conf的clusterCIDR: 172.16.0.0/12参数为pod的网段。

    [root@k8s-master01 k8s-ha-install]# vim kube-proxy/kube-proxy.conf 
    # 修改以下内容
    clusterCIDR: 172.16.0.0/12
    

    在master01将kube-proxy的systemd Service文件发送到其他节点

    for NODE in k8s-master01 k8s-master02 k8s-master03; do
         scp ${K8S_DIR}/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig
         scp kube-proxy/kube-proxy.conf $NODE:/etc/kubernetes/kube-proxy.conf
         scp kube-proxy/kube-proxy.service $NODE:/usr/lib/systemd/system/kube-proxy.service
     done
    
    for NODE in k8s-node01 k8s-node02; do
         scp /etc/kubernetes/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig
         scp kube-proxy/kube-proxy.conf $NODE:/etc/kubernetes/kube-proxy.conf
         scp kube-proxy/kube-proxy.service $NODE:/usr/lib/systemd/system/kube-proxy.service
     done
    

    所有节点启动kube-proxy(发送键输入到所有的会话)

    systemctl daemon-reload
    
    systemctl enable --now kube-proxy
    

    查看日志

    tail -f /var/log/messages
    

    查看状态

    systemctl status kube-proxy
    

    启动成功

    [root@k8s-master01 k8s-ha-install]# systemctl status kube-proxy
    ● kube-proxy.service - Kubernetes Kube Proxy
       Loaded: loaded (/usr/lib/systemd/system/kube-proxy.service; enabled; vendor preset: disabled)
       Active: active (running) since Thu 2021-08-05 15:42:25 CST; 7s ago
         Docs: https://github.com/kubernetes/kubernetes
     Main PID: 11767 (kube-proxy)
        Tasks: 6
       Memory: 54.2M
       CGroup: /system.slice/kube-proxy.service
               └─11767 /usr/local/bin/kube-proxy --config=/etc/kubernetes/kube-proxy.conf --v=2
    
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.735111   11767 shared_informer.go:240] Waiting for caches to sync for service config
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.735146   11767 config.go:224] Starting endpoint slice config controller
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.735151   11767 shared_informer.go:240] Waiting for caches to sync for endpoint slice config
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.735367   11767 reflector.go:219] Starting reflector *v1.Service (15m0s) from k8s.io/client-go/informers/factory.go:134
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.735813   11767 reflector.go:219] Starting reflector *v1beta1.EndpointSlice (15m0s) from k8s.io/client-go/informers/factory.go:134
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.738920   11767 service.go:275] Service default/kubernetes updated: 1 ports
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.837140   11767 shared_informer.go:247] Caches are synced for endpoint slice config
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.837210   11767 proxier.go:1036] Not syncing ipvs rules until Services and Endpoints have been received from master
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.837227   11767 shared_informer.go:247] Caches are synced for service config
    Aug 05 15:42:27 k8s-master01 kube-proxy[11767]: I0805 15:42:27.837470   11767 service.go:390] Adding new service port "default/kubernetes:https" at 10.96.0.1:443/TCP
    

    Calico配置

    在master01执行(取消发送键输入到所有的会话)

    cd /root/k8s-ha-install/calico/
    
    # 修改calico-etcd.yaml的以下位置
    sed -i 's#etcd_endpoints: "http://<ETCD_IP>:<ETCD_PORT>"#etcd_endpoints: "https://192.168.232.128:2379,https://192.168.232.129:2379,https://192.168.232.130:2379"#g' calico-etcd.yaml
    
    ETCD_CA=`cat /etc/kubernetes/pki/etcd/etcd-ca.pem | base64 | tr -d '
    '`
    ETCD_CERT=`cat /etc/kubernetes/pki/etcd/etcd.pem | base64 | tr -d '
    '`
    ETCD_KEY=`cat /etc/kubernetes/pki/etcd/etcd-key.pem | base64 | tr -d '
    '`
    
    sed -i "s@# etcd-key: null@etcd-key: ${ETCD_KEY}@g; s@# etcd-cert: null@etcd-cert: ${ETCD_CERT}@g; s@# etcd-ca: null@etcd-ca: ${ETCD_CA}@g" calico-etcd.yaml
    
    sed -i 's#etcd_ca: ""#etcd_ca: "/calico-secrets/etcd-ca"#g; s#etcd_cert: ""#etcd_cert: "/calico-secrets/etcd-cert"#g; s#etcd_key: "" #etcd_key: "/calico-secrets/etcd-key" #g' calico-etcd.yaml
    
    # 更改此处为自己的pod网段
    POD_SUBNET="172.16.0.0/12"
    
    # 注意下面的这个步骤是把calico-etcd.yaml文件里面的CALICO_IPV4POOL_CIDR下的网段改成自己的Pod网段,也就是把192.168.x.x/16改成自己的集群网段,并打开注释:
    sed -i 's@# - name: CALICO_IPV4POOL_CIDR@- name: CALICO_IPV4POOL_CIDR@g; s@#   value: "192.168.0.0/16"@  value: '"${POD_SUBNET}"'@g' calico-etcd.yaml
    
    kubectl apply -f calico-etcd.yaml
    

    查看容器状态

    kubectl  get po -n kube-system
    

    容器状态

    NAME                                      READY   STATUS    RESTARTS      AGE
    calico-kube-controllers-cdd5755b9-4fzg9   1/1     Running   0             113s
    calico-node-8xg62                         1/1     Running   0             113s
    calico-node-dczxz                         1/1     Running   0             113s
    calico-node-gn8ws                         1/1     Running   0             113s
    calico-node-qmwkd                         1/1     Running   0             113s
    calico-node-zfw8n                         1/1     Running   2 (78s ago)   113s
    

    如果容器状态异常可以使用kubectl describe 或者logs查看容器的日志

    课程链接(私信领取福利)

    http://www.kubeasy.com/

    知识共享许可协议

    本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

    欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

  • 相关阅读:
    PHP header函数使用教程
    mysql show processlist 命令检查mysql lock
    MySQL
    background-position 用法详细介绍
    Windows下Mysql主从配置(Mysql5.5)
    Tcl介绍和基础语法
    研发项目管理
    VCS 查看代码覆盖率
    Openrisc的or1200
    MY $MYVIMRC
  • 原文地址:https://www.cnblogs.com/MingsonZheng/p/15028406.html
Copyright © 2011-2022 走看看