CentOS环境下Kubernetes集群扩展策略
Kubernetes集群扩展主要分为节点扩展(横向增加工作节点数量,提升集群整体资源池容量)和Pod扩展(纵向或横向调整Pod数量/资源配额,匹配应用负载需求)两大维度,两者结合可实现集群规模的灵活调整。
setenforce 0)、防火墙(systemctl stop firewalld)、swap分区(swapoff -a);配置主机名(hostnamectl set-hostname <node-name>)和/etc/hosts文件(确保节点间域名解析正确);同步时间(使用NTP服务)。kubeadm token create --print-join-command获取加入命令(包含Token和CA证书哈希),在目标节点执行该命令完成加入。kubectl get nodes,确认新节点状态为Ready。通过Cluster Autoscaler实现节点的自动增减,应对资源需求波动。配置要点包括:
--min-nodes,如4)和最大节点数(--max-nodes,如20),避免资源浪费或不足;通过修改Deployment/StatefulSet的replicas字段,直接调整Pod数量。例如:
kubectl scale deployment my-deployment --replicas=5 -n default
适用于已知负载变化的场景(如促销活动前预扩容)。
Horizontal Pod Autoscaler(HPA):根据CPU、内存或自定义指标(如QPS、延迟)自动调整Pod副本数。需先安装Metrics Server收集资源数据,再创建HPA配置文件(示例如下)。例如,当Pod CPU使用率超过50%时,自动扩展副本数至10个(最小1个,最大10个):
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: my-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-deployment
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
Vertical Pod Autoscaler(VPA):自动调整Pod的资源请求(requests)和限制(limits),优化资源利用率。适用于资源需求波动大但有稳定基线的应用(如数据库)。
结合HPA(分钟级响应,处理瞬时流量波动)、Cluster Autoscaler(小时级调整,应对长期资源需求变化)和CronHPA(定时扩缩,处理周期性流量如早晚高峰),实现多维度的弹性覆盖。例如:
缩容时需避免服务中断,遵循以下步骤:
kubectl cordon <node-name>标记节点为不可调度,停止接收新流量;preStop Hook(如sleep 30),等待现有请求处理完毕;kubectl drain <node-name> --ignore-daemonsets,安全驱逐Pod;behavior字段配置冷却时间(stabilizationWindowSeconds: 120)和扩容步长(policies: - type: Pods value: 2 periodSeconds: 60),减少频繁扩缩带来的资源浪费。etcdctl snapshot save),避免数据丢失;maxReplicas和Cluster Autoscaler的max-nodes,避免过度扩容增加成本。