K8S生产级高可用部署
K8S生产级高可用部署
1 部署环境
OS:Ubuntu 24.04.4 LTS
2 部署组件
3 部署准备
3.1 节点规划
| 主机名 | IP | 类型 | 可运行服务/组件 |
| master01 | 10.32.0.101 | k8s master节点 | kubeadm、kubelet、kubectl、KeepAlived、containerd etcd、kube-apiserver、kube-scheduler、kube-controller-manager、calico dashboard、metrics、ingress、Longhorn ui节点、Prometheus+Grafana节点 KubeSphere节点 |
| master02 | 10.32.0.102 | k8s master节点 | kubeadm、kubelet、kubectl、KeepAlived、containerd etcd、kube-apiserver、kube-scheduler、kube-controller-manager、calico dashboard、metrics、ingress、Longhorn ui节点、Prometheus+Grafana节点 KubeSphere节点 |
| master03 | 10.32.0.104 | k8s master节点 | kubeadm、kubelet、kubectl、KeepAlived、containerd etcd、kube-apiserver、kube-scheduler、kube-controller-manager、calico dashboard、metrics、ingress、Longhorn ui节点、Prometheus+Grafana节点 KubeSphere节点 |
| worker01 | 10.32.0.105 | k8s worker节点 | kubelet、containerd、calico、metrics、Longhorn driver节点 Prometheus+Grafana节点、KubeSphere节点 |
| worker02 | 10.32.0.111 | k8s worker节点 | kubelet、containerd、calico、metrics、Longhorn driver节点 Prometheus+Grafana节点、KubeSphere节点 |
| worker03 | 10.32.0.109 | k8s worker节点 | kubelet、containerd、calico、metrics、Longhorn driver节点 Prometheus+Grafana节点、KubeSphere节点 |
| VIP | 10.32.0.112 |
kubernetes集群高可用主要指的是控制平面的高可用,多个master节点组件(通常为奇数)和Etcd组件的高可用,worker节点同通过前端负责均衡VIP(10.32.0.112)连接到Master。

