OpenCost:Kubernetes 成本监控,开源的云资源费用分析

OpenCost:Kubernetes 成本监控,开源的云资源费用分析 OpenCostKubernetes 成本监控开源的云资源费用分析随着企业将越来越多的工作负载迁移到 Kubernetes一个新的管理挑战随之浮现到底哪个团队、哪个应用在花钱公有云账单只能告诉你整个集群的月度费用却无法拆分到具体的 Namespace、Deployment 或 Pod 级别。OpenCost 正是 CNCF 开源社区对这一痛点的回答——它是一个专为 Kubernetes 设计的实时成本监控和分析工具可以按 Namespace、Pod、Deployment、Label 等维度精准分摊云资源费用帮助平台团队实现 FinOps财务运营让每个开发团队清晰地看到自己的资源消耗成本。OpenCost 与 Prometheus 深度集成并提供 Grafana 仪表盘和 REST API是 Kubernetes 成本治理的理想起点。服务器配置OpenCost 需要运行在 Kubernetes 集群内作为 Pod 部署。对于自托管 K3s 集群考虑到需要同时运行 Prometheus、OpenCost 及业务工作负载推荐使用4 核 8GB 内存的机型作为集群节点确保监控系统有充足资源不影响业务服务的稳定运行。推荐使用雨云服务器 rainyun-com搭建 集群节点。注册填码2026off领 5 折4 核 8GB 机型就够用是国内自托管 Kubernetes 学习和生产环境的优选方案。推荐配置参数规格CPU4 核 vCPU内存8 GB RAM系统盘80 GB SSD操作系统Ubuntu 22.04 LTS带宽10 Mbps角色K3s 单节点all-in-one或 Worker Node安装前提条件安装 K3s# 在 Ubuntu 22.04 上快速安装 K3scurl-sfLhttps://get.k3s.io|sh-# 配置 kubectlmkdir-p~/.kubesudocp/etc/rancher/k3s/k3s.yaml ~/.kube/configsudochown$USER:$USER~/.kube/configexportKUBECONFIG~/.kube/config# 验证集群kubectl get nodes安装 Helmcurlhttps://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3|bashhelm version第一步安装 PrometheusOpenCost 依赖OpenCost 需要从 Prometheus 读取 Kubernetes 资源指标CPU、内存使用率等必须先部署 Prometheus。# 添加 Prometheus 社区 Helm 仓库helm repoaddprometheus-community https://prometheus-community.github.io/helm-charts helm repo update# 安装 kube-prometheus-stack包含 Prometheus Grafana AlertManagerkubectl create namespace monitoring helminstallkube-prometheus-stack\prometheus-community/kube-prometheus-stack\--namespacemonitoring\--setprometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValuesfalse\--setprometheus.prometheusSpec.retention30d\--setprometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.resources.requests.storage20Gi\--setgrafana.adminPasswordadmin123\--wait验证 Prometheus 正常运行kubectl get pods-nmonitoring# 确保所有 pod 状态为 Running第二步安装 OpenCost# 添加 OpenCost Helm 仓库helm repoaddopencost https://opencost.github.io/opencost-helm-chart helm repo update# 安装 OpenCosthelminstallopencost opencost/opencost\--namespacemonitoring\--setopencost.exporter.defaultClusterIdmy-k3s-cluster\--setopencost.prometheus.internal.enabledfalse\--setopencost.prometheus.external.enabledtrue\--setopencost.prometheus.external.urlhttp://kube-prometheus-stack-prometheus.monitoring.svc:9090\--wait验证 OpenCost 安装kubectl get pods-nmonitoring-lapp.kubernetes.io/nameopencost# 预期输出# NAME READY STATUS RESTARTS AGE# opencost-xxxxxxxxx-xxxxx 2/2 Running 0 2m配置自定义定价针对雨云 VPS 等自托管节点在公有云AWS/GCP/Azure环境中OpenCost 可以自动获取官方定价数据。但对于自托管的 VPS如雨云服务器需要手动配置 CPU 和内存的每小时单价使成本分析有实际意义。创建自定义定价 ConfigMap# custom-pricing.yamlapiVersion:v1kind:ConfigMapmetadata:name:opencost-custom-pricingnamespace:monitoringdata:pricing.json:|{ provider: custom, description: 雨云 VPS 定价配置, CPU: 0.05, spotCPU: 0.03, RAM: 0.01, spotRAM: 0.006, GPU: 0.00, storage: 0.0003, zoneNetworkEgress: 0.00, regionNetworkEgress: 0.00, internetNetworkEgress: 0.08, description_CPU: 每核每小时 0.05 元基于 4 核 8GB 机型月付约 144 元计算, description_RAM: 每 GB 每小时 0.01 元, description_storage: 每 GB 每小时 0.0003 元 }kubectl apply-fcustom-pricing.yaml更新 OpenCost 配置以使用自定义定价helm upgrade opencost opencost/opencost\--namespacemonitoring\--reuse-values\--setopencost.customPricing.enabledtrue\--setopencost.customPricing.configmapNameopencost-custom-pricing\--setopencost.customPricing.keypricing.jsonHelm Values 完整配置参考# values-opencost.yamlopencost:exporter:defaultClusterId:rainyun-k3s-prodimage:registry:ghcr.iorepository:opencost/opencosttag:latestresources:requests:cpu:10mmemory:55Milimits:cpu:999mmemory:1Giprometheus:external:enabled:trueurl:http://kube-prometheus-stack-prometheus.monitoring.svc:9090customPricing:enabled:trueconfigmapName:opencost-custom-pricingkey:pricing.jsonui:enabled:trueimage:registry:ghcr.iorepository:opencost/opencost-uitag:latestresources:requests:cpu:10mmemory:55MiserviceAccount:create:truename:opencosthelm upgrade opencost opencost/opencost\--namespacemonitoring\-fvalues-opencost.yaml实战示例访问 OpenCost UI通过kubectl port-forward将 OpenCost UI 转发到本地# 转发 UI 端口9090kubectl port-forward-nmonitoring svc/opencost9090:9090# 转发 API 端口9003kubectl port-forward-nmonitoring svc/opencost9003:9003# 浏览器访问echoOpenCost UI: http://localhost:9090echoOpenCost API: http://localhost:9003使用 API 查询成本数据OpenCost 提供 REST API方便集成到自定义报表或告警系统中# 查询过去 7 天按 Namespace 分摊的成本curl-shttp://localhost:9003/allocation?window7daggregatenamespaceaccumulatetrue\|jq.data[0] | to_entries[] | {namespace: .key, totalCost: .value.totalCost}示例输出{namespace:default,totalCost:2.34}{namespace:monitoring,totalCost:5.67}{namespace:kube-system,totalCost:1.23}{namespace:production,totalCost:18.90}# 查询过去 30 天按 Deployment 分摊的成本curl-shttp://localhost:9003/allocation?window30daggregatedeploymentaccumulatefalse\|jq.data[] | to_entries[] | {name: .key, cpuCost: .value.cpuCost, ramCost: .value.ramCost}# 查询资产成本节点、持久卷等curl-shttp://localhost:9003/assets?window7daggregatetype\|jq.data[0]# 查询特定 Label 的成本如按 teambackend 统计curl-shttp://localhost:9003/allocation?window7daggregatelabel:teamaccumulatetrue\|jq.data[0]导入 Grafana DashboardOpenCost 官方提供 Grafana DashboardID: 15714一键导入即可# 获取 Grafana 访问地址kubectl port-forward-nmonitoring svc/kube-prometheus-stack-grafana3000:80echoGrafana: http://localhost:3000 (admin/admin123)在 Grafana 中点击左侧菜单Dashboards → Import在 “Import via grafana.com” 输入框中输入15714点击Load选择 Prometheus 数据源点击Import配置成本告警当某个 Namespace 的月度预估费用超过阈值时自动告警# opencost-alerts.yamlapiVersion:monitoring.coreos.com/v1kind:PrometheusRulemetadata:name:opencost-cost-alertsnamespace:monitoringlabels:release:kube-prometheus-stackspec:groups:-name:opencost.rulesrules:# 告警production namespace 月度费用超过 500 元-alert:HighCostNamespaceexpr:|sum( container_cpu_allocation * on(node) group_left() node_cpu_hourly_cost ) by (namespace) * 720 500for:5mlabels:severity:warningannotations:summary:Namespace {{ $labels.namespace }} 月度费用超出预算description:预估月度费用: ¥{{ $value | printf \%.2f\ }}# 告警单个 Pod 内存使用超过 2GB-alert:HighMemoryPodexpr:|container_memory_working_set_bytes{container!} 2 * 1024 * 1024 * 1024for:10mlabels:severity:infoannotations:summary:Pod {{ $labels.pod }} 内存使用超过 2GBkubectl apply-fopencost-alerts.yaml使用技巧按维度分析成本# 按 Pod 名称汇总适合找出吃资源的 Podcurl-shttp://localhost:9003/allocation?window24haggregatepodaccumulatetrue\|jq.data[0] | to_entries | sort_by(.value.totalCost) | reverse | .[0:10][] | {pod: .key, cost: .value.totalCost}# 按 Label 分析如 appnginxcurl-shttp://localhost:9003/allocation?window7daggregatelabel:app\|jq.data[0]# 查看集群级别汇总成本curl-shttp://localhost:9003/allocation?windowmonth-to-dateaggregatecluster\|jq.data[0]导出成本数据到 CSV# 获取 JSON 数据并用 jq 转换为 CSVcurl-shttp://localhost:9003/allocation?window7daggregatenamespaceaccumulatetrue\|jq-r.data[0] | to_entries[] | [.key, .value.cpuCost, .value.ramCost, .value.pvCost, .value.totalCost] | csv\cost-report-$(date%Y%m%d).csvecho成本报表已导出到: cost-report-$(date%Y%m%d).csv常用 kubectl 命令# 查看 OpenCost Pod 状态kubectl get pods-nmonitoring-lapp.kubernetes.io/nameopencost# 查看 OpenCost 日志kubectl logs-nmonitoring-lapp.kubernetes.io/nameopencost-copencost-f# 重启 OpenCost更新定价配置后kubectl rollout restart deployment/opencost-nmonitoring# 查看 OpenCost 资源使用情况kubectltoppod-nmonitoring-lapp.kubernetes.io/nameopencost与 Kubecost 的对比特性OpenCostKubecost Community开源协议Apache 2.0部分闭源CNCF 项目是Sandbox否自定义定价支持支持多集群需要手动聚合商业版支持Grafana 集成原生原生成本告警通过 Prometheus内置适用场景开源 / 自托管企业级功能需求OpenCost 让 Kubernetes 集群的成本从黑盒变成透明账单帮助团队准确识别资源浪费优化工作负载配置最终降低基础设施成本。无论你是在学习 FinOps 最佳实践还是正在为生产 K3s 集群构建成本监控体系都可以从 OpenCost 开始。