1.20 二进制部署

环境

192.168.202.191 sxy-k8sB-master01 # 2C2G 40G
192.168.202.192 sxy-k8sB-master02 # 2C2G 40G
192.168.202.193sxy-k8sB-master03 # 2C2G 40G

 # VIP 虚IP不占用机器资源
192.168.202.199 k8s-master-lb # 

#如果不是高可用集群,该IP为Master01的IP
192.168.202.194 sxy-k8sB-node01 # 2C2G 40G
192.168.202.195 sxy-k8sB-node02  # 2C2G 40G

K8s Service网段:17.96.0.0/12
K8s Pod网段:174.16.0.0/12

宿主机网段、K8s Service网段、Pod网段不能重复

配置所有节点hosts文件
[root@sxy-k8sB-master01 ~]# vim /etc/hosts

192.168.202.191 sxy-k8sB-master01
192.168.202.192 sxy-k8sB-master02
192.168.202.193 sxy-k8sB-master03
192.168.202.199 k8s-master-lb 
192.168.202.194 sxy-k8sB-node01
192.168.202.195 sxy-k8sB-node02
更换yum源
[root@sxy-k8sB-master01 ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo

[root@sxy-k8sB-master01 ~]# yum install -y yum-utils device-mapper-persistent-data lvm2

[root@sxy-k8sB-master01 ~]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

[root@sxy-k8sB-master01 ~]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo


必备工具安装
[root@sxy-k8sB-master01 ~]# yum install wget jq psmisc vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 git -y

所有节点关闭firewalld 、dnsmasq、selinux(CentOS7需要关闭NetworkManager,CentOS8不需要)
[root@sxy-k8sB-master01 ~]# systemctl disable --now firewalld 
[root@sxy-k8sB-master01 ~]# systemctl disable --now dnsmasq
Failed to execute operation: No such file or directory
[root@sxy-k8sB-master01 ~]# systemctl disable --now NetworkManager

Removed symlink /etc/systemd/system/multi-user.target.wants/NetworkManager.service.
Removed symlink /etc/systemd/system/dbus-org.freedesktop.NetworkManager.service.
Removed symlink /etc/systemd/system/network-online.target.wants/NetworkManager-wait-online.service.
Removed symlink /etc/systemd/system/dbus-org.freedesktop.nm-dispatcher.service.

[root@sxy-k8sB-master01 ~]# setenforce 0
setenforce: SELinux is disabled
[root@sxy-k8sB-master01 ~]# sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/sysconfig/selinux
[root@sxy-k8sB-master01 ~]# sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config


关闭swap分区,fstab注释swap
[root@sxy-k8sB-master01 ~]# swapoff -a && sysctl -w vm.swappiness=0
vm.swappiness = 0
[root@sxy-k8sB-master01 ~]# sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab

所有节点同步时间
#安装ntpdate
[root@sxy-k8sB-master01 ~]# rpm -ivh http://mirrors.wlnmp.com/centos/wlnmp-release-centos.noarch.rpm
Retrieving http://mirrors.wlnmp.com/centos/wlnmp-release-centos.noarch.rpm
Preparing...                          ################################# [100%]
Updating / installing...
   1:wlnmp-release-centos-2-1         ################################# [100%]
[root@sxy-k8sB-master01 ~]# yum install ntpdate -y

[root@sxy-k8sB-master01 ~]# ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
[root@sxy-k8sB-master01 ~]# echo 'Asia/Shanghai' >/etc/timezone
[root@sxy-k8sB-master01 ~]# ntpdate time2.aliyun.com

# 加入到crontab
*/5 * * * * /usr/sbin/ntpdate time2.aliyun.com

所有节点配置limit
[root@sxy-k8sB-master01 ~]# ulimit -SHn 65535
[root@sxy-k8sB-master01 ~]# vim /etc/security/limits.conf
# 末尾添加如下内容
* soft nofile 65536
* hard nofile 131072
* soft nproc 65535
* hard nproc 655350
* soft memlock unlimited
* hard memlock unlimited 

免密登录

# Master01节点免密钥登录其他节点,安装过程中生成配置文件和证书均在Master01上操作,集群管理也在Master01上操作,阿里云或者AWS上需要单独一台kubectl服务器。密钥配置如下:

[root@sxy-k8sB-master01 ~]# ssh-keygen -t rsa

[root@sxy-k8sB-master01 ~]# for i in sxy-k8sB-master01 sxy-k8sB-master02sxy-k8sB-master03 sxy-k8sB-node01 sxy-k8sB-node02;do ssh-copy-id -i .ssh/id_rsa.pub $i;done

Master01下载安装文件
[root@sxy-k8sB-master01 ~]# cd /root/ ; git clone https://github.com/dotbalo/k8s-ha-install.git

[root@sxy-k8sB-master01 ~]# cd /root/ ; git clone https://gitee.com/dukuan/k8s-ha-install.git

#有的系统不支持 去掉--exclude=kernel*
yum update -y --exclude=kernel* && reboot

内核升级

[root@sxy-k8sB-master01 ~]# cd /root/ 

[root@sxy-k8sB-master01 ~]# wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-devel-4.19.12-1.el7.elrepo.x86_64.rpm

[root@sxy-k8sB-master01 ~]# wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-4.19.12-1.el7.elrepo.x86_64.rpm

从master01节点传到其他节点:
[root@sxy-k8sB-master01 ~]# for i in sxy-k8sB-master02 sxy-k8sB-master03 sxy-k8sB-node01 sxy-k8sB-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

所有节点安装内核
[root@sxy-k8sB-master01 ~]# cd /root && yum localinstall -y kernel-ml*

所有节点更改内核启动顺序
[root@sxy-k8sB-master01 ~]# grub2-set-default  0 && grub2-mkconfig -o /etc/grub2.cfg

[root@sxy-k8sB-master01 ~]# grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"

#检查默认内核是不是4.19
[root@sxy-k8sB-master01 ~]# grubby --default-kernel
/boot/vmlinuz-4.19.12-1.el7.elrepo.x86_6
所有节点重启,然后检查内核是不是4.19
[root@sxy-k8sB-master01 ~]# uname -a
Linux sxy-k8sB-master01 4.19.12-1.el7.elrepo.x86_64 #1 SMP Fri Dec 21 11:06:36 EST 2018 x86_64 x86_64 x86_64 GNU/Linux

所有节点安装ipvsadm:
[root@sxy-k8sB-master01 ~]# yum install ipvsadm ipset sysstat conntrack libseccomp -y

[root@sxy-k8sB-master01 ~]# 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

##重启
[root@sxy-k8sB-master01 ~]# systemctl enable --now systemd-modules-load.service

#检查是否加载:
[root@sxy-k8sB-master01 ~]# lsmod | grep -e ip_vs -e nf_conntrack
ip_vs_ftp              16384  0 
nf_nat                 32768  1 ip_vs_ftp
ip_vs_sed              16384  0 
ip_vs_nq               16384  0 
ip_vs_fo               16384  0 
ip_vs_sh               16384  0 
ip_vs_dh               16384  0 
ip_vs_lblcr            16384  0 
ip_vs_lblc             16384  0 
ip_vs_wrr              16384  0 
ip_vs_rr               16384  0 


开启一些k8s集群中必须的内核参数,所有节点配置k8s内核:
[root@sxy-k8sB-master01 ~]# 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

[root@sxy-k8sB-master01 ~]# sysctl --system

#所有节点配置完内核后,重启服务器,保证重启后内核依旧加载
[root@sxy-k8sB-master01 ~]# lsmod | grep --color=auto -e ip_vs -e nf_conntrack


Docker安装

#所有节点
[root@sxy-k8sB-master01 ~]# yum install docker-ce-19.03.* -y

#由于新版kubelet建议使用systemd,所以可以把docker的CgroupDriver改成systemd
[root@sxy-k8sB-master01 ~]# mkdir /etc/docker
[root@sxy-k8sB-master01 ~]# cat > /etc/docker/daemon.json <<EOF
> {
>   "exec-opts": ["native.cgroupdriver=systemd"]
> }
> EOF

#所有节点设置开机自启动Docker:
[root@sxy-k8sB-master01 ~]# systemctl daemon-reload && systemctl enable --now docker

K8s及etcd安装

###选择最新版下载
[root@sxy-k8sB-node02 ~]# wget https://dl.k8s.io/v1.20.11/kubernetes-server-linux-amd64.tar.gz
#解压kubernetes安装文件
[root@sxy-k8sB-master01 ~]# tar -xf kubernetes-server-linux-amd64.tar.gz  --strip-components=3 -C /usr/local/bin 
#下载etcd安装包
[root@sxy-k8sB-master01 ~]# wget https://github.com/etcd-io/etcd/releases/download/v3.4.13/etcd-v3.4.13-linux-amd64.tar.gz
#解压ETCD文件

[root@sxy-k8sB-master01 ~]# 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}

#组件发到其他节点
[root@sxy-k8sB-master01 ~]# MasterNodes='sxy-k8sB-master02s^C-k8sB-master03'
[root@sxy-k8sB-master01 ~]# MasterNodes='sxy-k8sB-master02 sxy-k8sB-master03'
[root@sxy-k8sB-master01 ~]# WorkNodes='sxy-k8sB-node01 sxy-k8sB-node02'
[root@sxy-k8sB-master01 ~]# 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

所有节点创建目录
[root@sxy-k8sB-master01 ~]# mkdir -p /opt/cni/bin
#Master01切换到1.20.x分支(其他版本可以切换到其他分支)
[root@sxy-k8sB-master01 ~]# cd k8s-ha-install && git checkout manual-installation-v1.20.x

生成证书

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/cfssljso
etcd证书
所有Master节点创建etcd证书目录
[root@sxy-k8sB-master01 ~]# mkdir /etc/etcd/ssl -p

所有节点创建kubernetes相关目录
[root@sxy-k8sB-master01 ~]# mkdir -p /etc/kubernetes/pki

Master01节点生成etcd证书
[root@sxy-k8sB-master01 ~]# cd /root/k8s-ha-install/pki

[root@sxy-k8sB-master01 pki]# cfssl gencert -initca etcd-ca-csr.json | cfssljson -bare /etc/etcd/ssl/etcd-ca
2021/09/23 13:38:07 [INFO] generating a new CA key and certificate from CSR
2021/09/23 13:38:07 [INFO] generate received request
2021/09/23 13:38:07 [INFO] received CSR
2021/09/23 13:38:07 [INFO] generating key: rsa-2048
2021/09/23 13:38:08 [INFO] encoded CSR
2021/09/23 13:38:08 [INFO] signed certificate with serial number 714578536162361357839119151799816525922708582947

[root@sxy-k8sB-master01 pki]# 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,sxy-k8sB-master01,sxy-k8sB-master02,k8s-master03,192.168.202.191,192.168.202.192,192.168.202.193 \
>    -profile=kubernetes \
>    etcd-csr.json | cfssljson -bare /etc/etcd/ssl/etcd

2021/09/23 13:38:55 [INFO] generate received request
2021/09/23 13:38:55 [INFO] received CSR
2021/09/23 13:38:55 [INFO] generating key: rsa-2048
2021/09/23 13:38:55 [INFO] encoded CSR
2021/09/23 13:38:55 [INFO] signed certificate with serial number 592257562954525415964783139049002381804207134369


将证书复制到其他节点
[root@sxy-k8sB-master01 pki]# MasterNodes='sxy-k8sB-master02 sxy-k8sB-master03'
[root@sxy-k8sB-master01 pki]# WorkNodes='sxy-k8sB-node01 sxy-k8sB-node02'

[root@sxy-k8sB-master01 pki]# 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
etcd-ca-key.pem                                                                                                100% 1675     3.0MB/s   00:00    
etcd-ca.pem                                                                                                    100% 1367     2.3MB/s   00:00    
etcd-key.pem                                                                                                   100% 1675     3.0MB/s   00:00    
etcd.pem                                                                                                       100% 1521     3.1MB/s   00:00    
etcd-ca-key.pem                                                                                                100% 1675     3.6MB/s   00:00    
etcd-ca.pem                                                                                                    100% 1367     3.5MB/s   00:00    
etcd-key.pem                                                                                                   100% 1675     3.5MB/s   00:00    
etcd.pem                                                                                                       100% 1521     3.3MB/s   00:00  
k8s组件证书
Master01生成kubernetes证书
[root@sxy-k8sB-master01 pki]# cd /root/k8s-ha-install/pki

[root@sxy-k8sB-master01 pki]# cfssl gencert -initca ca-csr.json | cfssljson -bare /etc/kubernetes/pki/ca
2021/09/23 13:42:58 [INFO] generating a new CA key and certificate from CSR
2021/09/23 13:42:58 [INFO] generate received request
2021/09/23 13:42:58 [INFO] received CSR
2021/09/23 13:42:58 [INFO] generating key: rsa-2048
2021/09/23 13:42:59 [INFO] encoded CSR
2021/09/23 13:42:59 [INFO] signed certificate with serial number 625830786720910836753704089341680486695336236679

### # 17.96.0.0是k8s service的网段,如果说需要更改k8s service网段,那就需要更改17.96.0.1,
[root@sxy-k8sB-master01 pki]# cfssl gencert   -ca=/etc/kubernetes/pki/ca.pem   -ca-key=/etc/kubernetes/pki/ca-key.pem   -config=ca-config.json   -hostname=17.96.0.1,192.168.202.199,127.0.0.1,kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster,kubernetes.default.svc.cluster.local,192.168.202.191,192.168.202.192,192.168.202.193   -profile=kubernetes   apiserver-csr.json | cfssljson -bare /etc/kubernetes/pki/apiserver
2021/09/23 13:57:50 [INFO] generate received request
2021/09/23 13:57:50 [INFO] received CSR
2021/09/23 13:57:50 [INFO] generating key: rsa-2048
2021/09/23 13:57:50 [INFO] encoded CSR
2021/09/23 13:57:50 [INFO] signed certificate with serial number 506413729023178271676858922057232015366343570915

## 生成apiserver的聚合证书。Requestheader-client-xxx  requestheader-allowwd-xxx:aggerator
[root@sxy-k8sB-master01 pki]# cfssl gencert   -initca front-proxy-ca-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-ca 
2021/09/23 13:58:59 [INFO] generating a new CA key and certificate from CSR
2021/09/23 13:58:59 [INFO] generate received request
2021/09/23 13:58:59 [INFO] received CSR
2021/09/23 13:58:59 [INFO] generating key: rsa-2048
2021/09/23 13:59:00 [INFO] encoded CSR
2021/09/23 13:59:00 [INFO] signed certificate with serial number 46639735014959388897535952083440340716927249971

[root@sxy-k8sB-master01 pki]# 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
## 返回结果(忽略警告)
2021/09/23 13:59:14 [INFO] generate received request
2021/09/23 13:59:14 [INFO] received CSR
2021/09/23 13:59:14 [INFO] generating key: rsa-2048
2021/09/23 13:59:15 [INFO] encoded CSR
2021/09/23 13:59:15 [INFO] signed certificate with serial number 490712340124965306468828978424251937792451861594
2021/09/23 13:59:15 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

# 生成controller-manage的证书
[root@sxy-k8sB-master01 pki]# 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
2021/09/23 14:00:10 [INFO] generate received request
2021/09/23 14:00:10 [INFO] received CSR
2021/09/23 14:00:10 [INFO] generating key: rsa-2048
2021/09/23 14:00:10 [INFO] encoded CSR
2021/09/23 14:00:10 [INFO] signed certificate with serial number 441935209979025288307201385186500320121348312730
2021/09/23 14:00:10 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

# 注意,如果不是高可用集群,192.168.202.199:8443改为master01的地址,8443改为apiserver的端口,默认是6443
# set-cluster:设置一个集群项,
[root@sxy-k8sB-master01 pki]# kubectl config set-cluster kubernetes \
>      --certificate-authority=/etc/kubernetes/pki/ca.pem \
>      --embed-certs=true \
>      --server=https://192.168.202.199:8443 \
>      --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
Cluster "kubernetes" set.

# 设置一个环境项,一个上下文
[root@sxy-k8sB-master01 pki]# kubectl config set-cluster kubernetes \
>      --certificate-authority=/etc/kubernetes/pki/ca.pem \
>      --embed-certs=true \
>      --server=https://192.168.202.199:8443 \
>      --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
Cluster "kubernetes" set.
[root@sxy-k8sB-master01 pki]# kubectl config set-context system:kube-controller-manager@kubernetes \
>     --cluster=kubernetes \
>     --user=system:kube-controller-manager \
>     --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
Context "system:kube-controller-manager@kubernetes" created.

# set-credentials 设置一个用户项
[root@sxy-k8sB-master01 pki]# 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
User "system:kube-controller-manager" set.

# 使用某个环境当做默认环境
[root@sxy-k8sB-master01 pki]# kubectl config use-context system:kube-controller-manager@kubernetes \
>      --kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
Switched to context "system:kube-controller-manager@kubernetes".

[root@sxy-k8sB-master01 pki]# 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
2021/09/23 14:02:47 [INFO] generate received request
2021/09/23 14:02:47 [INFO] received CSR
2021/09/23 14:02:47 [INFO] generating key: rsa-2048
2021/09/23 14:02:48 [INFO] encoded CSR
2021/09/23 14:02:48 [INFO] signed certificate with serial number 684259820459008284308705643740626301308590336050
2021/09/23 14:02:48 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

# 注意,如果不是高可用集群,192.168.202.199:8443改为master01的地址,8443改为apiserver的端口,默认是6443
[root@sxy-k8sB-master01 pki]# kubectl config set-cluster kubernetes \
>      --certificate-authority=/etc/kubernetes/pki/ca.pem \
>      --embed-certs=true \
>      --server=https://192.168.202.199:8443 \
>      --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
Cluster "kubernetes" set.

[root@sxy-k8sB-master01 pki]# 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
User "system:kube-scheduler" set.

[root@sxy-k8sB-master01 pki]# kubectl config set-context system:kube-scheduler@kubernetes \
>      --cluster=kubernetes \
>      --user=system:kube-scheduler \
>      --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
Context "system:kube-scheduler@kubernetes" created.

[root@sxy-k8sB-master01 pki]# kubectl config use-context system:kube-scheduler@kubernetes \
>      --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
Switched to context "system:kube-scheduler@kubernetes".


[root@sxy-k8sB-master01 pki]# 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
2021/09/23 14:04:38 [INFO] generate received request
2021/09/23 14:04:38 [INFO] received CSR
2021/09/23 14:04:38 [INFO] generating key: rsa-2048
2021/09/23 14:04:39 [INFO] encoded CSR
2021/09/23 14:04:39 [INFO] signed certificate with serial number 720511964860218414200000140750748199449157885028
2021/09/23 14:04:39 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

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


[root@sxy-k8sB-master01 pki]# kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.202.199:8443     --kubeconfig=/etc/kubernetes/admin.kubeconfig
Cluster "kubernetes" set.

[root@sxy-k8sB-master01 pki]# 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
User "kubernetes-admin" set.

[root@sxy-k8sB-master01 pki]# kubectl config set-context kubernetes-admin@kubernetes     --cluster=kubernetes     --user=kubernetes-admin     --kubeconfig=/etc/kubernetes/admin.kubeconfig

[root@sxy-k8sB-master01 pki]# kubectl config use-context kubernetes-admin@kubernetes     --kubeconfig=/etc/kubernetes/admin.kubeconfig
Switched to context "kubernetes-admin@kubernetes".

# 创建ServiceAccount Key  secret
[root@sxy-k8sB-master01 pki]# openssl genrsa -out /etc/kubernetes/pki/sa.key 2048
Generating RSA private key, 2048 bit long modulus
................+++
......................................+++
e is 65537 (0x10001)

[root@sxy-k8sB-master01 pki]# openssl rsa -in /etc/kubernetes/pki/sa.key -pubout -out /etc/kubernetes/pki/sa.pub
writing RSA key


发送证书至其他节点
[root@sxy-k8sB-master01 pki]# for NODE in sxy-k8sB-master02 sxy-k8sB-master03; do
> for FILE in $(ls /etc/kubernetes/pki | grep -v etcd); 
> do
> scp /etc/kubernetes/pki/${FILE} $NODE:/etc/kubernetes/pki/${FILE};
> done;

[root@sxy-k8sB-master01 pki]# for FILE in admin.kubeconfig controller-manager.kubeconfig scheduler.kubeconfig;
> do
> scp /etc/kubernetes/${FILE} $NODE:/etc/kubernetes/${FILE};
> done;
admin.kubeconfig                                                                                               100% 6451    13.3MB/s   00:00    
controller-manager.kubeconfig                                                                                  100% 6587    13.4MB/s   00:00    
scheduler.kubeconfig                                                                                           100% 6515    12.0MB/s   00:00 
查看证书文件
[root@sxy-k8sB-master01 pki]# ls /etc/kubernetes/pki/
admin.csr      apiserver-key.pem  ca.pem                      front-proxy-ca.csr      front-proxy-client-key.pem  scheduler.csr
admin-key.pem  apiserver.pem      controller-manager.csr      front-proxy-ca-key.pem  front-proxy-client.pem      scheduler-key.pem
admin.pem      ca.csr             controller-manager-key.pem  front-proxy-ca.pem      sa.key                      scheduler.pem
apiserver.csr  ca-key.pem         controller-manager.pem      front-proxy-client.csr  sa.pub
[root@sxy-k8sB-master01 pki]#  ls /etc/kubernetes/pki/ |wc -l
23

Kubernetes系统组件配置

Etcd配置

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

Master01
[root@sxy-k8sB-master01 pki]# vim /etc/etcd/etcd.config.yml

name: 'sxy-k8sB-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.202.191:2380'
listen-client-urls: 'https://192.168.202.191:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.202.191:2380'
advertise-client-urls: 'https://192.168.202.191:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'sxy-k8sB-master01=https://192.168.202.191:2380,sxy-k8sB-master02=https://192.168.202.192:2380,k8s-master03=https://192.168.202.193: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
[root@sxy-k8sB-master02 ~]# vim /etc/etcd/etcd.config.yml

name: 'sxy-k8sB-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.202.192:2380'
listen-client-urls: 'https://192.168.202.192:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.202.192:2380'
advertise-client-urls: 'https://192.168.202.192:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'sxy-k8sB-master01=https://192.168.202.191:2380,sxy-k8sB-master02=https://192.168.202.192:2380,k8s-master03=https://192.168.202.193: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
[root@sxy-k8sB-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.202.193:2380'
listen-client-urls: 'https://192.168.202.193:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.202.193:2380'
advertise-client-urls: 'https://192.168.202.193:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'sxy-k8sB-master01=https://192.168.202.191:2380,sxy-k8sB-master02=https://192.168.202.192:2380,k8s-master03=https://192.168.202.193: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
创建Service
所有Master节点创建etcd service并启动
[root@sxy-k8sB-master01 pki]# 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的证书目录
[root@sxy-k8sB-master01 pki]# mkdir /etc/kubernetes/pki/etcd
[root@sxy-k8sB-master01 pki]# ln -s /etc/etcd/ssl/* /etc/kubernetes/pki/etcd/
[root@sxy-k8sB-master01 pki]# systemctl daemon-reload
[root@sxy-k8sB-master01 pki]# systemctl enable --now etcd
Created symlink from /etc/systemd/system/etcd3.service to /usr/lib/systemd/system/etcd.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/etcd.service to /usr/lib/systemd/system/etcd.service.

查看excd状态
[root@sxy-k8sB-master01 pki]# export ETCDCTL_API=3

[root@sxy-k8sB-master01 pki]# etcdctl --endpoints="192.168.202.193:2379,192.168.202.192:2379,192.168.202.191: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.202.193:2379 |  ed09934c14e08c4 |  3.4.13 |   20 kB |     false |      false |         2 |          8 |                  8 |        |
| 192.168.202.192:2379 | 9ba14ba2ca4d695c |  3.4.13 |   20 kB |      true |      false |         2 |          8 |                  8 |        |
| 192.168.202.191:2379 | 8119ddd527b15244 |  3.4.13 |   20 kB |     false |      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
[root@sxy-k8sB-master01 pki]# yum install keepalived haproxy -y

所有Master配置HAProxy,配置一样
[root@sxy-k8sB-master01 pki]# 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 sxy-k8sB-master01    192.168.202.191:6443  check
  server sxy-k8sB-master02    192.168.202.192:6443  check
  serversxy-k8sB-master03    192.168.202.193:6443  check

Master01 keepalived

所有Master节点配置KeepAlived,配置不一样,注意区分 [root@sxy-k8sB-master01 pki]# vim /etc/keepalived/keepalived.conf ,注意每个节点的IP和网卡(interface参数)

[root@sxy-k8sB-master01 pki]# 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 ens160
    mcast_src_ip 192.168.202.191
    virtual_router_id 51
    priority 101
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass K8SHA_KA_AUTH
    }
    virtual_ipaddress {
        192.168.202.199
    }
    track_script {
      chk_apiserver
} }

