基于centos7.9二进制部署kubernetes1.25.4

基于centos7.9二进制部署kubernetes1.25.4

1、环境准备

IP地址 主机 角色 系统
192.168.100.153 k8s-master01 K8S集群主节点 Centos7.9
192.168.100.154 k8s-master02 K8S集群主节点 Centos7.9
192.168.100.155 k8s-master03 K8S集群主节点 Centos7.9
192.168.100.156 k8s-node01 K8S集群从节点 Centos7.9
192.168.100.157 k8s-node02 K8S集群从节点 Centos7.9
192.168.100.99 虚拟IP keepalived虚拟IP,配置在master01  
1-1、主机名互相解析
 #所有节点:
 [root@k8s-master01 ~]#hostnamectl set-hostname k8s-master03
 [root@k8s-master01 ~]#vim /etc/hosts
 192.168.100.153 k8s-master01
 192.168.100.154 k8s-master02
 192.168.100.155 k8s-master03
 192.168.100.99 k8s-master-vip
 192.168.100.156 k8s-node01
 192.168.100.157 k8s-node02
1-2、CentOS Yum源配置
 #所有节点:
 [root@k8s-master01 ~]#curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
 [root@k8s-master01 ~]#yum install -y yum-utils device-mapper-persistent-data lvm2
 [root@k8s-master01 ~]#yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
1-3、必备工具安装
 #所有节点:
 [root@k8s-master01 ~]#yum install wget jq psmisc vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 git -y
1-4、关闭防火墙
 #所有节点:
 [root@k8s-master01 ~]#systemctl disable --now firewalld
 [root@k8s-master01 ~]#systemctl disable --now dnsmasq
 [root@k8s-master01 ~]#systemctl disable --now NetworkManager
 [root@k8s-master01 ~]#setenforce 0
 [root@k8s-master01 ~]#sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/sysconfig/selinux
 [root@k8s-master01 ~]#sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
 [root@k8s-master01 ~]#cat /etc/sysconfig/selinux
 [root@k8s-master01 ~]#cat /etc/selinux/config
1-5、禁用swap
 #所有节点:
 [root@k8s-master01 ~]#swapoff -a && sysctl -w vm.swappiness=0
 [root@k8s-master01 ~]#sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab
1-6、时间同步
 #所有节点:
 [root@k8s-master01 ~]#ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
 [root@k8s-master01 ~]#echo 'Asia/Shanghai' >/etc/timezone
 [root@k8s-master01 ~]#yum install -y chrony
 [root@k8s-master01 ~]#systemctl restart chronyd
 [root@k8s-master01 ~]#systemctl enable --now chronyd
 [root@k8s-master01 ~]#chronyc sources 
1-7、所有节点配置limit
 #所有节点:
 [root@k8s-master01 ~]#ulimit -SHn 65535
 ​
 [root@k8s-master01 ~]#vim /etc/security/limits.conf   #最后增加
 * soft nofile 65536
 * hard nofile 131072
 * soft nproc 65535
 * hard nproc 655350
 * soft memlock unlimited
 * hard memlock unlimited
1-8、系统升级、内核升级
 # 所有节点
 [root@k8s-master01 ~]#yum update -y --exclude=kernel*
 [root@k8s-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@k8s-master01 ~]#wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-4.19.12-1.el7.elrepo.x86_64.rpm
 [root@k8s-master01 ~]# yum localinstall -y kernel-ml*
 ​
 # 更改内核启动顺序
 [root@k8s-master01 ~]# grub2-set-default  0 && grub2-mkconfig -o /etc/grub2.cfg
 [root@k8s-master01 ~]# grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"
 ​
 # 检查默认内核是不是4.19
 [root@k8s-master01 ~]#  grubby --default-kernel
 /boot/vmlinuz-4.19.12-1.el7.elrepo.x86_64
 [root@k8s-master01 ~]# reboot
 ​
 [root@k8s-master01 ~]# uname -r
 4.19.12-1.el7.elrepo.x86_64
1-9、安装ipvsadm
# 所有节点
[root@k8s-master01 ~]# yum install ipvsadm ipset sysstat conntrack libseccomp -y

[root@k8s-master01 ~]# modprobe -- ip_vs
[root@k8s-master01 ~]# modprobe -- ip_vs_rr
[root@k8s-master01 ~]# modprobe -- ip_vs_wrr
[root@k8s-master01 ~]# modprobe -- ip_vs_sh
[root@k8s-master01 ~]# modprobe -- nf_conntrack


[root@k8s-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@k8s-master01 ~]# systemctl enable --now systemd-modules-load.service
[root@k8s-master01 ~]# lsmod | grep -e ip_vs -e nf_conntrack
1-10、开启支持k8s内核参数
# 所有节点

