You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pulumi中正确使用HorizontalPodAutoscaler(HPA v1)

解决Pulumi配置HPA v1的集群连接错误及示例

先解决集群连接错误

错误提示明确是Kubernetes客户端配置未加载,按以下步骤排查:

  • 确保本地~/.kube/config文件存在且有效,可通过kubectl get nodes验证集群连通性
  • 如果kubeconfig不在默认路径,设置KUBECONFIG环境变量指定路径:
    export KUBECONFIG=/path/to/your/kubeconfig
    
  • 若在云环境(如EKS、GKE),先通过对应云工具生成kubeconfig:
    • AWS EKS: aws eks update-kubeconfig --cluster-name your-cluster-name
    • GCP GKE: gcloud container clusters get-credentials your-cluster-name --zone your-zone

正确的Pulumi HPA v1配置示例

以下是完整的可运行示例,包含Deployment和对应的HPA配置(若已有Deployment可省略对应代码):

import * as k8s from "@pulumi/kubernetes";

const namespaceName = "default";
const deploymentName = "worker";
const prefixedHPAName = "worker-hpa";

// 定义Worker Deployment(已有则跳过)
const workerDeployment = new k8s.apps.v1.Deployment(deploymentName, {
    metadata: {
        namespace: namespaceName,
        name: deploymentName,
    },
    spec: {
        replicas: 1,
        selector: { matchLabels: { app: "worker" } },
        template: {
            metadata: { labels: { app: "worker" } },
            spec: {
                containers: [{
                    name: "worker",
                    image: "nginx:alpine",
                    resources: {
                        requests: { cpu: "100m" },
                        limits: { cpu: "500m" },
                    },
                }],
            },
        },
    },
});

// 配置HPA v1
const workerHpa = new k8s.autoscaling.v1.HorizontalPodAutoscaler(prefixedHPAName, {
    metadata: {
        name: prefixedHPAName,
        namespace: namespaceName,
        // 注意:clusterName无需手动指定,Pulumi会自动从kubeconfig获取集群信息
    },
    spec: {
        maxReplicas: 3,
        minReplicas: 1,
        scaleTargetRef: {
            apiVersion: "apps/v1",
            kind: "Deployment",
            name: deploymentName,
        },
        targetCPUUtilizationPercentage: 50,
    },
}, { dependsOn: [workerDeployment] }); // 确保HPA在Deployment创建后部署

关键注意事项

  • dependsOn参数避免HPA因找不到目标Deployment报错
  • 目标Deployment必须配置resources.requests.cpu,HPA v1才能基于CPU使用率扩缩容
  • 不要手动指定clusterName,Pulumi会自动读取kubeconfig中的集群配置

内容的提问来源于stack exchange,提问作者Tushar Jagtap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:24:30