master02
[root@sxy-k8sB-master02 ~]# 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 ens160
    mcast_src_ip 192.168.202.192
    virtual_router_id 51
    priority 100
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass K8SHA_KA_AUTH
    }
    virtual_ipaddress {
        192.168.202.199
    }
    track_script {
      chk_apiserver 
} }

master03
[root@sxy-k8sB-master03 ~]# 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 ens160
    mcast_src_ip 192.168.202.193
    virtual_router_id 51
    priority 100
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass K8SHA_KA_AUTH
    }
    virtual_ipaddress {
        192.168.202.199
    }
    track_script {
      chk_apiserver 
} }

健康检查配置

所有master节点
[root@sxy-k8sB-master01 pki]# 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

[root@sxy-k8sB-master01 pki]# chmod +x /etc/keepalived/check_apiserver.sh

所有master节点启动haproxy和keepalived
[root@sxy-k8sB-master01 pki]# systemctl daemon-reload
[root@sxy-k8sB-master01 pki]# systemctl enable --now haproxy
Created symlink from /etc/systemd/system/multi-user.target.wants/haproxy.service to /usr/lib/systemd/system/haproxy.service.
[root@sxy-k8sB-master01 pki]# systemctl enable --now keepalived
Created symlink from /etc/systemd/system/multi-user.target.wants/keepalived.service to /usr/lib/systemd/system/keepalived.service.