Kubernetes高可用架构中etcd与Master节点组件混合部署方式特点:
- 所需服务器节点资源少,具备超融合架构特点
- 部署简单,利于管理
- 容易进行横向拓展
- etcd复用Kubernetes的高可用
- 镩子一定风险,如果一台master主机挂了,master和etcd都少了一个节点,集群冗余度受到一定影响。
本文使用Keepalived+HAProxy架构实现Kubernetes的高可用。
3.2 主机名设置
对所有节点进行主机名配置:
user@user:~$ sudo hostnamectl set-hostname master01 #其他节点依次修改
生成环境通常建议在内网部署dns服务器,使用dns服务器进行解析,本文使用本地hosts文件进行解析。
如下hosts文件修改仅需在master01执行,后续使用批量分发至k8s集群所有节点:
sudo tee -a /etc/hosts > /dev/null << EOF 10.32.0.101 master01 10.32.0.102 master02 10.32.0.104 master03 10.32.0.105 worker01 10.32.0.111 worker02 10.32.0.109 worker03 EOF
3.3 变量准备
为实现自动化部署,自动化分发相关文件,提前定义相关主机名、IP组变量。
user@master01:~# vim var.sh #确认相关主机名和IP #!/bin/bash #***************************************************************# # ScriptName: var.sh #***************************************************************# # 集群 MASTER 机器 IP 数组 export MASTER_IPS=(10.32.0.101 10.32.0.102 10.32.0.104) # 集群 MASTER IP 对应的主机名数组 export MASTER_NAMES=(master01 master02 master03) # 集群 NODE 机器 IP 数组 export NODE_IPS=(10.32.0.105 10.32.0.111 10.32.0.109) # 集群 NODE IP 对应的主机名数组 export NODE_NAMES=(worker01 worker02 worker03) # 集群所有机器 IP 数组 export ALL_IPS=(10.32.0.101 10.32.0.102 10.32.0.104 10.32.0.105 10.32.0.111 10.32.0.109) # 集群所有IP 对应的主机名数组 export ALL_NAMES=(master01 master02 master03 worker01 worker02 worker03)
3.4 互信配置
为了方便远程分发文件和执行命令,本文配置master01节点至其它节点的ssh信任关系,即免密钥管理所有其它节点。注意:下列操作仅需在master01节点上执行。
user@master01:~$ source var.sh #载入变量 user@master01:~$ ssh-keygen -f ~/.ssh/id_rsa -N '' user@master01:~$ for all_ip in ${ALL_IPS[@]} do echo -e "\n\n\033[33m[INFO] >>> ${all_ip}...\033[0m" ssh-copy-id -i ~/.ssh/id_rsa.pub user@${all_ip} done user@master01:~$ for all_name in ${ALL_NAMES[@]} do echo -e "\n\n\033[33m[INFO] >>> ${all_name}...\033[0m" ssh-copy-id -i ~/.ssh/id_rsa.pub user@${all_name} done
解决root权限问题
- maser01节点执行
ssh-keygen -t ed25519 # 一路回车 for ip in ${ALL_IPS[@]}; do ssh-copy-id user@$ip; done
- 每台节点配置sudo免密(关键,每台都执行一次)
echo "user ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/user sudo chmod 440 /etc/sudoers.d/user
3.5 环境预配置
kubeadm本身仅用于部署Kubernetes集群,在正式使用kubeadm部署Kubernetes集群之前,需要对操作系统环境进行准备,即环境预配置。本文使用脚本自动完成。主要功能包括:
- 安装containerd、Kubernetes平台底层的容器组件
- 关闭SELinux及防火墙
- 优化相关内核参数,针对生成环境Kubernetes集群的基础系统调优配置。
- 关闭swap
- 设置相关模块,主要为转发模块。
- 创建container所使用的独立目录
- 配置crictl和运行时连接,便于后期使用crictl命令
提示:后续ctr命令下载镜像的时候,若需要使用containerd的加速,必须带上--hosts-dir,ctr当前环境所管理的镜像都属于k8s.io,因此创建一个别名。
user@master01:~# vim k8s-pre-set.sh #!/bin/bash #***************************************************************# # ScriptName: k8s-pre-set.sh #***************************************************************# # Initialize the machine. This needs to be executed on every machine. apt update && apt upgrade -y && apt autoremove -y # Install package sudo apt -y install conntrack ntpdate ntp ipvsadm ipset jq iptables sysstat wget # Add Docker's official GPG key sudo apt -y install ca-certificates curl gnupg sudo install -m 0755 -d /etc/apt/keyrings sudo curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg sudo chmod a+r /etc/apt/keyrings/docker.gpg # Add the repository to Apt sources: echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \ "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt update # Install and config containerd apt-cache madison containerd sudo apt -y install containerd.io sleep 3s mkdir -p /etc/containerd/certs.d/docker.io mkdir -p /data/containerd cat > /etc/containerd/config.toml <<EOF disabled_plugins = ["io.containerd.internal.v1.restart"] root = "/data/containerd" version = 2 [plugins] [plugins."io.containerd.grpc.v1.cri"] # sandbox_image = "registry.k8s.io/pause:3.10" sandbox_image = "registry.aliyuncs.com/google_containers/pause:3.10" [plugins."io.containerd.grpc.v1.cri".containerd] [plugins."io.containerd.grpc.v1.cri".containerd.runtimes] [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc] runtime_type = "io.containerd.runc.v2" [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options] SystemdCgroup = true [plugins."io.containerd.grpc.v1.cri".registry] config_path = "/etc/containerd/certs.d" [plugins."io.containerd.runtime.v1.linux"] shim_debug = true EOF cat > /etc/containerd/certs.d/docker.io/hosts.toml <<EOF server = "https://registry-1.docker.io" [host."https://docker.1ms.run"] capabilities = ["pull", "resolve", "push"] [host."https://dbzucv6w.mirror.aliyuncs.com"] capabilities = ["pull", "resolve", "push"] [host."https://docker.xuanyuan.me"] capabilities = ["pull", "resolve", "push"] EOF # config crictl & containerd cat > /etc/crictl.yaml <<EOF runtime-endpoint: unix:///run/containerd/containerd.sock image-endpoint: unix:///run/containerd/containerd.sock timeout: 10 debug: false EOF echo 'alias ctrpull="ctr -n k8s.io images pull --hosts-dir /etc/containerd/certs.d"' >> /etc/profile.d/custom_bash.sh systemctl restart containerd systemctl enable containerd --now # Turn off and disable the firewalld. systemctl disable ufw --now || true # Modify related kernel parameters & Disable the swap. cat > /etc/sysctl.d/k8s.conf << EOF net.ipv4.ip_forward = 1 net.bridge.bridge-nf-call-ip6tables = 1 net.bridge.bridge-nf-call-iptables = 1 net.ipv4.tcp_tw_recycle = 0 vm.swappiness = 0 vm.overcommit_memory = 1 vm.panic_on_oom = 0 net.ipv6.conf.all.disable_ipv6 = 1 EOF sysctl -p /etc/sysctl.d/k8s.conf >&/dev/null swapoff -a sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab modprobe br_netfilter modprobe overlay sysctl --system # Add ipvs modules cat > /etc/modules-load.d/ipvs.conf <<EOF ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh nf_conntrack br_netfilter overlay EOF systemctl restart systemd-modules-load.service
初始化所有节点:
user@master01:~# source var.sh user@master01:~# chmod +x *.sh user@master01:~# for all_ip in ${ALL_IPS[@]}; do echo -e "\n\n\033[33m[INFO] >>> ${all_ip}...\033[0m" cat /etc/hosts | ssh user@${all_ip} "sudo tee /etc/hosts > /dev/null" # 脚本拷到家目录(user 有权限) scp -rp k8s-pre-set.sh user@${all_ip}:/home/user/ # 用 sudo 运行脚本,脚本里的 sudo 就都能过了 ssh user@${all_ip} "sudo bash /home/user/k8s-pre-set.sh" done
注:本节所有操作均在master01节点上执行。初始化完毕后重启所有节点。
4 部署高可用组件
4.1 HAProxy安装
HAProxy是提供高可用性、负载均衡以及基于TCP(从而可以反向代理kubeapiserver等应用)和HTTP应用的代理,支持虚拟,是一个开源、免费、快速并可靠的一种高可用解决方案。
user@master01:~# HAVERSION=3.1.6 user@master01:~# LHAVERSION=$(echo ${HAVERSION} | cut -d. -f1,2) user@master01:~# wget https://mirrors.huaweicloud.com/haproxy/${LHAVERSION}/src/haproxy-${HAVERSION}.tar.gz user@master01:~# for master_ip in "${MASTER_IPS[@]}"; do echo -e "\n\n\033[33m[INFO] >>> ${master_ip}...\033[0m" ssh -o ServerAliveInterval=60 user@${master_ip} " set -e sudo apt-get -y install binutils gcc make wget libssl-dev libpcre2-dev zlib1g-dev cd /home/user rm -rf haproxy-${HAVERSION} tar -zxf haproxy-${HAVERSION}.tar.gz cd haproxy-${HAVERSION} make clean make -j\$(nproc) TARGET=linux-glibc USE_OPENSSL=1 USE_PCRE2=1 USE_ZLIB=1 USE_SYSTEMD=1 sudo make install PREFIX=/usr/local/haproxy sudo cp /usr/local/haproxy/sbin/haproxy /usr/sbin/ id haproxy &>/dev/null || sudo useradd -r -s /usr/sbin/nologin haproxy sudo mkdir -p /etc/haproxy/conf.d sudo cp -r examples/errorfiles/ /usr/local/haproxy/ haproxy -v " done
注:上述操作仅需要在master01节点上执行,在ubuntu24.04上需要明确指定USE_PCRE2 ,使用libssl-dev和libpcre2-dev相关库文件
4.2 KeepAlived安装
KeepAlived是一个基于VRRP协议来实现LVS服务高可用方案,可用解决静态路由出现的单点故障问题。本文中3台master节点均部署并运行KeepAlived,一台为主服务器(MASTER),另外两台为备份服务器(BACKUP)。
Master集群对外表现为一个VIP,主服务器会发送特定小学给备份服务器,当备份服务器收不到这个消息的时候,即主服务器宕机的时候,备份服务器就会接管虚拟IP,继续提供服务器,从而保证了高可用性。
user@master01:~# KPVERSION=2.3.2 user@master01:~# LKPVERSION=$(echo ${HAVERSION} | cut -d. -f1,2) user@master01:~# wget https://www.keepalived.org/software/keepalived-${KPVERSION}.tar.gz user@master01:~# for master_ip in "${MASTER_IPS[@]}"; do echo -e "\n\n\033[33m[INFO] >>> ${master_ip}...\033[0m" scp -p keepalived-${KPVERSION}.tar.gz user@${master_ip}:/home/user/ || continue ssh -o ServerAliveInterval=60 user@${master_ip} " set -e test -f /home/user/keepalived-${KPVERSION}.tar.gz || { echo '包不在位,退出'; exit 1; } sudo apt-get -y install curl gcc make libssl-dev libnl-3-dev libnl-genl-3-dev cd /home/user rm -rf keepalived-${KPVERSION} tar -zxf keepalived-${KPVERSION}.tar.gz cd keepalived-${KPVERSION} ./configure --sysconf=/etc --prefix=/usr/local/keepalived make -j\$(nproc) sudo make install sudo cp -a keepalived/keepalived.service /usr/lib/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable keepalived /usr/local/keepalived/sbin/keepalived --version | head -1 " done
注:上述操作仅需要在master01节点上执行。
4.3 创建配置文件
创建集群所需要的相关配置文件,采用脚本自动化创建相关配置文件。
user@master01:~# vim k8scfg.sh
#!/bin/bash #***************************************************************# # ScriptName: uk8cfg.sh #***************************************************************# ####################################### # 全局变量配置区 ####################################### echo -e "\n\033[33m[INFO] 开始定义全局参数...\033[0m" sleep 1 declare -A NODES=( [master01]="10.32.0.101" [master02]="10.32.0.102" [master03]="10.32.0.104" ) # 公共参数 K8SHA_VERSION=v1.32.3 K8SHA_VIP="10.32.0.112" K8SHA_PORT="6443" K8SHA_AUTH="ilovek8s" K8SHA_PODCIDR="10.10.0.0/16" K8SHA_SVCCIDR="10.20.0.0/16" K8SHA_DNSIP="10.20.0.10" K8SHA_NETINF="ens160" K8SHA_KA_RID="51" # VRRP Virtual Router ID(1-255,同一二层网络内唯一即可) K8SHA_VIP_MASK="23" # VIP 掩码长度,须与节点网卡实际掩码一致(ip addr 确认) # 修复3-1:KeepAlived 优先级分配顺序 # 关联数组遍历顺序是随机的,必须用有序数组保证优先级分配稳定: # 按此顺序依次分配 120、121、122...,越靠前优先级越高(master01 默认最高) K8SHA_NODE_ORDER=(master01 master02 master03) echo -e "\n\033[32m[SUCCESS] 全局参数定义已完成...\033[0m" set -euo pipefail # 启用严格模式 ####################################### # 函数定义区 ####################################### # 创建目录结构 init_dirs() { echo -e "\n\033[33m[INFO] 开始创建目录结构...\033[0m" sleep 1 # 残留检查:上次若用 sudo 运行,k8sdir 属主会是 root,本次写入必失败 if [[ -d k8sdir && ! -w k8sdir ]]; then echo -e "\n\033[31m[ERROR] k8sdir 属主是 root(上次 sudo 运行残留),本脚本应以普通用户运行。" echo -e "[ERROR] 请执行: sudo rm -rf k8sdir 后重跑\033[0m" exit 1 fi for node in "${!NODES[@]}"; do mkdir -p k8sdir/${node}/{keepalived,haproxy} done mkdir -p k8sdir/{keepalived,haproxy,init} echo -e "\n\033[32m[SUCCESS] 目录结构创建已完成...\033[0m" } # 下载基础配置文件 download_templates() { echo -e "\n\033[33m[INFO] 开始下载模板文件...\033[0m" sleep 1 # Keepalived模板(|| true:不让 wget 的非零返回码触发 set -e 静默退出,由下面的落地校验统一兜底) wget -qcP k8sdir/keepalived/ http://down.linuxsb.com/mydeploy/k8s/common/{uk8s-keepalived.conf.tpl,uk8s-check-apiserver.sh} || true # HAProxy模板 wget -qcP k8sdir/haproxy/ http://down.linuxsb.com/mydeploy/k8s/common/{uk8s-haproxy.cfg.tpl,k8s-haproxy.service} || true # k8s配置模板 wget -qcP k8sdir/init/ http://down.linuxsb.com/mydeploy/k8s/${K8SHA_VERSION}/ukubeadm-config.yaml.tpl || true # 修复3-3:模板落地校验——外部站点挂了/版本路径不存在时,给出明确报错再退出 local required=( "k8sdir/keepalived/uk8s-keepalived.conf.tpl" "k8sdir/keepalived/uk8s-check-apiserver.sh" "k8sdir/haproxy/uk8s-haproxy.cfg.tpl" "k8sdir/haproxy/k8s-haproxy.service" "k8sdir/init/ukubeadm-config.yaml.tpl" ) for f in "${required[@]}"; do if [[ ! -s "$f" ]]; then echo -e "\n\033[31m[ERROR] 模板缺失或为空: $f" echo -e "[ERROR] 请检查 down.linuxsb.com 可达性,以及版本路径是否正确: ${K8SHA_VERSION}\033[0m" exit 1 fi done echo -e "\n\033[32m[SUCCESS] 模板文件下载已完成...\033[0m" } # 生成HAProxy配置 gen_haproxy_conf() { echo -e "\n\033[33m[INFO] 生成 HAProxy 配置...\033[0m" sleep 1 local backend_servers="" for node_ip in "${NODES[@]}"; do backend_servers+=" server ${node_ip} ${node_ip}:${K8SHA_PORT} check\n" done # 使用临时文件处理多行替换 local tmpfile=$(mktemp) echo -e "$backend_servers" > "$tmpfile" # 替换模板中的占位符 sed -e "/BACKSERVER/ { r $tmpfile d }" "k8sdir/haproxy/uk8s-haproxy.cfg.tpl" > "k8sdir/haproxy/haproxy.cfg" rm -f "$tmpfile" echo -e "\n\033[32m[SUCCESS] HAProxy 配置已完成...\033[0m" } # 生成Keepalived配置 gen_keepalived_conf() { echo -e "\n\033[33m[INFO] 开始生成 KeepAlived 配置...\033[0m" sleep 1 local priority=120 # 修复3-1:改用有序数组遍历,保证优先级分配稳定(关联数组顺序随机) for node in "${K8SHA_NODE_ORDER[@]}"; do [[ -v "NODES[$node]" ]] || { echo -e "\n\033[31m[ERROR] $node 不在 NODES 中,检查 K8SHA_NODE_ORDER 定义\033[0m"; exit 1; } sed -e " s/K8SHA_VIP_ADDRESS/${K8SHA_VIP}/g s/K8SHA_VIP_MASK/${K8SHA_VIP_MASK}/g s/K8SHA_KA_RID/${K8SHA_KA_RID}/g s/K8SHA_VIP/${K8SHA_VIP}/g s/K8SHA_KA_STATE/BACKUP/g s/K8SHA_KA_INTF/${K8SHA_NETINF}/g s/K8SHA_IPLOCAL/${NODES[$node]}/g s/K8SHA_KA_PRIO/$((priority++))/g s/K8SHA_KA_AUTH/${K8SHA_AUTH}/g " k8sdir/keepalived/uk8s-keepalived.conf.tpl > "k8sdir/${node}/keepalived/keepalived.conf" cp k8sdir/keepalived/uk8s-check-apiserver.sh "k8sdir/${node}/keepalived/check_apiserver.sh" done echo -e "\n\033[32m[SUCCESS] KeepAlived 配置已完成...\033[0m" } # 生成k8s配置文件 gen_k8s_config() { echo -e "\n\033[33m[INFO] 开始生成 K8S 配置...\033[0m" sleep 1 # 生成动态 SAN 条目到临时文件 tmp_sans=$(mktemp) { # 添加所有节点名称和 IP for node in "${!NODES[@]}"; do echo " - $node" echo " - ${NODES[$node]}" done } > "$tmp_sans" # 生成动态 SAN 条目到临时文件 # 修复3-2:kubeadm 配置对所有节点是同一份(SAN 已含全部节点), # 原脚本循环三次只是把同一文件覆盖三遍,改为只生成一次。 # 顺手补上 K8SHA_DNSIP 占位符替换(若模板中存在则生效,不存在则 sed 不匹配、无副作用)。 sed -e " s|K8SHA_SVCCIDR|${K8SHA_SVCCIDR}|g s|K8SHA_PODCIDR|${K8SHA_PODCIDR}|g s|K8SHA_VERSION|${K8SHA_VERSION}|g s|K8SHA_VIP|${K8SHA_VIP}|g s|K8SHA_DNSIP|${K8SHA_DNSIP}|g /#DYNAMIC_SANS#/ { r $tmp_sans d } " k8sdir/init/ukubeadm-config.yaml.tpl > "k8sdir/init/kubeadm-config.yaml" rm -rf ${tmp_sans} echo -e "\n\033[32m[SUCCESS] K8S 配置已完成...\033[0m" } # 分发配置文件 # 【改动说明】原 scp 直写远端 /etc、/usr/lib/systemd 会 Permission denied, # 改为 stdin + sudo tee 落地;check_apiserver.sh 落地后补执行权限。 distribute_files() { echo -e "\n\033[33m[INFO] 分发配置文件...\033[0m" sleep 1 for node in "${!NODES[@]}"; do echo "正在处理节点: $node" # HAProxy 配置(本地留存一份 + 远端 sudo 落地) cp k8sdir/haproxy/haproxy.cfg k8sdir/${node}/haproxy/ ssh user@$node "sudo tee /etc/haproxy/haproxy.cfg > /dev/null" < k8sdir/haproxy/haproxy.cfg cp k8sdir/haproxy/k8s-haproxy.service k8sdir/${node}/haproxy/ ssh user@$node "sudo tee /usr/lib/systemd/system/haproxy.service > /dev/null" < k8sdir/haproxy/k8s-haproxy.service # Keepalived 配置与检查脚本 for f in k8sdir/$node/keepalived/*; do ssh user@$node "sudo tee /etc/keepalived/$(basename $f) > /dev/null" < "$f" done # 健康检查脚本必须有执行权限,否则 track_script 失败、VIP 漂移异常 ssh user@$node "sudo chmod +x /etc/keepalived/check_apiserver.sh" done echo -e "\n\033[32m[SUCCESS] 配置分发已完成...\033[0m" } ####################################### # 主执行流程 ####################################### main() { init_dirs download_templates gen_keepalived_conf gen_k8s_config gen_haproxy_conf distribute_files # 设置执行权限 chmod u+x *.sh echo -e "\n\033[32m[SUCCESS] 所有配置已完成...\033[0m" sleep 1 } main "$@"
执行
sudo chmod +x k8scfg.sh
./k8scfg.sh
注:上述操作仅需要在master01节点上执行。
该配置文件产生配置文件清单:
- kubeadm-config.yaml:kubeadm初始化文件,位于kubeadm/目录
- keepalived:keepalived配置文件,位于各master节点的/etc/keepalived目录
- haprox:haproxy配置文件,位于各个master节点的/etc/haprox目录
- calico.yaml:calico网络组件部署文件,位于kubeadm/calico目录
4.4 启动服务
启动keepalived和HAProx服务,从而构建master节点高可用。
- 检查服务配置:确认所有master节点相关keepalived配置文件和keepalived检测脚本文件。
user@master01:~$ source var.sh user@master01:~$ for master_ip in ${MASTER_IPS[@]} do echo -e "\n\n\033[33m[INFO] >>> ${master_ip}...\033[0m" ssh user@${master_ip} "cat /etc/keepalived/keepalived.conf" ssh user@${master_ip} "cat /etc/keepalived/check_apiserver.sh" done
- 启动高可用服务
user@master01:~$ source var.sh user@master01:~$ for master_ip in "${MASTER_IPS[@]}"; do echo -e "\n\n\033[33m[INFO] >>> ${master_ip}...\033[0m" ssh user@${master_ip} "sudo systemctl enable --now haproxy" ssh user@${master_ip} "sudo systemctl enable --now keepalived" ssh user@${master_ip} "systemctl is-active haproxy keepalived" done user@master01:~$ for all_ip in ${ALL_IPS[@]} do sleep 2 echo -e "\n\n\033[33m[INFO] >>> ${all_ip}...\033[0m" ssh user@${all_ip} "ping -c1 10.32.0.112" done
注:上述操作仅需要在master01节点上执行。
5 集群部署
5.1 相关组件
需要在每台机器上安装一下软件:
- kubeadm:初始化集群指令
- kubelet:在集群的每个节点上用来启动pod和container等
- kubectl:用来与集群通信的命令行工具
5.2 正式安装
快速安装所有节点的kubeadm、kubelet、kubectl组件:
user@master01:~$ for all_ip in ${ALL_IPS[@]}; do echo -e "\n\n\033[33m[INFO] >>> ${all_ip}...\033[0m" ssh user@${all_ip} "curl -fsSL https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.32/deb/Release.key | sudo gpg --dearmor --yes -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg" ssh user@${all_ip} "cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.32/deb/ / EOF" ssh user@${all_ip} "sudo apt update && sudo apt -y install kubelet=1.32.3-1.1 kubectl=1.32.3-1.1 kubeadm=1.32.3-1.1 --allow-downgrades" ssh user@${all_ip} "sudo systemctl enable kubelet" # ← 加 sudo done user@master01:~$ apt-cache madison kubelet #查看相应版本
注:上述操作在master01节点执行。
6 集群初始化
6.1 预配置检查
使用k8scfg.sh创建配置的时候,会创建如下配置文件,集群初始化之前建议再次检查和确认配置文件。
user@master01:~$ cat k8sdir/init/kubeadm-config.yaml --- apiVersion: kubeadm.k8s.io/v1beta3 kind: ClusterConfiguration etcd: local: dataDir: "/data/etcd" networking: serviceSubnet: "10.20.0.0/16" podSubnet: "10.10.0.0/16" dnsDomain: "cluster.local" kubernetesVersion: "v1.32.3" controlPlaneEndpoint: "10.32.0.112:16443" imageRepository: registry.aliyuncs.com/google_containers apiServer: certSANs: - localhost - 127.0.0.1 - 10.32.0.112 - master03 - 10.32.0.104 - master02 - 10.32.0.102 - master01 - 10.32.0.101 extraArgs: service-node-port-range: "80-65535" default-not-ready-toleration-seconds: "180" default-unreachable-toleration-seconds: "180" controllerManager: extraArgs: node-monitor-period: "3s" node-monitor-grace-period: "30s" certificatesDir: "/etc/kubernetes/pki" #clusterName: "example-cluster" --- apiVersion: kubelet.config.k8s.io/v1beta1 kind: KubeletConfiguration cgroupDriver: systemd imageGCHighThresholdPercent: 95 imageGCLowThresholdPercent: 90 --- apiVersion: kubeproxy.config.k8s.io/v1alpha1 kind: KubeProxyConfiguration mode: ipvs
k8s默认的端口范围为30000~32767,为便于后期大量的应用,建议做端口扩展,如ingress的80、443端口,然后开发80-65535端口号。同时开放更多端口后,使用的时候需要注意外部应用端口和k8s使用的nodeport端口冲突的情况。
默认的kubeadm配置可用使用kubeadm config print init-default > config.yaml生成。
6.2 master01上初始化
在master01节点上执行初始化,即可完成单节点的kubernetes,其他节点采用添加的方式部署。
先查一下各节点swap是否关闭,没关闭则关闭
for all_ip in ${ALL_IPS[@]}; do echo -e "\n\033[33m[INFO] >>> ${all_ip}...\033[0m" ssh user@${all_ip} " sudo swapoff -a sudo sed -i '/swap/s/^[^#]/#&/' /etc/fstab echo '--- fstab ---'; grep swap /etc/fstab || echo '已无 swap 条目' echo '--- 运行时 ---'; free -h | grep -i swap " done
提示:kubeadm init过程会执行系统预检查,预检查通过则继续init。
sudo kubeadm init --config=k8sdir/init/kubeadm-config.yaml --upload-certs
输出:
W1203 01:28:22.713250 111130 common.go:101] your configuration file uses a deprecated API spec: "kubeadm.k8s.io/v1beta3" (kind: "ClusterConfiguration"). Please use 'kubeadm config migrate --old-config old.yaml --new-config new.yaml', which will write the new, similar spec using a newer API version. [init] Using Kubernetes version: v1.32.3 [preflight] Running pre-flight checks [preflight] Pulling images required for setting up a Kubernetes cluster [preflight] This might take a minute or two, depending on the speed of your internet connection [preflight] You can also perform this action beforehand using 'kubeadm config images pull' W1203 01:28:22.820946 111130 checks.go:846] detected that the sandbox image "" of the container runtime is inconsistent with that used by kubeadm.It is recommended to use "registry.aliyuncs.com/google_containers/pause:3.10" as the CRI sandbox image. [certs] Using certificateDir folder "/etc/kubernetes/pki" [certs] Generating "ca" certificate and key [certs] Generating "apiserver" certificate and key [certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local localhost master01 master02 master03] and IPs [10.20.0.1 10.32.0.101 10.32.0.112 127.0.0.1 10.32.0.104 10.32.0.102] [certs] Generating "apiserver-kubelet-client" certificate and key [certs] Generating "front-proxy-ca" certificate and key [certs] Generating "front-proxy-client" certificate and key [certs] Generating "etcd/ca" certificate and key [certs] Generating "etcd/server" certificate and key [certs] etcd/server serving cert is signed for DNS names [localhost master01] and IPs [10.32.0.101 127.0.0.1 ::1] [certs] Generating "etcd/peer" certificate and key [certs] etcd/peer serving cert is signed for DNS names [localhost master01] and IPs [10.32.0.101 127.0.0.1 ::1] [certs] Generating "etcd/healthcheck-client" certificate and key [certs] Generating "apiserver-etcd-client" certificate and key [certs] Generating "sa" key and public key [kubeconfig] Using kubeconfig folder "/etc/kubernetes" W1203 01:28:25.356861 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "admin.conf" kubeconfig file W1203 01:28:25.685572 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "super-admin.conf" kubeconfig file W1203 01:28:25.867565 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "kubelet.conf" kubeconfig file W1203 01:28:26.044016 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "controller-manager.conf" kubeconfig file W1203 01:28:26.422885 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "scheduler.conf" kubeconfig file [etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests" [control-plane] Using manifest folder "/etc/kubernetes/manifests" [control-plane] Creating static Pod manifest for "kube-apiserver" [control-plane] Creating static Pod manifest for "kube-controller-manager" [control-plane] Creating static Pod manifest for "kube-scheduler" [kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env" [kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml" [kubelet-start] Starting the kubelet [wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests" [kubelet-check] Waiting for a healthy kubelet at http://127.0.0.1:10248/healthz. This can take up to 4m0s [kubelet-check] The kubelet is healthy after 503.065406ms [api-check] Waiting for a healthy API server. This can take up to 4m0s [api-check] The API server is healthy after 6.023042795s [upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace [kubelet] Creating a ConfigMap "kubelet-config" in namespace kube-system with the configuration for the kubelets in the cluster [upload-certs] Storing the certificates in Secret "kubeadm-certs" in the "kube-system" Namespace [upload-certs] Using certificate key: 8bc2514c0a07b304c4356c2e0a6fc9fe99cc15812ae0b733fe54e1f1c58a411e [mark-control-plane] Marking the node master01 as control-plane by adding the labels: [node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers] [mark-control-plane] Marking the node master01 as control-plane by adding the taints [node-role.kubernetes.io/control-plane:NoSchedule] [bootstrap-token] Using token: o8gn9i.iyukn96pakybytnf [bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles [bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes [bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials [bootstrap-token] Configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token [bootstrap-token] Configured RBAC rules to allow certificate rotation for all node client certificates in the cluster [bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace [kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key [addons] Applied essential addon: CoreDNS W1203 01:28:34.980017 111130 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [addons] Applied essential addon: kube-proxy Your Kubernetes control-plane has initialized successfully! To start using your cluster, you need to run the following as a regular user: mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config Alternatively, if you are the root user, you can run: export KUBECONFIG=/etc/kubernetes/admin.conf You should now deploy a pod network to the cluster. Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at: https://kubernetes.io/docs/concepts/cluster-administration/addons/ You can now join any number of control-plane nodes running the following command on each as root: kubeadm join 10.32.0.112:16443 --token o8gn9i.iyukn96pakybytnf \ --discovery-token-ca-cert-hash sha256:5e9fed82f6e728016a13e72e35e25158ccbdae3adf9890ccc17fc92ac012303e \ --control-plane --certificate-key 8bc2514c0a07b304c4356c2e0a6fc9fe99cc15812ae0b733fe54e1f1c58a411e Please note that the certificate-key gives access to cluster sensitive data, keep it secret! As a safeguard, uploaded-certs will be deleted in two hours; If necessary, you can use "kubeadm init phase upload-certs --upload-certs" to reload certs afterward. Then you can join any number of worker nodes by running the following on each as root: kubeadm join 10.32.0.112:16443 --token o8gn9i.iyukn96pakybytnf \ --discovery-token-ca-cert-hash sha256:5e9fed82f6e728016a13e72e35e25158ccbdae3adf9890ccc17fc92ac012303e
注:上述token默认24小时有效,token和hash可用通过如下方式获取:
kubeadm token list
如果token过期,可用用一下命令生成新的token:
kubeadm token create openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
如果初始化异常可用执行:
sudo kubeadm reset -f sudo rm -rf /etc/kubernetes/manifests /var/lib/etcd /var/lib/kubelet/*.conf sudo systemctl restart containerd kubelet sudo kubeadm init --config=k8sdir/init/kubeadm-config.yaml --upload-certs
6.3 添加Master节点
使用kubeadm join将其他Master节点添加至集群
user@master01:~# for ip in 10.32.0.102 10.32.0.104; do echo -e "\n\033[33m[INFO] >>> $ip...\033[0m"; ssh user@$ip "sudo kubeadm join 10.32.0.112:16443 --token o8gn9i.iyukn96pakybytnf --discovery-token-ca-cert-hash sha256:5e9fed82f6e728016a13e72e35e25158ccbdae3adf9890ccc17fc92ac012303e --control-plane --certificate-key 8bc2514c0a07b304c4356c2e0a6fc9fe99cc15812ae0b733fe54e1f1c58a411e"; done
输出
[INFO] >>> 10.32.0.102... [preflight] Running pre-flight checks [preflight] Reading configuration from the "kubeadm-config" ConfigMap in namespace "kube-system"... [preflight] Use 'kubeadm init phase upload-config --config your-config.yaml' to re-upload it. [preflight] Running pre-flight checks before initializing the new control plane instance [preflight] Pulling images required for setting up a Kubernetes cluster [preflight] This might take a minute or two, depending on the speed of your internet connection [preflight] You can also perform this action beforehand using 'kubeadm config images pull' W1203 01:44:51.372284 103724 checks.go:846] detected that the sandbox image "" of the container runtime is inconsistent with that used by kubeadm.It is recommended to use "registry.aliyuncs.com/google_containers/pause:3.10" as the CRI sandbox image. [download-certs] Downloading the certificates in Secret "kubeadm-certs" in the "kube-system" Namespace [download-certs] Saving the certificates to the folder: "/etc/kubernetes/pki" [certs] Using certificateDir folder "/etc/kubernetes/pki" [certs] Generating "front-proxy-client" certificate and key [certs] Generating "etcd/healthcheck-client" certificate and key [certs] Generating "etcd/peer" certificate and key [certs] etcd/peer serving cert is signed for DNS names [localhost master02] and IPs [10.32.0.102 127.0.0.1 ::1] [certs] Generating "apiserver-etcd-client" certificate and key [certs] Generating "etcd/server" certificate and key [certs] etcd/server serving cert is signed for DNS names [localhost master02] and IPs [10.32.0.102 127.0.0.1 ::1] [certs] Generating "apiserver" certificate and key [certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local localhost master01 master02 master03] and IPs [10.20.0.1 10.32.0.102 10.32.0.112 127.0.0.1 10.32.0.104 10.32.0.101] [certs] Generating "apiserver-kubelet-client" certificate and key [certs] Valid certificates and keys now exist in "/etc/kubernetes/pki" [certs] Using the existing "sa" key [kubeconfig] Generating kubeconfig files [kubeconfig] Using kubeconfig folder "/etc/kubernetes" W1203 01:45:13.660342 103724 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "admin.conf" kubeconfig file W1203 01:45:13.780349 103724 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "controller-manager.conf" kubeconfig file W1203 01:45:14.011854 103724 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "scheduler.conf" kubeconfig file [control-plane] Using manifest folder "/etc/kubernetes/manifests" [control-plane] Creating static Pod manifest for "kube-apiserver" [control-plane] Creating static Pod manifest for "kube-controller-manager" [control-plane] Creating static Pod manifest for "kube-scheduler" [check-etcd] Checking that the etcd cluster is healthy [kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml" [kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env" [kubelet-start] Starting the kubelet [kubelet-check] Waiting for a healthy kubelet at http://127.0.0.1:10248/healthz. This can take up to 4m0s [kubelet-check] The kubelet is healthy after 1.000924495s [kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap [etcd] Announced new etcd member joining to the existing etcd cluster [etcd] Creating static Pod manifest for "etcd" {"level":"warn","ts":"2026-12-03T01:45:15.598393Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc00014c1e0/10.32.0.101:2379","attempt":0,"error":"rpc error: code = FailedPrecondition desc = etcdserver: can only promote a learner member which is in sync with leader"} {"level":"warn","ts":"2026-12-03T01:45:16.098427Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc00014c1e0/10.32.0.101:2379","attempt":0,"error":"rpc error: code = FailedPrecondition desc = etcdserver: can only promote a learner member which is in sync with leader"} [etcd] Waiting for the new etcd member to join the cluster. This can take up to 40s [mark-control-plane] Marking the node master02 as control-plane by adding the labels: [node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers] [mark-control-plane] Marking the node master02 as control-plane by adding the taints [node-role.kubernetes.io/control-plane:NoSchedule] This node has joined the cluster and a new control plane instance was created: * Certificate signing request was sent to apiserver and approval was received. * The Kubelet was informed of the new secure connection details. * Control plane label and taint were applied to the new node. * The Kubernetes control plane instances scaled up. * A new etcd member was added to the local/stacked etcd cluster. To start administering your cluster from this node, you need to run the following as a regular user: mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config Run 'kubectl get nodes' to see this node join the cluster. [INFO] >>> 10.32.0.104... [preflight] Running pre-flight checks [preflight] Reading configuration from the "kubeadm-config" ConfigMap in namespace "kube-system"... [preflight] Use 'kubeadm init phase upload-config --config your-config.yaml' to re-upload it. [preflight] Running pre-flight checks before initializing the new control plane instance [preflight] Pulling images required for setting up a Kubernetes cluster [preflight] This might take a minute or two, depending on the speed of your internet connection [preflight] You can also perform this action beforehand using 'kubeadm config images pull' W1203 01:45:18.139558 104698 checks.go:846] detected that the sandbox image "" of the container runtime is inconsistent with that used by kubeadm.It is recommended to use "registry.aliyuncs.com/google_containers/pause:3.10" as the CRI sandbox image. [download-certs] Downloading the certificates in Secret "kubeadm-certs" in the "kube-system" Namespace [download-certs] Saving the certificates to the folder: "/etc/kubernetes/pki" [certs] Using certificateDir folder "/etc/kubernetes/pki" [certs] Generating "apiserver" certificate and key [certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local localhost master01 master02 master03] and IPs [10.20.0.1 10.32.0.104 10.32.0.112 127.0.0.1 10.32.0.102 10.32.0.101] [certs] Generating "apiserver-kubelet-client" certificate and key [certs] Generating "front-proxy-client" certificate and key [certs] Generating "etcd/server" certificate and key [certs] etcd/server serving cert is signed for DNS names [localhost master03] and IPs [10.32.0.104 127.0.0.1 ::1] [certs] Generating "etcd/healthcheck-client" certificate and key [certs] Generating "apiserver-etcd-client" certificate and key [certs] Generating "etcd/peer" certificate and key [certs] etcd/peer serving cert is signed for DNS names [localhost master03] and IPs [10.32.0.104 127.0.0.1 ::1] [certs] Valid certificates and keys now exist in "/etc/kubernetes/pki" [certs] Using the existing "sa" key [kubeconfig] Generating kubeconfig files [kubeconfig] Using kubeconfig folder "/etc/kubernetes" W1203 01:45:41.253829 104698 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "admin.conf" kubeconfig file W1203 01:45:41.367269 104698 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "controller-manager.conf" kubeconfig file W1203 01:45:41.503184 104698 endpoint.go:57] [endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address [kubeconfig] Writing "scheduler.conf" kubeconfig file [control-plane] Using manifest folder "/etc/kubernetes/manifests" [control-plane] Creating static Pod manifest for "kube-apiserver" [control-plane] Creating static Pod manifest for "kube-controller-manager" [control-plane] Creating static Pod manifest for "kube-scheduler" [check-etcd] Checking that the etcd cluster is healthy [kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml" [kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env" [kubelet-start] Starting the kubelet [kubelet-check] Waiting for a healthy kubelet at http://127.0.0.1:10248/healthz. This can take up to 4m0s [kubelet-check] The kubelet is healthy after 1.001193554s [kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap [etcd] Announced new etcd member joining to the existing etcd cluster [etcd] Creating static Pod manifest for "etcd" {"level":"warn","ts":"2026-12-03T01:45:43.151827Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc0004b63c0/10.32.0.102:2379","attempt":0,"error":"rpc error: code = FailedPrecondition desc = etcdserver: can only promote a learner member which is in sync with leader"} {"level":"warn","ts":"2026-12-03T01:45:43.645688Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc0004b63c0/10.32.0.102:2379","attempt":0,"error":"rpc error: code = FailedPrecondition desc = etcdserver: can only promote a learner member which is in sync with leader"} {"level":"warn","ts":"2026-12-03T01:45:44.142988Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc0004b63c0/10.32.0.102:2379","attempt":0,"error":"rpc error: code = FailedPrecondition desc = etcdserver: can only promote a learner member which is in sync with leader"} {"level":"warn","ts":"2026-12-03T01:45:44.642458Z","logger":"etcd-client","caller":"v3@v3.5.16/retry_interceptor.go:63","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc0004b63c0/10.32.0.102:2379","attempt":0,"error":"rpc error: code = Unavailable desc = etcdserver: rpc not supported for learner"} [etcd] Waiting for the new etcd member to join the cluster. This can take up to 40s [mark-control-plane] Marking the node master03 as control-plane by adding the labels: [node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers] [mark-control-plane] Marking the node master03 as control-plane by adding the taints [node-role.kubernetes.io/control-plane:NoSchedule] This node has joined the cluster and a new control plane instance was created: * Certificate signing request was sent to apiserver and approval was received. * The Kubelet was informed of the new secure connection details. * Control plane label and taint were applied to the new node. * The Kubernetes control plane instances scaled up. * A new etcd member was added to the local/stacked etcd cluster. To start administering your cluster from this node, you need to run the following as a regular user: mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config Run 'kubectl get nodes' to see this node join the cluster.
6.4 添加kubect环境
for master_ip in "${MASTER_IPS[@]}"; do echo -e "\n\033[33m[INFO] >>> ${master_ip}...\033[0m" ssh -T user@${master_ip} 'bash -s' <<'EOF' set -e U=$(id -un) # 1) 当前用户(user)自己的 kubeconfig mkdir -p "$HOME/.kube" sudo install -m 600 -o "$U" -g "$U" /etc/kubernetes/admin.conf "$HOME/.kube/config" # 2) root 的 kubeconfig sudo mkdir -p /root/.kube sudo install -m 600 /etc/kubernetes/admin.conf /root/.kube/config # 3) root 的 kubectl 环境(仅 root 生效) sudo tee /etc/profile.d/custom_kubectl.sh > /dev/null <<'EOB' if [ "$(id -u)" = "0" ] && [ -f /root/.kube/config ]; then export KUBECONFIG=/root/.kube/config if [ -n "$BASH_VERSION" ] && [ -n "$PS1" ] && command -v kubectl >/dev/null 2>&1; then source <(kubectl completion bash) 2>/dev/null fi fi EOB sudo chmod 644 /etc/profile.d/custom_kubectl.sh EOF done
此时master节点为notready状态

7 安装NIC插件
7.1 部署calio
user@master01:~$ kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.29.3/manifests/tigera-operator.yaml user@master01:~$ wget https://raw.githubusercontent.com/projectcalico/calico/v3.29.3/manifests/custom-resources.yaml user@master01:~$ vim custom-resources.yaml # This section includes base Calico installation configuration. # For more information, see: https://docs.tigera.io/calico/latest/reference/installation/api#operator.tigera.io/v1.Installation apiVersion: operator.tigera.io/v1 kind: Installation metadata: name: default spec: # Configures Calico networking. calicoNetwork: ipPools: - name: default-ipv4-ippool blockSize: 26 cidr: 10.10.0.0/16 encapsulation: VXLANCrossSubnet natOutgoing: Enabled nodeSelector: all() --- # This section configures the Calico API server. # For more information, see: https://docs.tigera.io/calico/latest/reference/installation/api#operator.tigera.io/v1.APIServer apiVersion: operator.tigera.io/v1 kind: APIServer metadata: name: default spec: {} user@master01:~$ kubectl create -f custom-resources.yaml
部署完后,master节点已经就绪:

验证:

8 添加Worker节点
8.1 添加Worker节点
user@master01:~$ source var.sh user@master01:~$ for node_ip in ${NODE_IPS[@]} do echo -e "\n\n\033[33m[INFO] >>> ${node_ip}...\033[0m" ssh user@${node_ip} "sudo kubeadm join 10.32.0.112:16443 --token o8gn9i.iyukn96pakybytnf \ --discovery-token-ca-cert-hash sha256:5e9fed82f6e728016a13e72e35e25158ccbdae3adf9890ccc17fc92ac012303e" ssh user@${node_ip} "sudo systemctl enable kubelet.service" done
确认验证:

9 Helm部署
9.1 helm介绍
9.2 helm优势
9.3 前置准备
9.4 二进制安装Helm
建议采用二进制安装helm
user@master01:~$ source var.sh user@master01:~$ mkdir helm user@master01:~$ cd helm/ user@master01:~/helm$ HELMVERSION=v3.17.2 user@master01:~/helm$ wget https://repo.huaweicloud.com/helm/${HELMVERSION}/helm-${HELMVERSION}-linux-amd64.tar.gz user@master01:~/helm$ tar -zxvf helm-${HELMVERSION}-linux-amd64.tar.gz user@master01:~$ cd ~/helm && ls -l linux-amd64/helm # 确认文件在当前目录 for master_ip in "${MASTER_IPS[@]}"; do echo -e "\n\033[33m[INFO] >>> ${master_ip}...\033[0m" scp -rp linux-amd64/helm user@${master_ip}:/home/user/helm || continue ssh -T user@${master_ip} 'bash -s' <<'EOF' set -e sudo install -m 755 /home/user/helm /usr/local/bin/helm sudo tee /etc/profile.d/custom_helm.sh > /dev/null <<'EOB' if [ -n "$BASH_VERSION" ] && [ -n "$PS1" ] && command -v helm >/dev/null 2>&1; then source <(helm completion bash) 2>/dev/null fi EOB helm version --short EOF done user@master01~/helm$ source /etc/profile user@master01~/helm$ helm version $查看安装版本
9.5 Helm操作
查找
user@master01:~$ helm search hub #可搜索全部可用chart
user@master01:~$ helm search hub wordpress
添加,类似CentO S添加yum源,给helm仓库添加相关源。
root@master01:~# helm repo list #查看repo user@master01:~$ helm repo add azure https://mirror.azure.cn/kubernetes/charts user@master01:~$ helm repo add aliyun https://kubernetes.oss-cn-hangzhou.aliyuncs.com/charts user@master01:~$ helm repo add bitnami https://charts.bitnami.com/bitnami user@master01:~$ helm search repo azure user@master01:~$ helm search repo aliyun user@master01:~$ helm search repo bitnami #搜索repo中的chart user@master01:~$ helm repo update #更新repo的chart
10 Metrics安装
10.1 获取部署文件
根据实际生成环境,没Metrics Server的部署镜像个性化修改,其它保持默认即可。
主要涉及:部署副本数为3,追加--kubelet-insecure-tls配置。
本文使用helm部署metrics。
user@master01:~$ mkdir metrics user@master01:~$ cd metrics/ user@master01:~/metrics$ helm repo add metrics-server https://kubernetes-sigs.github.io/metrics-server/ user@master01:~/metrics$ helm repo list | grep metrics-server metrics-server https://kubernetes-sigs.github.io/metrics-server/ user@master01:~/metrics$ helm search repo metrics-server NAME CHART VERSION APP VERSION DESCRIPTION metrics-server/metrics-server 3.14.0 0.9.0 Metrics Server is a scalable, efficient source ...
10.2 创建自定义配置
user@master01:~/metrics$ helm show values metrics-server/metrics-server > defaults-values.yaml #查看默认配置 user@master01:~/metrics$ vim myvalues.yaml image: repository: registry.aliyuncs.com/google_containers/metrics-server #修改为阿里云镜像 args: - --kubelet-insecure-tls #自签名证书场景必须追加此行
10.3 正式部署
user@master01:~/metrics$ helm upgrade --install metrics-server metrics-server/metrics-server \
-n kube-system -f myvalues.yaml

验证:
user@master01:~/metrics$ kubectl -n kube-system get pods -l app.kubernetes.io/name=metrics-server -o wide user@master01:~/metrics$ kubectl top nodes

10.4 查看资源监控
user@master01:~$ kubectl top nodes
user@master01:~$ kubectl top pods --all-namespaces

11 Nginx Ingress部署
11.1 ingress介绍
11.2 设置标签
user@master01:~$ kubectl label nodes master0{1,2,3} ingress=enable
11.3 获取部署文件
获取部署ingress部署所需的yaml资源。
user@master01:~$ mkdir ingress user@master01:~$ cd ingress/ user@master01:~/ingress$ helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx/ "ingress-nginx" has been added to your repositories user@master01:~/ingress$ helm repo list | grep ingress-nginx ingress-nginx https://kubernetes.github.io/ingress-nginx/ user@master01:~/ingress$ helm search repo ingress-nginx NAME CHART VERSION APP VERSION DESCRIPTION ingress-nginx/ingress-nginx 4.15.1 1.15.1 Ingress controller for Kubernetes using NGINX a... user@master01:~/ingress$ helm show values ingress-nginx --repo https://kubernetes.github.io/ingress-nginx > defaults-values.yaml #查看默认配置
11.4 创建自定义文件配置
user@master01:~/ingress$ vim myvalues.yaml controller: image: registry: m.daocloud.io/registry.k8s.io image: ingress-nginx/controller tag: "v1.15.1" digest: "" config: allow-snippet-annotations: "true" client-header-buffer-size: "512k" large-client-header-buffers: "4 512k" client-body-buffer-size: "128k" proxy-buffer-size: "256k" proxy-body-size: "50m" server-name-hash-bucket-size: "128" map-hash-bucket-size: "128" ssl-ciphers: "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" ssl-protocols: "TLSv1.2 TLSv1.3" log-format-upstream: '{"time": "$time_iso8601", "remote_addr": "$proxy_protocol_addr", "x-forward-for": "$proxy_add_x_forwarded_for", "request_id": "$req_id","remote_user": "$remote_user", "bytes_sent": $bytes_sent, "request_time": $request_time, "status": $status, "vhost": "$host", "request_proto": "$server_protocol", "path": "$uri", "request_query": "$args", "request_length": $request_length, "duration": $request_time,"method": "$request_method", "http_referrer": "$http_referer", "http_user_agent": "$http_user_agent" }' tolerations: - key: node-role.kubernetes.io/control-plane effect: NoSchedule nodeSelector: kubernetes.io/os: linux replicaCount: 3 extraVolumeMounts: - name: timeconfig mountPath: /etc/localtime readOnly: true extraVolumes: - name: timeconfig hostPath: path: /etc/localtime type: File admissionWebhooks: patch: image: registry: registry.cn-hangzhou.aliyuncs.com image: google_containers/kube-webhook-certgen tag: v1.4.0 digest: "" service: type: NodePort externalTrafficPolicy: "Cluster" nodePorts: http: "30080" https: "30443"
11.5 正式部署
拉取镜像
sudo ctr -n k8s.io images pull --platform linux/amd64 \ k8s.m.daocloud.io/ingress-nginx/controller:v1.15.1
渲染验证
helm template ingress-nginx ./ingress-nginx-4.15.1.tgz -f myvalues.yaml | grep -E 'image:.*(controller|certgen)'
期望三行
image: m.daocloud.io/registry.k8s.io/ingress-nginx/controller:v1.15.1 image: registry.cn-hangzhou.aliyuncs.com/google_containers/kube-webhook-certgen:v1.4.0 image: registry.cn-hangzhou.aliyuncs.com/google_containers/kube-webhook-certgen:v1.4.0

安装
user@master01:~/ingress$ helm upgrade --install ingress-nginx ./ingress-nginx-4.15.1.tgz --namespace ingress-nginx --create-namespace -f myvalues.yaml
验证
kubectl -n ingress-nginx get pods -w kubectl -n ingress-nginx get svc

12 Dashboard部署
12.1 设置标签
基于最佳实践,非业务应用,或者集群自身的应用都应该部署在Master节点
user@master01:~$ kubectl label nodes master0{1,2,3} dashboard=enable
提示:建议对应K8s自身的应用(如dashboard),此类非业务应用部署在master节点
12.2 创建证书
默认的dashboard会自动创建证书,同时使用对应证书创建secret。生产环境可用启动相应的域名进行部署dashboard,因此需要为对应的域名制作TLS证书。
基于实验目的,采用自签证书。
user@master01:~$ mkdir -p /home/user/dashboard/certs user@master01:~$ cd /home/user/dashboard user@master01:~/dashboard$ openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \ -keyout certs/tls.key -out certs/tls.crt \ -subj "/CN=k8s.bsoft.cn" \ -addext "subjectAltName=DNS:k8s.bsoft.cn,IP:10.32.0.112"
验证SAN+权限:
user@master01:~/dashboard$ openssl x509 -in certs/tls.crt -noout -text | grep -A1 "Subject Alternative Name" user@master01:~/dashboard$ chmod 600 certs/tls.key user@master01:~/dashboard$ chmod 644 certs/tls.crt user@master01:~/dashboard$ ll certs/tls.*

12.3 手动创建密钥
自定义证书场景,建议提前适应相对应的证书创建secret
user@master01:~/dashboard/certs$ cd /home/user/dashboard/ user@master01:~/dashboard$ kubectl create ns kubernetes-dashboard #v3版本dashboard独立ns user@master01:~/dashboard$ kubectl -n kubernetes-dashboard create secret tls kubernetes-dashboard-certs \ --cert=/home/user/dashboard/certs/tls.crt --key=/home/user/dashboard/certs/tls.key user@master01:~/dashboard$ kubectl -n kubernetes-dashboard get secret kubernetes-dashboard-certs -o yaml #查看证书信息
12.4 获取部署文件
添加kubernetes-dashboard的repo仓库
user@master01:~/dashboard$ helm repo add kubernetes-dashboard https://kubernetes-retired.github.io/dashboard/ user@master01:~/dashboard$ helm repo list

12.5 创建自定义配置
user@master01:~$ cd /home/user/dashboard
user@master01:~/dashboard$ helm show values kubernetes-dashboard/kubernetes-dashboard > defaults-values.yaml #查看默认配置
编辑自定义文件
cat > /home/user/dashboard/myvalues.yaml <<'EOF' app: scheduling: nodeSelector: {"dashboard": "enable"} ingress: enabled: true hosts: - k8s.bsoft.cn ingressClassName: nginx useDefaultAnnotations: false annotations: nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" nginx.ingress.kubernetes.io/ssl-redirect: "true" tls: enabled: true secretName: "kubernetes-dashboard-certs" tolerations: - key: node-role.kubernetes.io/control-plane effect: NoSchedule auth: image: repository: m.daocloud.io/docker.io/kubernetesui/dashboard-auth tag: "1.4.0" scaling: replicas: 1 containers: volumeMounts: - mountPath: /tmp name: tmp-volume - mountPath: /etc/localtime name: timeconfig volumes: - name: tmp-volume emptyDir: {} - name: timeconfig hostPath: path: /etc/localtime nodeSelector: {"dashboard": "enable"} tolerations: - key: node-role.kubernetes.io/control-plane operator: "Exists" effect: "NoSchedule" api: image: repository: m.daocloud.io/docker.io/kubernetesui/dashboard-api tag: "1.14.0" scaling: replicas: 1 containers: volumeMounts: - mountPath: /tmp name: tmp-volume - mountPath: /etc/localtime name: timeconfig volumes: - name: tmp-volume emptyDir: {} - name: timeconfig hostPath: path: /etc/localtime nodeSelector: {"dashboard": "enable"} tolerations: - key: node-role.kubernetes.io/control-plane operator: "Exists" effect: "NoSchedule" web: image: repository: m.daocloud.io/docker.io/kubernetesui/dashboard-web tag: "1.7.0" scaling: replicas: 1 containers: volumeMounts: - mountPath: /tmp name: tmp-volume - mountPath: /etc/localtime name: timeconfig volumes: - name: tmp-volume emptyDir: {} - name: timeconfig hostPath: path: /etc/localtime nodeSelector: {"dashboard": "enable"} tolerations: - key: node-role.kubernetes.io/control-plane operator: "Exists" effect: "NoSchedule" metricsScraper: image: repository: m.daocloud.io/docker.io/kubernetesui/dashboard-metrics-scraper tag: "1.2.2" scaling: replicas: 1 containers: volumeMounts: - mountPath: /tmp name: tmp-volume - mountPath: /etc/localtime name: timeconfig volumes: - name: tmp-volume emptyDir: {} - name: timeconfig hostPath: path: /etc/localtime nodeSelector: {"dashboard": "enable"} tolerations: - key: node-role.kubernetes.io/control-plane operator: "Exists" effect: "NoSchedule" kong: nodeSelector: {"dashboard": "enable"} tolerations: - key: node-role.kubernetes.io/control-plane operator: "Exists" effect: "NoSchedule" EOF
12.6 正式部署
根据生产环境最佳实践进行调优,调优完成后开始部署:
渲染验证:
cd /home/user/dashboard helm template kubernetes-dashboard kubernetes-dashboard/kubernetes-dashboard --version 7.14.0 -f myvalues.yaml | grep 'image:' | sort -u

安装:
user@master01:~/dashboard$ helm upgrade --install kubernetes-dashboard kubernetes-dashboard/kubernetes-dashboard \ --version 7.14.0 -n kubernetes-dashboard -f myvalues.yaml
提示:也可用单独将dashboard包下载至本地,然后通过命令部署
helm pull kubernetes-dashboard/kubernetes-dashboard helm upgrade --install kubernetes-dashboard ./kubernetes-dashboard-7.11.1.tgz \ --create-namespace --namespace kubernetes-dashboard \ -f myvalues.yaml

user@master01:~/dashboard$ helm -n kubernetes-dashboard list

user@master01:~/dashboard$ helm -n kubernetes-dashboard list user@master01:~/dashboard$ kubectl -n kubernetes-dashboard get ingress -o wide

修复成固定NodePort(这样访问地址稳定,也符合最初的规划)
helm upgrade ingress-nginx ingress-nginx/ingress-nginx \ -n ingress-nginx \ --set controller.service.type=NodePort \ --set controller.service.externalTrafficPolicy=Cluster \ --set controller.service.nodePorts.http=30080 \ --set controller.service.nodePorts.https=30443
浙公网安备 33010602011771号