# 开启路由转发和一些集群中必须的内核参数优化
[root@k8s-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
net.ipv4.conf.all.route_localnet = 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@k8s-master01 ~]# sysctl --system

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

2、安装containerd

# 所有节点

#安装docker-ce-20.10
[root@k8s-master01 ~]# yum install docker-ce-20.10.* docker-ce-cli-20.10.* containerd -y

# 配置Containerd所需的模块
[root@k8s-master01 ~]# cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF

[root@k8s-master01 ~]# modprobe -- overlay
[root@k8s-master01 ~]# modprobe -- br_netfilter

# 配置Containerd所需的内核
[root@k8s-master01 ~]# cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward                 = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

[root@k8s-master01 ~]# sysctl --system

# 配置Containerd的配置文件
[root@k8s-master01 ~]# mkdir -p /etc/containerd
[root@k8s-master01 ~]# containerd config default | tee /etc/containerd/config.toml
# 将Containerd的Cgroup改为Systemd,pause下载改为阿里云:

[root@k8s-master01 ~]# vim /etc/containerd/config.toml
......
sandbox_image = "registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.8"   #修改此行为阿里云地址,大约在61行
......
          [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
            BinaryName = ""
            CriuImagePath = ""
            CriuPath = ""
            CriuWorkPath = ""
            IoGid = 0
            IoUid = 0
            NoNewKeyring = false
            NoPivotRoot = false
            Root = ""
            ShimCgroup = ""
            SystemdCgroup = true             #大约在125行
......


[root@k8s-master01 ~]# systemctl daemon-reload && systemctl enable --now containerd

# 配置crictl客户端连接的运行时位置
[root@k8s-master01 ~]# cat > /etc/crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF

3、生成证书

说明:目前版本是1.25.4,安装时需要下载最新的1.25.x版本:(进入后点击Server Binaries 选择ARM Server版本)

https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.25.md

3-1、下载相关组件
# master01:

#下载kubernetes安装包
[root@k8s-master01 ~]# wget https://dl.k8s.io/v1.25.4/kubernetes-server-linux-amd64.tar.gz

# 下载etcd安装包
[root@k8s-master01 ~]#wget https://github.com/etcd-io/etcd/releases/download/v3.5.4/etcd-v3.5.4-linux-amd64.tar.gz
 
 
# 解压kubernetes安装文件
[root@k8s-master01 ~]# 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}
#说明:--strip-components=3 是剥离前三级目录

# 解压etcd安装文件
[root@k8s-master01 ~]# tar -zxvf etcd-v3.5.4-linux-amd64.tar.gz --strip-components=1 -C /usr/local/bin etcd-v3.5.4-linux-amd64/etcd{,ctl}

[root@k8s-master01 ~]# ls /usr/local/bin/
etcd     kube-apiserver           kubectl  kube-proxy
etcdctl  kube-controller-manager  kubelet  kube-scheduler

[root@k8s-master01 ~]# kubelet --version
Kubernetes v1.25.4
[root@k8s-master01 ~]# etcdctl version
etcdctl version: 3.5.4
API version: 3.5

# 将组件发送到其他节点
[root@k8s-master01 ~]# for i in k8s-master02 k8s-master03 k8s-node01 k8s-node02;do
> scp /usr/local/bin/kube{let,ctl,-apiserver,-proxy,-scheduler,-controller-manager} $i:/usr/local/bin/; scp /usr/local/bin/etcd* $i:/usr/local/bin/
> done

# 所有节点创建/opt/cni/bin目录
[root@k8s-master01 ~]# mkdir -p /opt/cni/bin
3-1、下载生成证书工具
[root@k8s-master01 ~]# wget "https://pkg.cfssl.org/R1.2/cfssl_linux-amd64" -O /usr/local/bin/cfssl

[root@k8s-master01 ~]# wget "https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64" -O /usr/local/bin/cfssljson

[root@k8s-master01 ~]# wget "https://pkg.cfssl.org/R1.2/cfssl-certinfo_1.6.1_linux_amd64" -O /usr/local/bin/cfssl-certinfo

[root@k8s-master01 ~]# chmod +x /usr/local/bin/cfssl*
3-3、etcd证书
# 所有节点
[root@k8s-master01 ~]# mkdir /etc/etcd/ssl -p
[root@k8s-master01 ~]# mkdir /etc/kubernetes/pki -p


# master01:
[root@k8s-master01 ~]# cd k8s-ha-install/
[root@k8s-master01 k8s-ha-install]# git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/manual-installation
  remotes/origin/manual-installation-v1.16.x
  remotes/origin/manual-installation-v1.17.x
  remotes/origin/manual-installation-v1.18.x
  remotes/origin/manual-installation-v1.19.x
  remotes/origin/manual-installation-v1.20.x
  remotes/origin/manual-installation-v1.20.x-csi-hostpath
  remotes/origin/manual-installation-v1.21.x
  remotes/origin/manual-installation-v1.22.x
  remotes/origin/manual-installation-v1.23.x
  remotes/origin/manual-installation-v1.24.x
  remotes/origin/manual-installation-v1.25.x
  remotes/origin/master
  
# 切换到1.25.x分支(其他版本可以切换到其他分支,.x即可,不需要更改为具体的数字)
[root@k8s-master01 k8s-ha-install]# git checkout manual-installation-v1.25.x
Branch manual-installation-v1.25.x set up to track remote branch manual-installation-v1.25.x from origin.
Switched to a new branch 'manual-installation-v1.25.x'
[root@k8s-master01 pki]# ls
admin-csr.json      ca-csr.json       front-proxy-ca-csr.json      kube-proxy-csr.json
apiserver-csr.json  etcd-ca-csr.json  front-proxy-client-csr.json  manager-csr.json
ca-config.json      etcd-csr.json     kubelet-csr.json             scheduler-csr.json


# 生成etcd CA证书和CA证书的key
[root@k8s-master01 pki]# cfssl gencert -initca etcd-ca-csr.json | cfssljson -bare /etc/etcd/ssl/etcd-ca


[root@k8s-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,k8s-master01,k8s-master02,k8s-master03,192.168.100.153,192.168.100.154,192.168.100.155 \
-profile=kubernetes \
etcd-csr.json | cfssljson -bare /etc/etcd/ssl/etcd

2022/11/16 19:45:32 [INFO] generate received request
2022/11/16 19:45:32 [INFO] received CSR
2022/11/16 19:45:32 [INFO] generating key: rsa-2048
2022/11/16 19:45:33 [INFO] encoded CSR
2022/11/16 19:45:33 [INFO] signed certificate with serial number 497579505319136534258647128183377500491269693934

# 将证书复制到其他Master节点
[root@k8s-master01 pki]# scp /etc/etcd/ssl/*.pem 192.168.100.154:/etc/etcd/ssl/
[root@k8s-master01 pki]# scp /etc/etcd/ssl/*.pem 192.168.100.155:/etc/etcd/ssl/
3-4、生成k8s其他组件证书
# master01

# 生成kubernetes证书
[root@k8s-master01 pki]# cfssl gencert -initca ca-csr.json | cfssljson -bare /etc/kubernetes/pki/ca
2022/11/16 19:52:29 [INFO] generating a new CA key and certificate from CSR
2022/11/16 19:52:29 [INFO] generate received request
2022/11/16 19:52:29 [INFO] received CSR
2022/11/16 19:52:29 [INFO] generating key: rsa-2048
2022/11/16 19:52:29 [INFO] encoded CSR
2022/11/16 19:52:29 [INFO] signed certificate with serial number 430208719002673708340685834561638947457362482649

# 10.96.0.1.是k8s service的网段,如果说需要更改k8s service网段,那就需要更改10.96.0.1,
# 如果不是高可用集群,192.168.100.99为Master01的IP
[root@k8s-master01 pki]# 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.100.99,127.0.0.1,kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster,kubernetes.default.svc.cluster.local,192.168.100.153,192.168.100.154,192.168.100.155   -profile=kubernetes   apiserver-csr.json | cfssljson -bare /etc/kubernetes/pki/apiserver

2022/11/16 19:54:36 [INFO] generate received request
2022/11/16 19:54:36 [INFO] received CSR
2022/11/16 19:54:36 [INFO] generating key: rsa-2048
2022/11/16 19:54:36 [INFO] encoded CSR
2022/11/16 19:54:37 [INFO] signed certificate with serial number 148342655706954807225322374042758254794472502284


# 生成apiserver的聚合证书。Requestheader-client-xxx  requestheader-allowwd-xxx:aggerator
[root@k8s-master01 pki]# cfssl gencert   -initca front-proxy-ca-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-ca 
2022/11/16 19:54:59 [INFO] generating a new CA key and certificate from CSR
2022/11/16 19:54:59 [INFO] generate received request
2022/11/16 19:54:59 [INFO] received CSR
2022/11/16 19:54:59 [INFO] generating key: rsa-2048
2022/11/16 19:55:01 [INFO] encoded CSR
2022/11/16 19:55:01 [INFO] signed certificate with serial number 723218518093835071844654491175562369108910318661

[root@k8s-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
# 返回结果(忽略警告)
2022/11/16 19:55:25 [INFO] generate received request
2022/11/16 19:55:25 [INFO] received CSR
2022/11/16 19:55:25 [INFO] generating key: rsa-2048
2022/11/16 19:55:26 [INFO] encoded CSR
2022/11/16 19:55:26 [INFO] signed certificate with serial number 103250417928382168375525563395057855193395592806
2022/11/16 19:55:26 [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@k8s-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


# 注意,如果不是高可用集群,192.168.100.99:8443改为master01的地址,8443改为apiserver的端口,默认是6443
# set-cluster:设置一个集群项

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

# set-credentials 设置一个用户项
[root@k8s-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

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

[root@k8s-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
   
   
[root@k8s-master01 pki]# kubectl config set-cluster kubernetes \
     --certificate-authority=/etc/kubernetes/pki/ca.pem \
     --embed-certs=true \
     --server=https://192.168.100.99:8443 \
     --kubeconfig=/etc/kubernetes/scheduler.kubeconfig
     
     
[root@k8s-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

[root@k8s-master01 pki]# kubectl config set-context system:kube-scheduler@kubernetes \
     --cluster=kubernetes \
     --user=system:kube-scheduler \
     --kubeconfig=/etc/kubernetes/scheduler.kubeconfig


[root@k8s-master01 pki]# kubectl config use-context system:kube-scheduler@kubernetes \
     --kubeconfig=/etc/kubernetes/scheduler.kubeconfig


[root@k8s-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
   
   
   
[root@k8s-master01 pki]# kubectl config set-cluster kubernetes  --certificate-authority=/etc/kubernetes/pki/ca.pem  --embed-certs=true   --server=https://192.168.100.99:8443  --kubeconfig=/etc/kubernetes/admin.kubeconfig

[root@k8s-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

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

[root@k8s-master01 pki]# kubectl config use-context kubernetes-admin@kubernetes  --kubeconfig=/etc/kubernetes/admin.kubeconfig


# 创建ServiceAccount Key ➡ secret
[root@k8s-master01 pki]# openssl genrsa -out /etc/kubernetes/pki/sa.key 2048

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

[root@k8s-master01 pki]# ls /etc/kubernetes/pki/  | wc -l
23

# 发送证书至其他节点
[root@k8s-master01 pki]# scp /etc/kubernetes/pki/* 192.168.100.154:/etc/kubernetes/pki/
[root@k8s-master01 pki]# scp /etc/kubernetes/pki/* 192.168.100.155:/etc/kubernetes/pki/

4、配置etcd

4-1、配置etcd

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

# master01:
[root@k8s-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.100.153:2380'
listen-client-urls: 'https://192.168.100.153:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.100.153:2380'
advertise-client-urls: 'https://192.168.100.153:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master01=https://192.168.100.153:2380,k8s-master02=https://192.168.100.154:2380,k8s-master03=https://192.168.100.155: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@k8s-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.100.154:2380'
listen-client-urls: 'https://192.168.100.154:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.100.154:2380'
advertise-client-urls: 'https://192.168.100.154:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master01=https://192.168.100.153:2380,k8s-master02=https://192.168.100.154:2380,k8s-master03=https://192.168.100.155: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@k8s-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.100.155:2380'
listen-client-urls: 'https://192.168.100.155:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.100.155:2380'
advertise-client-urls: 'https://192.168.100.155:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master01=https://192.168.100.153:2380,k8s-master02=https://192.168.100.154:2380,k8s-master03=https://192.168.100.155: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
4-2、创建用于etcd的service
# 所有Master节点创建etcd service并启动
[root@k8s-master01 ~]# 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@k8s-master01 ~]# mkdir /etc/kubernetes/pki/etcd
[root@k8s-master01 ~]# ln -s /etc/etcd/ssl/* /etc/kubernetes/pki/etcd/
[root@k8s-master01 ~]# systemctl daemon-reload
[root@k8s-master01 ~]# systemctl enable --now etcd


# 查看etcd状态
[root@k8s-master01 ~]# export ETCDCTL_API=3
[root@k8s-master01 ~]#  etcdctl --endpoints="192.168.100.153:2379,192.168.100.154:2379,192.168.100.155: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.100.153:2379 | e9f58d0912257160 |   3.5.4 |   20 kB |      true |      false |         2 |          9 |                  9 |        |
| 192.168.100.154:2379 | 7b304cf1777afde5 |   3.5.4 |   25 kB |     false |      false |         2 |          9 |                  9 |        |
| 192.168.100.155:2379 | a3e2564921c8f7ea |   3.5.4 |   25 kB |     false |      false |         2 |          9 |                  9 |        |
+----------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+

5、配置高可用

说明:如果不是高可用集群,haproxy和keepalived无需安装

5-1、配置haproxy
# 所有Master节点安装keepalived和haproxy
[root@k8s-master01 ~]# yum install keepalived haproxy -y

# 所有Master配置HAProxy,配置一样,删掉默认所有内容后复制下列内容
[root@k8s-master01 ~]# 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.100.153:6443  check
  server k8s-master02    192.168.100.154:6443  check
  server k8s-master03    192.168.100.155:6443  check


[root@k8s-master01 ~]# scp /etc/haproxy/haproxy.cfg 192.168.100.154:/etc/haproxy/haproxy.cfg
  
[root@k8s-master01 ~]# scp /etc/haproxy/haproxy.cfg 192.168.100.155:/etc/haproxy/haproxy.cfg
5-2、配置keepalived
# 所有Master节点配置KeepAlived,配置不一样,注意区分,默认内容删除后复制下列内容
# 下列内容interface eth0网卡名修改成自己Master机器的网卡名
# 注意每个节点的IP和网卡(interface后的网卡名参数)

# master01
[root@k8s-master01 ~]# vim /etc/keepalived/keepalived.conf
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 eth0
#   mcast_src_ip 224.8.8.8
    virtual_router_id 51
    priority 101
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.100.99
    }
    unicast_src_ip 192.168.100.153
    unicast_peer {
        192.168.100.154
        192.168.100.155
    }
    track_script {
      chk_apiserver 
    } 
}


[root@k8s-master01 ~]# vim /etc/keepalived/check_apiserver.sh 
[root@k8s-master01 ~]# chmod +x /etc/keepalived/check_apiserver.sh
[root@k8s-master01 ~]# scp /etc/keepalived/check_apiserver.sh 192.168.100.154:/etc/keepalived/check_apiserver.sh
[root@k8s-master01 ~]# scp /etc/keepalived/check_apiserver.sh 192.168.100.155:/etc/keepalived/check_apiserver.sh
# master02
[root@k8s-master02 ~]# vim /etc/keepalived/keepalived.conf
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 eth0
#    mcast_src_ip 224.8.8.8
    virtual_router_id 51
    priority 100
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.100.99
    }
    unicast_src_ip 192.168.100.154
    unicast_peer {
        192.168.100.153
        192.168.100.155
    }

    track_script {
      chk_apiserver 
    } 
}
# master03
[root@k8s-master03 ~]# vim /etc/keepalived/keepalived.conf
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 eth0
#    mcast_src_ip 224.8.8.8
    virtual_router_id 51
    priority 100
    nopreempt
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.100.99
    }
    unicast_src_ip 192.168.100.155
    unicast_peer {
        192.168.100.153
        192.168.100.155
    }

    track_script {
      chk_apiserver 
    }
}
# 所有master节点
# 创建健康性检查脚本:
[root@k8s-master01 keepalived]# 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@k8s-master01 ~]# chmod +x /etc/keepalived/check_apiserver.sh
# 所有master节点启动haproxy和keepalived
[root@k8s-master01 ~]# systemctl daemon-reload && systemctl enable --now haproxy && systemctl enable --now keepalived

[root@k8s-master01 ~]# systemctl status haproxy keepalived

[root@k8s-master02 ~]# ping 192.168.100.99
PING 192.168.100.99 (192.168.100.99) 56(84) bytes of data.
64 bytes from 192.168.100.99: icmp_seq=1 ttl=64 time=1.23 ms

[root@k8s-master02 ~]# telnet 192.168.100.99 8443

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

6、配置k8s组件

# 所有节点
[root@k8s-master01 ~]# mkdir -p /etc/kubernetes/manifests/ /etc/systemd/system/kubelet.service.d /var/lib/kubelet /var/log/kubernetes

注意本文档使用的k8s service网段为192.168.0.0/16,该网段不能和宿主机的网段、Pod网段的重复,请按需修改

# master01:
[root@k8s-master01 ~]# 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  \
      --advertise-address=192.168.100.153 \
      --service-cluster-ip-range=10.96.0.0/16  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.100.153:2379,https://192.168.100.154:2379,https://192.168.100.155: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  \
	  --feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
      --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@k8s-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  \
      --advertise-address=192.168.100.154 \
      --service-cluster-ip-range=10.96.0.0/16  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.100.153:2379,https://192.168.100.154:2379,https://192.168.100.155: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  \
	  --feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
      --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@k8s-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  \
      --advertise-address=192.168.100.155 \
      --service-cluster-ip-range=10.96.0.0/16  \
      --service-node-port-range=30000-32767  \
      --etcd-servers=https://192.168.100.153:2379,https://192.168.100.154:2379,https://192.168.100.155: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  \
	  --feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
      --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
6-1、启动kube-apiserver
# 所有Master节点开启kube-apiserver
[root@k8s-master01 ~]# systemctl daemon-reload && systemctl enable --now kube-apiserver

[root@k8s-master01 ~]# systemctl status kube-apiserver
6-2、ControllerManager

说明:所有Master节点配置kube-controller-manager service(所有master节点配置一样)

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

# 所有Master节点:
[root@k8s-master01 ~]# 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 \
      --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 \
	  --feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
      --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
[root@k8s-master01 ~]# systemctl daemon-reload && systemctl enable --now kube-controller-manager && systemctl status kube-controller-manager
6-3、Schedule

说明:所有Master节点配置kube-scheduler service(所有master节点配置一样)

#所有master节点:
[root@k8s-master01 ~]# 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 \
      --leader-elect=true \
      --authentication-kubeconfig=/etc/kubernetes/scheduler.kubeconfig \
      --authorization-kubeconfig=/etc/kubernetes/scheduler.kubeconfig \
      --kubeconfig=/etc/kubernetes/scheduler.kubeconfig

Restart=always
RestartSec=10s

[Install]
WantedBy=multi-user.target

[root@k8s-master01 ~]# systemctl daemon-reload && systemctl enable --now kube-scheduler && systemctl status kube-scheduler
6-4、TLS Bootstrapping配置

说明:只需要在Master01创建bootstrap

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

# master01:
[root@k8s-master01 ~]# cd /root/k8s-ha-install/bootstrap

[root@k8s-master01 bootstrap]#  kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.100.99:8443     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig

[root@k8s-master01 bootstrap]# kubectl config set-credentials tls-bootstrap-token-user     --token=c8ad9c.2e4d610cf3e7426e --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig

[root@k8s-master01 bootstrap]# kubectl config set-context tls-bootstrap-token-user@kubernetes     --cluster=kubernetes     --user=tls-bootstrap-token-user     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig

[root@k8s-master01 bootstrap]# kubectl config use-context tls-bootstrap-token-user@kubernetes     --kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig

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

image-20221116210539756

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

# 可以正常查询集群状态,才可以继续往下,否则不行,需要排查k8s组件是否有故障
[root@k8s-master01 bootstrap]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS      MESSAGE                                                                                        ERROR
controller-manager   Unhealthy   Get "https://127.0.0.1:10257/healthz": dial tcp 127.0.0.1:10257: connect: connection refused   
scheduler            Unhealthy   Get "https://127.0.0.1:10259/healthz": dial tcp 127.0.0.1:10259: connect: connection refused   
etcd-1               Healthy     {"health":"true","reason":""}                                                                  
etcd-0               Healthy     {"health":"true","reason":""}                                                                  
etcd-2               Healthy     {"health":"true","reason":""}    

[root@k8s-master01 bootstrap]# kubectl create -f bootstrap.secret.yaml 
secret/bootstrap-token-c8ad9c created
clusterrolebinding.rbac.authorization.k8s.io/kubelet-bootstrap created
clusterrolebinding.rbac.authorization.k8s.io/node-autoapprove-bootstrap created
clusterrolebinding.rbac.authorization.k8s.io/node-autoapprove-certificate-rotation created
clusterrole.rbac.authorization.k8s.io/system:kube-apiserver-to-kubelet created
clusterrolebinding.rbac.authorization.k8s.io/system:kube-apiserver created

7、配置node节点

7-1、复制证书
# Master01节点复制证书至Node节点
[root@k8s-master01 bootstrap]# cd /etc/kubernetes/
[root@k8s-master01 kubernetes]#for NODE in k8s-master02 k8s-master03 k8s-node01 k8s-node02; do
     ssh $NODE mkdir -p /etc/kubernetes/pki
     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
7-2、配置Kubelet
# 所有节点创建相关目录
[root@k8s-master01 kubernetes]# mkdir -p /var/lib/kubelet /var/log/kubernetes /etc/systemd/system/kubelet.service.d /etc/kubernetes/manifests/

# 所有节点配置kubelet service
[root@k8s-master01 kubernetes]# vim  /usr/lib/systemd/system/kubelet.service
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/kubernetes/kubernetes

[Service]
ExecStart=/usr/local/bin/kubelet

Restart=always
StartLimitInterval=0
RestartSec=10

[Install]
WantedBy=multi-user.target
# 所有节点配置kubelet service的配置文件(也可以写到kubelet.service)
[root@k8s-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=--container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock"
Environment="KUBELET_CONFIG_ARGS=--config=/etc/kubernetes/kubelet-conf.yml"
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@k8s-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:
- 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


[root@k8s-master01 kubernetes]# systemctl daemon-reload && systemctl enable --now 
[root@k8s-master01 kubernetes]# systemctl status kubelet
7-3、kube-proxy配置

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

# 以下操作只在Master01执行
[root@k8s-master01 kubernetes]# cd /root/k8s-ha-install
[root@k8s-master01 k8s-ha-install]# kubectl -n kube-system create serviceaccount kube-proxy

[root@k8s-master01 k8s-ha-install]# kubectl create clusterrolebinding system:kube-proxy         --clusterrole system:node-proxier         --serviceaccount kube-system:kube-proxy

[root@k8s-master01 k8s-ha-install]# SECRET=$(kubectl -n kube-system get sa/kube-proxy \
 --output=jsonpath='{.secrets[0].name}')

[root@k8s-master01 k8s-ha-install]# JWT_TOKEN=$(kubectl -n kube-system get secret/$SECRET \
 --output=jsonpath='{.data.token}' | base64 -d)
 
[root@k8s-master01 k8s-ha-install]# PKI_DIR=/etc/kubernetes/pki

[root@k8s-master01 k8s-ha-install]# K8S_DIR=/etc/kubernetes

[root@k8s-master01 k8s-ha-install]#  kubectl config set-cluster kubernetes     --certificate-authority=/etc/kubernetes/pki/ca.pem     --embed-certs=true     --server=https://192.168.100.99:8443     --kubeconfig=${K8S_DIR}/kube-proxy.kubeconfig

[root@k8s-master01 k8s-ha-install]# kubectl config set-credentials kubernetes     --token=${JWT_TOKEN}     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig

[root@k8s-master01 k8s-ha-install]# kubectl config set-context kubernetes     --cluster=kubernetes     --user=kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig

[root@k8s-master01 k8s-ha-install]# kubectl config use-context kubernetes     --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig

# 将kubeconfig发送至其他节点
[root@k8s-master01 k8s-ha-install]# for NODE in k8s-master02 k8s-master03; do
scp /etc/kubernetes/kube-proxy.kubeconfig  $NODE:/etc/kubernetes/kube-proxy.kubeconfig
done
   
[root@k8s-master01 k8s-ha-install]# for NODE in k8s-node01 k8s-node02; do
scp /etc/kubernetes/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig
done

# 所有节点添加kube-proxy的配置和service文件:
[root@k8s-master01 k8s-ha-install]# vim /usr/lib/systemd/system/kube-proxy.service
[Unit]
Description=Kubernetes Kube Proxy
Documentation=https://github.com/kubernetes/kubernetes
After=network.target

[Service]
ExecStart=/usr/local/bin/kube-proxy \
  --config=/etc/kubernetes/kube-proxy.yaml \
  --v=2

Restart=always
RestartSec=10s

[Install]
WantedBy=multi-user.target


# 如果更改了集群Pod的网段,需要更改kube-proxy.yaml的clusterCIDR为自己的Pod网段:
[root@k8s-master01 k8s-ha-install]# vim /etc/kubernetes/kube-proxy.yaml
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
clientConnection:
  acceptContentTypes: ""
  burst: 10
  contentType: application/vnd.kubernetes.protobuf
  kubeconfig: /etc/kubernetes/kube-proxy.kubeconfig
  qps: 5
clusterCIDR: 172.16.0.0/12 
configSyncPeriod: 15m0s
conntrack:
  max: null
  maxPerCore: 32768
  min: 131072
  tcpCloseWaitTimeout: 1h0m0s
  tcpEstablishedTimeout: 24h0m0s
enableProfiling: false
healthzBindAddress: 0.0.0.0:10256
hostnameOverride: ""
iptables:
  masqueradeAll: false
  masqueradeBit: 14
  minSyncPeriod: 0s
  syncPeriod: 30s
ipvs:
  masqueradeAll: true
  minSyncPeriod: 5s
  scheduler: "rr"
  syncPeriod: 30s
kind: KubeProxyConfiguration
metricsBindAddress: 127.0.0.1:10249
mode: "ipvs"
nodePortAddresses: null
oomScoreAdj: -999
portRange: ""
udpIdleTimeout: 250ms

# 所有节点启动kube-proxy
[root@k8s-master01 k8s-ha-install]# systemctl daemon-reload && systemctl enable --now kube-proxy && systemctl status kube-proxy

8、安装Calico

# 以下步骤只在master01执行
[root@k8s-master01 k8s-ha-install]#cd /root/k8s-ha-install/calico/
# 更改calico的网段,主要需要将红色部分的网段,改为自己的Pod网段
[root@k8s-master01 calico]#sed -i "s#POD_CIDR#172.16.0.0/12#g" calico.yaml
# 检查网段是自己的Pod网段, grep "IPV4POOL_CIDR" calico.yaml  -A 1

更改后如下所示:

image-20221116213209169

[root@k8s-master01 calico]# kubectl apply -f calico.yaml

#稍等几分钟,查看pod状态
[root@k8s-master01 k8s-ha-install]# kubectl get pod -n kube-system
NAME                                       READY   STATUS    RESTARTS   AGE
calico-kube-controllers-86d8c4fb68-9wtm4   1/1     Running   0          2m53s
calico-node-kwhrq                          1/1     Running   0          2m52s
calico-node-nm7qs                          1/1     Running   0          2m53s
calico-node-qkzlv                          1/1     Running   0          2m53s
calico-node-tpl5n                          1/1     Running   0          2m53s
calico-typha-768795f74d-bht5m              1/1     Running   0          2m53s

9、安装CoreDNS

# master01

[root@k8s-master01 calico]# cd /root/k8s-ha-install/

# 如果更改了k8s service的网段需要将coredns的serviceIP改成k8s service网段的第十个IP
[root@k8s-master01 k8s-ha-install]# COREDNS_SERVICE_IP=`kubectl get svc | grep kubernetes | awk '{print $3}'`0
[root@k8s-master01 k8s-ha-install]# echo ${COREDNS_SERVICE_IP}
10.96.0.10

[root@k8s-master01 k8s-ha-install]# sed -i "s#KUBEDNS_SERVICE_IP#${COREDNS_SERVICE_IP}#g" CoreDNS/coredns.yaml

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

10、安装Metrics Server

说明:在新版的Kubernetes中系统资源的采集均使用Metrics-server,可以通过Metrics采集节点和Pod的内存、磁盘、CPU和网络的使用率。

# 安装metrics server
[root@k8s-master01 k8s-ha-install]# cd /root/k8s-ha-install/metrics-server
[root@k8s-master01 metrics-server]# ls
comp.yaml

[root@k8s-master01 metrics-server]# kubectl create -f .

[root@k8s-master01 metrics-server]# kubectl get nodes
NAME           STATUS   ROLES    AGE   VERSION
k8s-master01   Ready    <none>   23m   v1.25.4
k8s-master02   Ready    <none>   22m   v1.25.4
k8s-master03   Ready    <none>   65s   v1.25.4
k8s-node01     Ready    <none>   22m   v1.25.4
k8s-node02     Ready    <none>   21m   v1.25.4

11、集群验证

安装busybox
[root@k8s-master01 metrics-server]# cat<<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - name: busybox
    image: registry.cn-beijing.aliyuncs.com/dotbalo/redis-trib:4.0.10
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  restartPolicy: Always
EOF
[root@k8s-master01 metrics-server]# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
busybox   1/1     Running   0          29s

1.	Pod必须能解析Service
2.	Pod必须能解析跨namespace的Service
3.	每个节点都必须要能访问Kubernetes的kubernetes svc 443和kube-dns的service 53
4.	Pod和Pod之前要能通
a)	同namespace能通信
b)	跨namespace能通信
c)	跨机器能通信