VIP测试
[root@sxy-k8sB-master01 ~]#  ping 192.168.202.199
PING 192.168.202.199 (192.168.202.199) 56(84) bytes of data.
64 bytes from 192.168.202.199: icmp_seq=1 ttl=64 time=179 ms
64 bytes from 192.168.202.199: icmp_seq=2 ttl=64 time=0.207 ms
64 bytes from 192.168.202.199: icmp_seq=3 ttl=64 time=0.224 ms

如果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

查看routeID是否冲突

Kubernetes组件配置

所有节点创建相关目录
[root@sxy-k8sB-master01 log]# mkdir -p /etc/kubernetes/manifests/ /etc/systemd/system/kubelet.service.d /var/lib/kubelet /var/log/kubernetes

Apiserver

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

Master01配置
[root@sxy-k8sB-master01 log]# 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.202.191 \
      --service-cluster-ip-range=17.96.0.0/12  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.202.191:2379,https://192.168.202.192:2379,https://192.168.202.193: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
[root@sxy-k8sB-master02 ~]# 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.202.192 \
      --service-cluster-ip-range=17.96.0.0/12  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.202.191:2379,https://192.168.202.192:2379,https://192.168.202.193: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
[root@sxy-k8sB-master03 ~]# 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.202.193 \
      --service-cluster-ip-range=17.96.0.0/12  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.202.191:2379,https://192.168.202.192:2379,https://192.168.202.193: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
