温馨提示×

centos k8s自动扩缩容怎么做

小樊
44
2025-08-10 21:15:49
栏目: 智能运维

在CentOS上实现K8s自动扩缩容,通常使用Horizontal Pod Autoscaler(HPA)和Cluster Autoscaler,具体操作如下:

一、Pod水平自动扩缩容(HPA)

  1. 创建Deployment:先定义应用的Deployment,例如:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        resources:
          requests:
            cpu: "100m"
            memory: "200Mi"
          limits:
            cpu: "500m"
            memory: "1Gi"
  1. 配置HPA:通过kubectl命令或YAML文件创建HPA,设置扩缩容规则,例如:
kubectl autoscale deployment nginx-deployment --cpu-percent=50 --min=2 --max=10

或使用YAML文件:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: nginx-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx-deployment
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

二、节点自动扩缩容(Cluster Autoscaler)

  1. 安装Cluster Autoscaler:在K8s集群上部署Cluster Autoscaler,可通过以下命令安装:
kubectl apply -f https://github.com/kubernetes/autoscaler/releases/download/cluster-autoscaler/v1.21.0/cluster-autoscaler.yaml
  1. 配置节点组:确保节点组支持自动扩缩容,如使用云厂商的节点组或配置本地节点的扩缩容策略。

三、验证与监控

  1. 查看HPA状态
kubectl get hpa
  1. 监控节点和Pod状态:使用kubectl top nodeskubectl top pods命令监控资源使用情况,或通过Prometheus等工具进行更详细的监控。

0