使用开源工具监控 Kubernetes 云成本
Kubernetes
![](/data/attachment/album/202308/20/133353k1bfc3vbbfco9p1z.jpg)



> 
> OpenCost 是一款与 Kubernetes 无缝集成的云成本监控工具，可让您实时跟踪云支出，从而相应地优化资源。
> 
> 
> 


[Kubernetes](https://www.redhat.com/en/topics/containers/what-is-kubernetes?intcmp=7013a000002qLH8AAM) 是一个强大的平台，用于管理云中的动态容器化应用，但可能很难理解成本发生在哪里。管理 Kubernetes 资源的成本效率可能是一个挑战。这就是 [OpenCost](https://www.opencost.io/) 的用武之地。OpenCost 是一种云成本监控工具，与 Kubernetes 无缝集成，让你可以实时跟踪云支出，以便相应地优化资源。


OpenCost 是一个开源 [CNCF 沙盒项目](https://www.cncf.io/projects/opencost/) 和 [规范](https://github.com/opencost/opencost/blob/develop/spec/opencost-specv01.md)，用于实时监控与 Kubernetes 部署相关的云成本。该规范按服务、部署、命名空间、标签等对当前和历史 Kubernetes 云支出和资源分配进行建模。这些数据对于理解和优化 Kubernetes 从应用到基础设施的成本和性能至关重要。


### 要求和安装


开始使用 OpenCost 是一个相对简单的过程。OpenCost 使用 [Prometheus](https://prometheus.io/) 进行监控和指标存储。你可以从 [Prometheus 社区的 Kubernetes Helm Chart](https://prometheus-community.github.io/helm-charts) 安装它。


#### 安装 Prometheus


首先使用以下命令安装 Prometheus：



```
$ helm install my-prometheus --repo https://prometheus-community.github.io/helm-charts prometheus \
 --namespace prometheus --create-namespace \
 --set pushgateway.enabled=false --set alertmanager.enabled=false -f \
https://raw.githubusercontent.com/opencost/opencost/develop/kubernetes/prometheus/extraScrapeConfigs.yaml

```

#### 安装 OpenCost


接下来，使用 `kubectl` 命令安装 OpenCost：



```
$ kubectl apply --namespace opencost -f \
https://raw.githubusercontent.com/opencost/opencost/develop/kubernetes/opencost.yaml

```

此命令将 OpenCost 部署到你的集群并开始收集数据。这就是大多数安装所需的全部内容。你可以[使用你自己的 Prometheus](https://www.opencost.io/docs/install#providing-your-own-prometheus) 安装或使用 [OpenCost Helm Chart](https://github.com/opencost/opencost-helm-chart/) 自定义部署。


#### 测试和访问


OpenCost 会自动检测它是否在 AWS、Azure 还是 GCP 上运行，你可以将其配置为为本地 Kubernetes 部署提供定价。首先转发 API 和 UI 访问的端口：



```
$ kubectl port-forward --namespace opencost service/opencost 9003 9090

```

大约五分钟内，你可以验证 UI 和服务器是否正在运行，并且你可以通过 **<http://localhost:9090>** 访问 OpenCost UI。


### 监控成本


你已准备好开始使用部署到 Kubernetes 集群的 OpenCost 来监控云成本。OpenCost 仪表板提供对云支出的实时可见性，使你能够识别成本异常并优化云资源。你可以按节点、命名空间、pod、标签等查看云支出。


![OpenCost monitoring console](/data/attachment/album/202308/20/133418rbnq4ltzxxb4v3gn.png)


[kubectl cost](https://github.com/kubecost/kubectl-cost) 插件提供了对 Kubernetes 成本分配指标的简单 CLI 查询。它允许开发人员、运营商和其他人快速确定任何 Kubernetes 工作负载的成本和效率。



```
$ kubectl cost --service-port 9003 \
--service-name opencost --kubecost-namespace opencost \
--allocation-path /allocation/compute pod \
--window 5m --show-efficiency=true

+-------+---------+-------------+----------+---------------+
|CLUSTER|NAMESPACE|POD          |MONTH RATE|COST EFFICIENCY|
+-------+---------+-------------+----------+---------------+
|cl-one |kube-syst|coredns-db...| 1.486732 |      0.033660 |
|       |         |coredns-...dm| 1.486732 |      0.032272 |
|       |         |kube-prox...7| 1.359577 |      0.002200 |
|       |         |kube-prox...x| 1.359577 |      0.002470 |
|       |opencost |opencost...5t| 0.459713 |      0.187180 |
|       |kube-syst|aws-node-cbwl| 0.342340 |      0.134960 |
|       |         |aws-node-gbfh| 0.342340 |      0.133760 |
|       |prometheu|my-prome...pv| 0.000000 |      0.000000 |
|       |         |my-prome...hn| 0.000000 |      0.000000 |
|       |         |my-prome...89| 0.000000 |      0.000000 |
+-------+---------+-------------+----------+---------------+
| SUMMED|         |             | 6.837011 |               |
+-------+---------+-------------+----------+---------------+

```

你还可以集成 API，以编程方式将数据提取到你选择的平台中。


### Kubernetes 优化策略


现在你已经掌握了云成本，是时候优化你的 Kubernetes 环境了。优化是一个迭代过程。从栈的顶部（容器）开始并遍历每一层。每一步的效率都会复合。有很多方法可以优化 Kubernetes 以提高成本效率，例如：


* 查找废弃的工作负载和未申明的卷：不再使用或断开连接的容器荚和存储会继续消耗资源而不提供价值。
* 调整你的工作负载大小：确保你为你的工作负载使用正确大小的容器。调查分配过多和分配不足的容器。
* 自动扩展：自动扩展可以帮助你仅在需要时使用资源来节省成本。
* 调整集群大小：节点过多或过大可能会导致效率低下。在容量、可用性和性能之间找到适当的平衡可能会大大降低成本。
* 研究更便宜的节点类型：CPU、RAM、网络和存储有很多变化。切换到 ARM 架构可能会带来更大的节省。
* 投资 FinOps 团队：组织内的专门团队可以通过协调预留实例、现货实例和节省计划来寻找实现更大节省的方法。


### 从今天开始


监控 Kubernetes 环境中的成本可能具有挑战性，但使用 OpenCost 则不必如此。要开始使用 OpenCost 并控制你的云支出，请访问 [OpenCost](https://opencost.io/) 网站，在 [GitHub](https://github.com/opencost) 中获取代码，查看 [OpenCost 文档](https://www.opencost.io/docs/)，并参与 [CNCF Slack](https://slack.cncf.io/) 中的 **#opencost** 频道。


*（题图：MJ/5de557f1-464c-480c-8698-130748f60b20）*




---


via: <https://opensource.com/article/23/3/kubernetes-cloud-cost-monitoring>


作者：[Matt Ray](https://opensource.com/users/mattray-0) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
[Kubernetes](https://www.redhat.com/en/topics/containers/what-is-kubernetes?intcmp=7013a000002qLH8AAM) is a powerful platform for managing dynamic containerized applications in the cloud, but it may be difficult to understand where costs are incurred. Managing the cost efficiency of Kubernetes resources can be a challenge. That's where [OpenCost](https://www.opencost.io/) comes in. OpenCost is a cloud cost monitoring tool that integrates seamlessly with Kubernetes, allowing you to track your cloud spend in real-time so you can optimize your resources accordingly.

**[ Also read How to measure the cost of running applications ]**

OpenCost is an open source [CNCF Sandbox project](https://www.cncf.io/projects/opencost/) and [specification](https://github.com/opencost/opencost/blob/develop/spec/opencost-specv01.md) for the real-time monitoring of cloud costs associated with Kubernetes deployments. The specification models current and historical Kubernetes cloud spend and resource allocation by service, deployment, namespace, labels, and much more. This data is essential for understanding and optimizing Kubernetes for both cost and performance from the applications down through the infrastructure.

## Requirements and installation

Getting started with OpenCost is a relatively straightforward process. OpenCost uses [Prometheus](https://prometheus.io/) for both monitoring and metric storage. You can install it from the [Prometheus Community Kubernetes Helm Chart](https://prometheus-community.github.io/helm-charts).

### Install Prometheus

Begin by installing Prometheus using the following command:

```
``````
$ helm install my-prometheus --repo https://prometheus-community.github.io/helm-charts prometheus \
--namespace prometheus --create-namespace \
--set pushgateway.enabled=false --set alertmanager.enabled=false -f \
https://raw.githubusercontent.com/opencost/opencost/develop/kubernetes/prometheus/extraScrapeConfigs.yaml
```


### Install OpenCost

Next, install OpenCost using the `kubectl`

command:

```
``````
$ kubectl apply --namespace opencost -f \
https://raw.githubusercontent.com/opencost/opencost/develop/kubernetes/opencost.yaml
```


This command deploys OpenCost to your cluster and starts collecting data. That is all that most installations require. You can [use your own Prometheus](https://www.opencost.io/docs/install#providing-your-own-prometheus) installation or customize the deployment with the [OpenCost Helm Chart](https://github.com/opencost/opencost-helm-chart/).

### Testing and access

OpenCost automatically detects whether it runs on AWS, Azure, or GCP, and you can configure it to provide pricing for on-premises Kubernetes deployments. Begin by forwarding ports for API and UI access:

```
````$ kubectl port-forward --namespace opencost service/opencost 9003 9090`


Within about five minutes, you can verify the UI and server are running, and you may access the OpenCost UI at ** http://localhost:9090**.

## Monitor costs

You are ready to start monitoring your cloud costs with OpenCost deployed to your Kubernetes cluster. The OpenCost dashboard provides real-time visibility into your cloud spend, allowing you to identify cost anomalies and optimize your cloud resources. You can view your cloud spend by nodes, namespaces, pods, tags, and more.

![OpenCost monitoring console](https://opensource.com/sites/default/files/2023-03/opencost.png)

(Matthew Ray, CC BY-SA 4.0)

The [kubectl cost](https://github.com/kubecost/kubectl-cost) plugin provides easy CLI queries to Kubernetes cost allocation metrics. It allows developers, operators, and others to determine the cost and efficiency for any Kubernetes workload quickly.

```
``````
$ kubectl cost --service-port 9003 \
--service-name opencost --kubecost-namespace opencost \
--allocation-path /allocation/compute pod \
--window 5m --show-efficiency=true
+-------+---------+-------------+----------+---------------+
|CLUSTER|NAMESPACE|POD |MONTH RATE|COST EFFICIENCY|
+-------+---------+-------------+----------+---------------+
|cl-one |kube-syst|coredns-db...| 1.486732 | 0.033660 |
| | |coredns-...dm| 1.486732 | 0.032272 |
| | |kube-prox...7| 1.359577 | 0.002200 |
| | |kube-prox...x| 1.359577 | 0.002470 |
| |opencost |opencost...5t| 0.459713 | 0.187180 |
| |kube-syst|aws-node-cbwl| 0.342340 | 0.134960 |
| | |aws-node-gbfh| 0.342340 | 0.133760 |
| |prometheu|my-prome...pv| 0.000000 | 0.000000 |
| | |my-prome...hn| 0.000000 | 0.000000 |
| | |my-prome...89| 0.000000 | 0.000000 |
+-------+---------+-------------+----------+---------------+
| SUMMED| | | 6.837011 | |
+-------+---------+-------------+----------+---------------+
```



You can also integrate an API to extract the data programmatically into your platform of choice.

## Kubernetes optimization strategies

Now that you have a handle on your cloud costs, it's time to optimize your Kubernetes environment. Optimization is an iterative process. Start at the top of the stack (containers) and work through each layer. The efficiencies compound at each step. There are many ways to optimize Kubernetes for cost efficiency, such as:

- Look for abandoned workloads and unclaimed volumes: Pods and storage that are no longer in use or are disconnected continue to consume resources without providing value.
- Right-size your workloads: Ensure you're using the right size containers for your workloads. Investigate over- and under-allocated containers.
- Autoscaling: Autoscaling can help you save costs by only using resources when needed.
- Right-size your cluster: Too many or too-large nodes may be inefficient. Finding the right balance between capacity, availability, and performance may greatly reduce costs.
- Investigate cheaper node types: There's a lot of variation in CPU, RAM, networking, and storage. Switching to ARM architectures may unlock even greater savings.
- Invest in a FinOps team: A dedicated team within your organization can look for ways to unlock greater savings by coordinating reserved instances, spot instances, and savings plans.

## Get started today

Monitoring costs in a Kubernetes environment can be challenging, but with OpenCost, it doesn't have to be. To get started with OpenCost and take control of your cloud spend, visit the [OpenCost](https://opencost.io/) website, get the code in [GitHub](https://github.com/opencost), check out the [OpenCost documentation](https://www.opencost.io/docs/), and get involved in the **#opencost** channel in the [CNCF Slack](https://slack.cncf.io/).

**[ Related read How to prioritize cloud spending ]**

## Comments are closed.