启动apiserver
所有Master节点开启kube-apiserver
[root@sxy-k8sB-master01 log]# systemctl daemon-reload && systemctl enable --now kube-apiserver
Created symlink from /etc/systemd/system/multi-user.target.wants/kube-apiserver.service to /usr/lib/systemd/system/kube-apiserver.service.

检测kube-server状态
[root@sxy-k8sB-master01 log]# systemctl status kube-apiserver
● kube-apiserver.service - Kubernetes API Server
   Loaded: loaded (/usr/lib/systemd/system/kube-apiserver.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2021-09-23 15:28:21 CST; 21s ago
     Docs: https://github.com/kubernetes/kubernetes
 Main PID: 3230 (kube-apiserver)
   CGroup: /system.slice/kube-apiserver.service
           └─3230 /usr/local/bin/kube-apiserver --v=2 --logtostderr=true --allow-privileged=true --bind-address=0.0.0.0 --secure-port=6443 --i...


ControllerManager

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

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

[root@sxy-k8sB-master01 log]# 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=174.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
[root@sxy-k8sB-master01 log]#  systemctl daemon-reload
[root@sxy-k8sB-master01 log]#  systemctl enable --now kube-controller-manager
Created symlink from /etc/systemd/system/multi-user.target.wants/kube-controller-manager.service to /usr/lib/systemd/system/kube-controller-manager.service.

### 查看启动状态
[root@sxy-k8sB-master01 log]#  systemctl enable --now kube-controller-manager
[root@sxy-k8sB-master01 log]#  systemctl  status kube-controller-manager
● kube-controller-manager.service - Kubernetes Controller Manager
   Loaded: loaded (/usr/lib/systemd/system/kube-controller-manager.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2021-09-23 15:31:53 CST; 41s ago
     Docs: https://github.com/kubernetes/kubernetes
 Main PID: 3566 (kube-controller)
   CGroup: /system.slice/kube-controller-manager.service

遇到无法启动的请使用重启大法

Scheduler

所有Master节点配置kube-scheduler service
[root@sxy-k8sB-master03 kubernetes]# 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.targe

[root@sxy-k8sB-master01 pki]# systemctl daemon-reload

[root@sxy-k8sB-master01 pki]# systemctl enable --now kube-scheduler

TLS Bootstrapping配置

在Master01创建bootstrap

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

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

[root@sxy-k8sB-master01 ~]# cd /root/k8s-ha-install/bootstrap
[root@sxy-k8sB-master01 bootstrap]# kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.202.199:8443     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
Cluster "kubernetes" set.
[root@sxy-k8sB-master01 bootstrap]# kubectl config set-credentials tls-bootstrap-token-user     --token=c8ad9c.2e4d610cf3e7426e --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
User "tls-bootstrap-token-user" set.
[root@sxy-k8sB-master01 bootstrap]# kubectl config set-context tls-bootstrap-token-user@kubernetes     --cluster=kubernetes     --user=tls-bootstrap-token-user     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
Context "tls-bootstrap-token-user@kubernetes" created.
[root@sxy-k8sB-master01 bootstrap]# kubectl config use-context tls-bootstrap-token-user@kubernetes     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
Switched to context "tls-bootstrap-token-user@kubernetes".


[root@sxy-k8sB-master01 bootstrap]# mkdir -p /root/.kube ; cp /etc/kubernetes/admin.kubeconfig /root/.kube/config


[root@sxy-k8sB-master01 bootstrap]# kubectl create -f bootstrap.secret.yaml

复制证书

Master01节点复制证书至Node节点
[root@sxy-k8sB-master01 bootstrap]# cd /etc/kubernetes/
[root@sxy-k8sB-master01 kubernetes]# for NODE in sxy-k8sB-master02 sxy-k8sB-master03 sxy-k8sB-node01 sxy-k8sB-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配置

所有节点创建相关目录
[root@sxy-k8sB-master01 kubernetes]# mkdir -p /var/lib/kubelet /var/log/kubernetes /etc/systemd/system/kubelet.service.d /etc/kubernetes/manifests/

所有节点配置kubelet service
[root@sxy-k8sB-node02 ~]# 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的配置文件
[root@sxy-k8sB-master01 kubernetes]# 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

[root@sxy-k8sB-master01 kubernetes]# 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:
- 17.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
[root@sxy-k8sB-master01 kubernetes]# systemctl daemon-reload
[root@sxy-k8sB-master01 kubernetes]# systemctl enable --now kubelet
Created symlink from /etc/systemd/system/multi-user.target.wants/kubelet.service to /usr/lib/systemd/system/kubelet.service.

此时系统日志/var/log/messages
Unable to update cni config: no networks found in /etc/cni/net.d 显示只有如下信息为正常

kube-proxy配置

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

以下操作在Master01执行
[root@sxy-k8sB-master01 kubernetes]# 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.202.199: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
在master01将kube-proxy的systemd Service文件发送到其他节点

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

for NODE in sxy-k8sB-master01 sxy-k8sB-master02sxy-k8sB-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 sxy-k8sB-node01 sxy-k8sB-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
[root@sxy-k8sB-master01 k8s-ha-install]# systemctl daemon-reload
[root@sxy-k8sB-master01 k8s-ha-install]# systemctl enable --now kube-proxy
Created symlink from /etc/systemd/system/multi-user.target.wants/kube-proxy.service to /usr/lib/systemd/system/kube-proxy.service.

安装Calico

以下步骤只在master01执行
[root@sxy-k8sB-master01 k8s-ha-install]# cd /root/k8s-ha-install/calico/

#修改calico-etcd.yaml的以下位置
[root@sxy-k8sB-master01 calico]# sed -i 's#etcd_endpoints: "http://<ETCD_IP>:<ETCD_PORT>"#etcd_endpoints: "https://192.168.202.191:2379,https://192.168.202.192:2379,https://192.168.202.193:2379"#g' calico-etcd.yaml

[root@sxy-k8sB-master01 calico]# ETCD_CA=`cat /etc/kubernetes/pki/etcd/etcd-ca.pem | base64 | tr -d '\n'`
[root@sxy-k8sB-master01 calico]# ETCD_CERT=`cat /etc/kubernetes/pki/etcd/etcd.pem | base64 | tr -d '\n'`
[root@sxy-k8sB-master01 calico]# ETCD_KEY=`cat /etc/kubernetes/pki/etcd/etcd-key.pem | base64 | tr -d '\n'`
[root@sxy-k8sB-master01 calico]# 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
[root@sxy-k8sB-master01 calico]# 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网段
[root@sxy-k8sB-master01 calico]# POD_SUBNET="174.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.202.0/24"@  value: '"${POD_SUBNET}"'@g' calico-etcd.yaml

安装CoreDNS

安装对应版本(推荐)
[root@sxy-k8sB-master01 ~]# cd /root/k8s-ha-install/

[root@sxy-k8sB-master01 k8s-ha-install]# sed -i "s#10.96.0.10#17.96.0.10#g" CoreDNS/coredns.yaml

安装coredns
[root@sxy-k8sB-master01 k8s-ha-install]# kubectl  create -f CoreDNS/coredns.yaml 
Logo

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

更多推荐