12、安装dashboard

[root@k8s-master01 kubernetes]# cd /root/k8s-ha-install/dashboard/
[root@k8s-master01 dashboard]# kubectl  create -f .

[root@k8s-master01 dashboard]#  kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.3/aio/deploy/recommended.yaml

# 创建管理员用户

[root@k8s-master01 dashboard]# vim admin.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding 
metadata: 
  name: admin-user
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kube-system

[root@k8s-master01 dashboard]# kubectl apply -f admin.yaml -n kube-system

# 查看token值(注意不要复制到空格):
[root@k8s-master01 dashboard]# kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')

# 将ClusterIP更改为NodePort(如果已经为NodePort忽略此步骤):
kubectl edit svc kubernetes-dashboard -n kubernetes-dashboard

根据自己的实例端口号,通过任意安装了kube-proxy的宿主机的IP+端口即可访问到dashboard:

访问Dashboard:[https://192.168.100.156:31703/(请更改31703为自己的端口),选择登录方式为令牌(即token方式)

13、命令补全

[root@k8s-master01 dashboard]# yum install bash-completion -y
[root@k8s-master01 dashboard]# source /usr/share/bash-completion/bash_completion
[root@k8s-master01 dashboard]# source <(kubectl completion bash)
[root@k8s-master01 dashboard]# echo "source <(kubectl completion bash)" >> ~/.bashrc
posted @ 2022-11-17 16:14  大雨转暴雨  阅读(282)  评论(0编辑  收藏  举报