使用 prometheus-operator/kube-prometheus 栈时已内置 KSM,无需重复安装;GKE 上角色权限受限,需先创建 cluster-admin-binding;custom-resource-state 已冻结,后续将由 resource-state-metrics 取代
kube-state-metrics
kubernetesApache-2.0活跃维护把 Kubernetes 集群里各类资源对象的状态转成 Prometheus 指标暴露出来,补上 cAdvisor 等只看容器运行时指标的盲区,方便做集群监控和告警。
Add-on agent to generate and expose cluster-level metrics.
kubectl apply -f examples/standardREADME 未说明显存或 GPU 要求,作为集群内 Pod 运行的 Go 服务,无特殊硬件依赖
监听 Kubernetes API 并生成集群对象状态指标,供 Prometheus 抓取
把 Kubernetes 集群里各类资源对象的状态转成 Prometheus 指标暴露出来,补上 cAdvisor 等只看容器运行时指标的盲区,方便做集群监控和告警。
核心能力
- 监听 API Server 生成 Deployment、Node、Pod 等对象状态指标
- 在 /metrics 端点以明文暴露原始未修改的 API 数据
- 支持 allow/deny 列表按正则过滤资源与指标
- 支持水平分片与 DaemonSet 分片扩展采集规模
- 提供 /healthz、/livez、/readyz 健康检查端点
容易踩的坑
- v2.20.0最新正式版2026-08-18 · 2026-08-18 08:46 UTC
v2.20.0 / 2026-08-16
Notes
Custom Resource State (CRS) metrics are now feature-frozen; no new CRS features will be accepted going forward. See #3050 for details.
- This release builds with Go
v1.26.6 - This release builds with
k8s.io/client-go:v0.36.3
Changelog
- [CHANGE]
kube_pod_status_reasonnow emits a row only for the reason that is actually set, instead of one zero/one row per known reason for every pod by @bhope in #3089 - [FEATURE] Add
kube_pod_status_disruption_reasonmetric for pods evicted via the Eviction API by @bhope in #3088 - [FEATURE] Add MutatingAdmissionPolicy and MutatingAdmissionPolicyBinding metrics by @mrueg in #3019
- [FEATURE] Add ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding metrics by @mrueg in #3014
- [FEATURE] Add HPA scale up/down behavior tolerance metrics by @emmayusufu in #3015
- [FEATURE] Add
kube_node_spec_pod_cidrsmetric by @emmayusufu in #3011 - [FEATURE] Add
kube_pod_resourceclaim_infometric for DRA ResourceClaim references by @cyber-slave-labs in #3005 - [FEATURE] Add
kube_pod_init_container_status_last_terminated_exitcodemetric by @emmayusufu in #3000 - [FEATURE] Add init container
state_startedandlast_terminated_timestampmetrics by @emmayusufu in #2997 - [FEATURE] Shard only resource mutation watch events by @jfremy-openai in #2993
- [FEATURE] Add label generation support for ephemeral volumes in pods by @eminaktas in #2891
- [FEATURE] Allow wildcards in annotation and label allowlists by @skoef in #2873
- [FEATURE] Add access mode metric for PersistentVolumes by @viragvoros in #2823
- [ENHANCEMENT] Reduce allocations in metric generation and header sanitization by @mrueg in #3060
- [ENHANCEMENT] Implement
cache.StoreBookmark and LastStoreSyncResourceVersion in MetricsStore for client-go 0.36 compatibility by @mrueg in #2965 - [BUGFIX] Don't panic on a Deployment with an unset
rollingUpdatevalue by @mrueg in #3083 - [BUGFIX] Serialize config reloads so one does not strand another instance by @mrueg in #3070
- [BUGFIX] Rebuild clients from the current kubeconfig on reload by @mrueg in #3080
- [BUGFIX] Check CRD fields instead of asserting them during discovery by @mrueg in #3078
- [BUGFIX] Build each EndpointSlice hint's labels independently by @mrueg in #3076
- [BUGFIX] Guard the store builder state shared with discovery by @mrueg in #3075
- [BUGFIX] Read the discovery GVK cache under the lock by @mrueg in #3074
- [BUGFIX] Scope the metrics handler scrape lock to reading the writers by @mrue
- This release builds with Go
- v2.19.12026-06-12 · 2026-06-12 05:38 UTC
查看更新说明
v2.19.1 / 2026-06-10
Notes
- This release builds with Go
v1.26.4 - This release builds with
k8s.io/client-go:v0.35.4
Changelog
- [SECURITY] Upgrade Go toolchain to address CVE-2026-42504 (GO-2026-5038) by @slessard in #2982
- [SECURITY] Fix several high-scoring CVEs (golang.org/x/net, oauth2, sys, term, text) by @slessard in #2981
- [BUGFIX] Fix watch-list bookmarks with sharding (WatchListClient compatibility) by @jfremy-openai in #2974
- [BUGFIX] Don't panic on CronJobs with unparseable schedules by @atosatto in #2978
Full Changelog: https://github.com/kubernetes/kube-state-metrics/compare/v2.19.0...v2.19.1
- This release builds with Go
- v2.19.02026-05-21 · 2026-05-21 07:33 UTC
查看更新说明
v2.19.0 / 2026-05-05
Notes
The v2.19.0 tag was force-moved from it's original commit (https://github.com/kubernetes/kube-state-metrics/commit/b18fbda7881baa84f6cf51dff2a727191b58d049) to the one succeeding it (https://github.com/kubernetes/kube-state-metrics/commit/2ef24549bff9865db214ccb03cc36f1fc214d1be) to address an issue in KSM's image promotion; see https://github.com/kubernetes/kube-state-metrics/pull/2964 for more information.
This release addresses a security vulnerability (GHSA-g3c8-4qh2-rhrg) where
/debug/pprof/*endpoints were not protected by the--auth-filterflag. The endpoints have been moved to the telemetry server and are now correctly gated. See #2924 for details. Credits to @vldevadath for responsible disclosure.- This release builds with Go
v1.26.2 - This release builds with
k8s.io/client-go:v0.35.4
Changelog
- [SECURITY] Fix authentication bypass: move pprof endpoints to telemetry server and protect with auth filter (GHSA-g3c8-4qh2-rhrg) by @bhope in #2924
- [SECURITY] Bump
go-jose/v4tov4.1.4for CVE-2026-34986 by @marioferh in #2941 - [SECURITY] Fix CVE-2026-24051 in otel go library by @marvin659 in #2908
- [SECURITY] Fix CVE-2026-39883 in otel go library by @Dinesh-Jilagam in #2952
- [SECURITY] Bump
google.golang.org/grpctov1.79.3by @sturman in #2925 - [FEATURE] Add
PreemptionBySchedulerandTerminationByKubelettokube_pod_status_reasonby @bhope in #2892 - [FEATURE] Add
SchedulingGatedtokube_pod_status_reasonby @bhope in #2880 - [FEATURE] Add
containerlabel to HPA ContainerResource metrics by @bxrne in #2836 - [FEATURE] Add deployment-based sharding example by @ystkfujii in #2931
- [BUGFIX] Handle DeletedFinalStateUnknown panic in CR informer by @rexagod in #2955
- [BUGFIX] Fix memory leak from orphaned CR reflector goroutines on repeated CRD discovery by @bhope in #2920
- [BUGFIX] Load CRS config when
--continue-without-custom-resource-state-config-fileis set and file exists by @ybouhachem in #2918 - [BUGFIX] Accept legacy
custom_resource_config_fileas deprecated alias by @nmn3m in #2926 - [BUGFIX] Fix order-dependent metric loss from header deduplication by @jfremy-openai in #2866
- [BUGFIX] Avoid mutating metric families during write by @bhope in #2852
- [BUGFIX] Honor
stderrthresholdwhenlogtostderris enabled by @pierluigilenoci in #2906 - [ENHANCEMENT] Bump to Kubernetes 1.35 by @mrueg in #2861
- [ENHANCEMENT] Build with Go 1.26 by @mrueg in #2890
- [ENHANCEMENT] Switch to a maintained fork of
robfig/cronby @mrueg in #2874
Full Changelog
- chore: Merge
release-2.18back intomainby @rexagod in https://github.com/kubernetes/kube-state-metrics/pull/2850
- This release builds with Go
- v2.18.02026-01-18 · 2026-01-18 04:58 UTC
查看更新说明
v2.18.0 / 2026-01-11
Note
- This release builds with Go
v1.25.6 - This release builds with
k8s.io/client-go:v0.34.3 - This release addresses a regression that caused a panic when new versions were added to existing
CustomResourceDefinitions. See the post-mortem analysis in https://github.com/kubernetes/kube-state-metrics/pull/2838 for more details. endpointslicesare now part of the default resources exposed as metrics.endpointsis deprecated and needs to be manually activated through the--resourcesflag. See https://github.com/kubernetes/kube-state-metrics/pull/2659 for more details.
Changelog
- [CHANGE] Replace endpoints with endpointslices as default resource by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2659
- [BUGFIX] Fix regression: React on WATCH updates for CRD informer by @rexagod in https://github.com/kubernetes/kube-state-metrics/pull/2838
- [BUGFIX] Deduplicate tolerations when generating
kube_pod_tolerationsby @bhope in https://github.com/kubernetes/kube-state-metrics/pull/2835 - [FEATURE] Allow filtering resources via URL parameters by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2844
- [FEATURE] Add
kube_job_status_readymetric by @nmn3m in https://github.com/kubernetes/kube-state-metrics/pull/2771 - [FEATURE] Add
kube_deployment_ownermetric by @nmn3m in https://github.com/kubernetes/kube-state-metrics/pull/2782 - [FEATURE] Add
kube_deployment_status_replicas_terminatingandkube_replicaset_status_terminating_replicasmetrics by @atiratree in https://github.com/kubernetes/kube-state-metrics/pull/2708 - [FEATURE] Promote CronJob, HPA, and Pod metrics from BETA to STABLE by @nmn3m in https://github.com/kubernetes/kube-state-metrics/pull/2798
- [FEATURE] Promote StatefulSet metrics to STABLE by @yasicar in https://github.com/kubernetes/kube-state-metrics/pull/2783
- [FEATURE] Add info metric for client-go version by @fpetkovski in https://github.com/kubernetes/kube-state-metrics/pull/2739
- [FEATURE] Warn on probe failing by @mickael-carl in https://github.com/kubernetes/kube-state-metrics/pull/2808
- [ENHANCEMENT] Add
failedcondition tokube_certificatesigningrequest_conditionby @ksmiley in https://github.com/kubernetes/kube-state-metrics/pull/2841 - [ENHANCEMENT] Reduce allocations when creating metric families by @fpetkovski in https://github.com/kubernetes/kube-state-metrics/pull/2807
- [ENHANCEMENT] Bump to kubernetes 1.34 by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2785
- [ENHANCEMENT] Bump exporter-toolkit by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2770
- [ENHANCEMENT] Replace gojsontoyaml with gojq by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2660
- [ENHANCEMENT] Split benchmarks by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2759
Full Changelog
- build(deps): Bump sigs.k8s.io/yaml from 1.4.0 to 1.5.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2694
- chore: Merge v2.16 back into
mainby @rexagod in https://github.com/kubernetes/kube-state-metrics/pull/2697 - build(deps): Bump github.com/oklog/run from 1.1.0 to 1.2.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2696
- feat(pod): Add new metric for pod unscheduled time tracking by @yshngg in https://github.com/kubernetes/kube-state-metrics/pull/2699
- build(deps): Bump github.com/KimMachineGun/automemlimit from 0.7.3 to 0.7.4 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2707
- chore: Add CatherineF-dev into SECURITY_CONTACTS by @CatherineF-dev in https://github.com/kubernetes/kube-state-metrics/pull/2710
- build(deps): Bump sigs.k8s.io/yaml from 1.5.0 to 1.6.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2712
- build(deps): Bump github.com/prometheus/client_golang from 1.22.0 to 1
- This release builds with Go
- v2.17.0v2.17.0 / 2025-09-012025-09-01 · 2025-09-01 13:38 UTC
查看更新说明
Note
- This release builds with Go
v1.24.6 - This release builds with
k8s.io/client-go:v0.33.4 - This release is the last release that has endpoint metrics enabled by default. In the next release we will enable endpointslices metrics and disable endpoint metrics by default, since the endpoint resources are deprecated. You can still alter this behaviour in kube-state-metrics' config.
Changelog
- [FEATURE] Add new metric for pod unscheduled time tracking by @yshngg in https://github.com/kubernetes/kube-state-metrics/pull/2699
- [BUGFIX] Fix index out of range by @taraspos in https://github.com/kubernetes/kube-state-metrics/pull/2716
- [BUGFIX] Config file overrides apply to some fields but not other by @rashmichandrashekar in https://github.com/kubernetes/kube-state-metrics/pull/2705
- [BUGFIX] Fix logic for plain text fallback format by @timonegk in https://github.com/kubernetes/kube-state-metrics/pull/2730
- [FEATURE] Include reason label to
kube_deployment_status_conditionby @Rishab87 in https://github.com/kubernetes/kube-state-metrics/pull/2719 - [FEATURE] Continue running kube-state-metrics when config file doesnt exist at startup by @rashmichandrashekar in https://github.com/kubernetes/kube-state-metrics/pull/2703
- [FEATURE] Introduce deletion timestamp metric for daemonset, statefulset, deployment, service and pdb by @IgorIgnatevBolt in https://github.com/kubernetes/kube-state-metrics/pull/2678
- [FEATURE] Add HorizontalPodAutoscaler created and deletionTimestamp info into metrics by @IgorIgnatevBolt in https://github.com/kubernetes/kube-state-metrics/pull/2675
Full Changelog
- build(deps): Bump sigs.k8s.io/yaml from 1.4.0 to 1.5.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2694
- chore: Merge v2.16 back into
mainby @rexagod in https://github.com/kubernetes/kube-state-metrics/pull/2697 - build(deps): Bump github.com/oklog/run from 1.1.0 to 1.2.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2696
- feat(pod): Add new metric for pod unscheduled time tracking by @yshngg in https://github.com/kubernetes/kube-state-metrics/pull/2699
- build(deps): Bump github.com/KimMachineGun/automemlimit from 0.7.3 to 0.7.4 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2707
- chore: Add CatherineF-dev into SECURITY_CONTACTS by @CatherineF-dev in https://github.com/kubernetes/kube-state-metrics/pull/2710
- build(deps): Bump sigs.k8s.io/yaml from 1.5.0 to 1.6.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2712
- build(deps): Bump github.com/prometheus/client_golang from 1.22.0 to 1.23.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2717
- fix(customresourcestate): fix index out of range by @taraspos in https://github.com/kubernetes/kube-state-metrics/pull/2716
- fix: Config file overrides apply to some fields but not other by @rashmichandrashekar in https://github.com/kubernetes/kube-state-metrics/pull/2705
- chore: Build with k8s 1.33 by @mrueg in https://github.com/kubernetes/kube-state-metrics/pull/2720
- fix: Fixed the format of Markdown files by @Rishab87 in https://github.com/kubernetes/kube-state-metrics/pull/2714
- build(deps): Bump actions/checkout from 4.2.2 to 5.0.0 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2731
- docs: Update metrics-store-performance-optimization.md by @ydFu in https://github.com/kubernetes/kube-state-metrics/pull/2723
- feat: include reason label to
kube_deployment_status_conditionby @Rishab87 in https://github.com/kubernetes/kube-state-metrics/pull/2719 - build(deps): Bump the k8s-dependencies group with 5 updates by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/2737
- build(deps): Bump amannn/action-semantic-pull-request from 5.5.3 to 6.0.1 by @dependabot[bot] in https://github.com/kubernetes/kube-state-metrics/pull/
- This release builds with Go
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
Overview
kube-state-metrics (KSM) is a simple service that listens to the Kubernetes API server and generates metrics about the state of the objects. (See examples in the Metrics section below.) It is not focused on the health of the individual Kubernetes components, but rather on the health of the various objects inside, such as deployments, nodes and pods.
kube-state-metrics is about generating metrics from Kubernetes API objects without modification. This ensures that features provided by kube-state-metrics have the same grade of stability as the Kubernetes API objects themselves. In turn, this means that kube-state-metrics in certain situations may not show the exact same values as kubectl, as kubectl applies certain heuristics to display comprehensible messages. kube-state-metrics exposes raw data unmodified from the Kubernetes API, this way users have all the data they require and perform heuristics as they see fit.
The metrics are exported on the HTTP endpoint /metrics on the listening port
(default 8080). They are served as plaintext. They are designed to be consumed
either by Prometheus itself or by a scraper that is compatible with scraping a
Prometheus client endpoint. You can also open /metrics in a browser to see
the raw metrics. Note that the metrics exposed on the /metrics endpoint
reflect the current state of the Kubernetes cluster. When Kubernetes objects
are deleted they are no longer visible on the /metrics endpoint.
[!NOTE] This README is generated from a template. Please make your changes there and run
make generate-template.
Table of Contents
- Versioning
- Metrics Documentation
- Kube-state-metrics self metrics
- kube-state-metrics vs. metrics-server
- Scaling kube-state-metrics
- Setup
- Usage
Versioning
Kubernetes Version
kube-state-metrics uses client-go to talk with
Kubernetes clusters. The supported Kubernetes cluster version is determined by
client-go.
All additional compatibility is only best effort, or happens to still/already be supported.
Compatibility matrix
At most, 5 kube-state-metrics and 5 kubernetes releases will be recorded below. Generally, it is recommended to use the latest release of kube-state-metrics. If you run a very recent version of Kubernetes, you might want to use an unreleased version to have the full range of supported resources. If you run an older version of Kubernetes, you might need to run an older version in order to have full support for all resources. Be aware, that the maintainers will only support the latest release. Older versions might be supported by interested users of the community.
| kube-state-metrics | Kubernetes client-go Version |
|---|---|
| v2.16.0 | v1.32 |
| v2.17.0 | v1.33 |
| v2.18.0 | v1.34 |
| v2.19.0 | v1.35 |
| v2.20.0 | v1.36 |
| main | v1.37 |
Resource group version compatibility
Resources in Kubernetes can evolve, i.e., the group version for a resource may change from alpha to beta and finally GA in different Kubernetes versions. For now, kube-state-metrics will only use the oldest API available in the latest release.
Container Image
The latest container image can be found at:
registry.k8s.io/kube-state-metrics/kube-state-metrics:v2.20.0(arch:amd64,arm,arm64,ppc64leands390x)- Multi-architecture images
Metrics Documentation
Any resources and metrics based on alpha Kubernetes APIs are excluded from any stability guarantee, which may be changed at any given release.
See the docs directory for more information on the exposed metrics.
Custom Resource State Metrics
[!NOTE]
custom-resource-stateis feature-frozen in favor of resource-state-metrics. Onceresource-state-metricsis stable,custom-resource-statewill be deprecated.
Conflict resolution in label names
The *_labels family of metrics exposes Kubernetes labels as Prometheus labels.
As Kubernetes
is more liberal than
Prometheus
in terms of allowed characters in label names,
we automatically convert unsupported characters to underscores.
For example, app.kubernetes.io/name becomes label_app_kubernetes_io_name.
This conversion can create conflicts when multiple Kubernetes labels like
foo-bar and foo_bar would be converted to the same Prometheus label label_foo_bar.
Kube-state-metrics automatically adds a suffix _conflictN to resolve this conflict,
so it converts the above labels to
label_foo_bar_conflict1 and label_foo_bar_conflict2.
If you'd like to have more control over how this conflict is resolved, you might want to consider addressing this issue on a different level of the stack, e.g. by standardizing Kubernetes labels using an Admission Webhook that ensures that there are no possible conflicts.
ECMAScript regular expression support for allow and deny lists
Starting from #2616, kube-state-metrics supports ECMAScript's regexp for allow and deny lists. This was incorporated as a workaround for the limitations of the regexp package in Go, which does not support lookarounds due to their non-linear time complexity. Please note that while lookarounds are now supported for allow and deny lists, regular expressions' evaluation time is capped at a minute to prevent performance issues.
Kube-state-metrics self metrics
kube-state-metrics exposes its own general process metrics under --telemetry-host and --telemetry-port (default 8081).
kube-state-metrics also exposes list and watch success and error metrics. These can be used to calculate the error rate of list or watch resources. If you encounter those errors in the metrics, it is most likely a configuration or permission issue, and the next thing to investigate would be looking at the logs of kube-state-metrics.
Example of the above mentioned metrics:
kube_state_metrics_list_total{resource="*v1.Node",result="success"} 1
kube_state_metrics_list_total{resource="*v1.Node",result="error"} 52
kube_state_metrics_watch_total{resource="*v1beta1.Ingress",result="success"} 1
kube-state-metrics also exposes some http request metrics, examples of those are:
http_request_duration_seconds_bucket{handler="metrics",method="get",le="2.5"} 30
http_request_duration_seconds_bucket{handler="metrics",method="get",le="5"} 30
http_request_duration_seconds_bucket{handler="metrics",method="get",le="10"} 30
http_request_duration_seconds_bucket{handler="metrics",method="get",le="+Inf"} 30
http_request_duration_seconds_sum{handler="metrics",method="get"} 0.021113919999999998
http_request_duration_seconds_count{handler="metrics",method="get"} 30
kube-state-metrics also exposes build and configuration metrics:
kube_state_metrics_build_info{branch="main",goversion="go1.15.3",revision="6c9d775d",version="v2.0.0-beta"} 1
kube_state_metrics_shard_ordinal{shard_ordinal="0"} 0
kube_state_metrics_total_shards 1
kube_state_metrics_build_info is used to expose version and other build information. For more usage about the info pattern,
please check this blog post.
Sharding metrics expose --shard and --total-shards flags and can be used to validate
run-time configuration, see /examples/prometheus-alerting-rules.
kube-state-metrics also exposes metrics about it config file and the Custom Resource State config file:
kube_state_metrics_config_hash{filename="crs.yml",type="customresourceconfig"} 2.38272279311849e+14
kube_state_metrics_config_hash{filename="config.yml",type="config"} 2.65285922340846e+14
kube_state_metrics_last_config_reload_success_timestamp_seconds{filename="crs.yml",type="customresourceconfig"} 1.6704882592037103e+09
kube_state_metrics_last_config_reload_success_timestamp_seconds{filename="config.yml",type="config"} 1.6704882592035313e+09
kube_state_metrics_last_config_reload_successful{filename="crs.yml",type="customresourceconfig"} 1
kube_state_metrics_last_config_reload_successful{filename="config.yml",type="config"} 1
kube-state-metrics vs. metrics-server
The metrics-server is a project that has been inspired by Heapster and is implemented to serve the goals of core metrics pipelines in Kubernetes monitoring architecture. It is a cluster level component which periodically scrapes metrics from all Kubernetes nodes served by Kubelet through Metrics API. The metrics are aggregated, stored in memory and served in Metrics API format. The metrics-server stores the latest values only and is not responsible for forwarding metrics to third-party destinations.
kube-state-metrics is focused on generating completely new metrics from Kubernetes' object state (e.g. metrics based on deployments, replica sets, etc.). It holds an entire snapshot of Kubernetes state in memory and continuously generates new metrics based off of it. And just like the metrics-server it too is not responsible for exporting its metrics anywhere.
Having kube-state-metrics as a separate project also enables access to these metrics from monitoring systems such as Prometheus.
Scaling kube-state-metrics
Resource recommendation
Resource usage for kube-state-metrics changes with the Kubernetes objects (Pods/Nodes/Deployments/Secrets etc.) size of the cluster. To some extent, the Kubernetes objects in a cluster are in direct proportion to the node number of the cluster.
As a general rule, you should allocate:
- 250MiB memory
- 0.1 cores
Note that if CPU limits are set too low, kube-state-metrics' internal queues will not be able to be worked off quickly enough, resulting in increased memory consumption as the queue length grows. If you experience problems resulting from high memory allocation or CPU throttling, try increasing the CPU limits.
Latency
In a 100 node cluster scaling test the latency numbers were as follows:
"Perc50": 259615384 ns,
"Perc90": 475000000 ns,
"Perc99": 906666666 ns.
A note on costing
By default, kube-state-metrics exposes several metrics for events across your cluster. If you have a large number of frequently-updating resources on your cluster, you may find that a lot of data is ingested into these metrics. This can incur high costs on some cloud providers. Please take a moment to configure what metrics you'd like to expose, as well as consult the documentation for your Kubernetes environment in order to avoid unexpectedly high costs.
Horizontal sharding
In order to shard kube-state-metrics horizontally, some automated sharding capabilities have been implemented. It is configured with the following flags:
--shard(zero indexed)--total-shards
Sharding is done by taking an md5 sum of the Kubernetes Object's UID and performing a modulo operation on it with the total number of shards. Each shard decides whether the object is handled by the respective instance of kube-state-metrics or not. Note that this means all instances of kube-state-metrics, even if sharded, will have the network traffic and the resource consumption for unmarshaling objects for all objects, not just the ones they are responsible for. To optimize this further, the Kubernetes API would need to support sharded list/watch capabilities. In the optimal case, memory consumption for each shard will be 1/n compared to an unsharded setup. Typically, kube-state-metrics needs to be memory and latency optimized in order for it to return its metrics rather quickly to Prometheus. One way to reduce the latency between kube-state-metrics and the kube-apiserver is to run KSM with the --use-apiserver-cache flag. In addition to reducing the latency, this option will also lead to a reduction in the load on etcd.
Sharding should be used carefully and additional monitoring should be set up in order to ensure that sharding is set up and functioning as expected (eg. instances for each shard out of the total shards are configured).
Automated sharding
Automatic sharding allows each shard to discover its nominal position when deployed in a StatefulSet which is useful for automatically configuring sharding.
To enable automated sharding, kube-state-metrics must be run by a StatefulSet and the pod name and namespace must be handed to the kube-state-metrics process via the --pod and --pod-namespace flags. Example manifests demonstrating the autosharding functionality can be found in /examples/autosharding.
This way of deploying shards is useful when you want to manage KSM shards through a single Kubernetes resource (a single StatefulSet in this case) instead of having one Deployment per shard. The advantage can be especially significant when deploying a high number of shards.
The downside of using an auto-sharded setup comes from the rollout strategy supported by StatefulSets. When managed by a StatefulSet, pods are replaced one at a time with each pod first getting terminated and then recreated. Besides such rollouts being slower, they will also lead to short downtime for each shard. If a Prometheus scrape happens during a rollout, it can miss some of the metrics exported by kube-state-metrics.
Deployment sharding
If you prefer to manage shards as independent Deployment objects instead of using a single StatefulSet, you can use deployment-based sharding. In this model, each Deployment is configured with an explicit shard index using --shard=<N> and the total number of shards using --total-shards=<N>.
Example manifests for deployment-based sharding are available in /examples/deploymentsharding.
Compared to automated sharding, this approach:
- Uses the standard
Deploymentrolling update behavior, which can reduce the risk of metric gaps during upgrades - Gives each shard a fixed, explicitly assigned shard index
The trade-offs are that:
- You must manage each shard as a separate Kubernetes
Deployment - You must keep the shard configuration consistent across all shard
Deploymentobjects, such as the total shard count and shared settings- This means scaling the number of shards requires redeploying all of them
Daemonset sharding for pod metrics
For pod metrics, they can be sharded per node with the following flag:
--node=$(NODE_NAME)
Each kube-state-metrics pod uses FieldSelector (spec.nodeName) to watch/list pod metrics only on the same node.
A daemonset kube-state-metrics example:
apiVersion: apps/v1
kind: DaemonSet
spec:
template:
spec:
containers:
- image: registry.k8s.io/kube-state-metrics/kube-state-metrics:IMAGE_TAG
name: kube-state-metrics
args:
- --resources=pods
- --node=$(NODE_NAME)
env:
- name: NODE_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: spec.nodeName
These pods only need to list and watch pods, so the daemonset sharding example runs them, and the deployment for unassigned pods below, under a dedicated kube-state-metrics-shard ServiceAccount whose ClusterRole only allows listing and watching pods, plus the token and subject access reviews needed for --auth-filter.
To track metrics for unassigned pods, you need to add an additional deployment and set --track-unscheduled-pods, as shown in the following example:
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- image: registry.k8s.io/kube-state-metrics/kube-state-metrics:IMAGE_TAG
name: kube-state-metrics
args:
- --resources=pods
- --track-unscheduled-pods
Other metrics can be sharded via Horizontal sharding.
Resource Filtering
The /metrics endpoint supports filtering by resource type using the resources query parameter. This allows you to scrape only the metrics for specific Kubernetes resources, which can be useful for reducing the amount of data scraped or for creating separate scraping jobs for different resource types.
Example:
curl 'http://localhost:8080/metrics?resources=pods,secrets'
Multiple resources can be specified as a comma-separated list, or by providing the resources parameter multiple times.
You can also exclude specific resources using the exclude_resources query parameter. This is useful if you want to scrape all metrics except for a few specific ones.
Example:
curl 'http://localhost:8080/metrics?exclude_resources=pods'
If both resources and exclude_resources are provided, the resources parameter acts as an allowlist, and exclude_resources acts as a denylist, filtering out any resources specified in the exclude_resources parameter from the allowed resources.
The exclude_resources takes precedence here and you can only filter on resources that are enabled in kube-state-metrics.
Setup
Install this project to your $GOPATH using go get:
go get k8s.io/kube-state-metrics/v2
Building the Docker container
Simply run the following command in this root folder, which will create a self-contained, statically-linked binary and build a Docker image:
make container
Usage
Simply build and run kube-state-metrics inside a Kubernetes pod which has a service account token that has read-only access to the Kubernetes cluster.
For users of prometheus-operator/kube-prometheus stack
The (kube-prometheus) stack installs kube-state-metrics as one of its components; you do not need to install kube-state-metrics if you're using the kube-prometheus stack.
If you want to revise the default configuration for kube-prometheus, for example to enable non-default metrics, have a look at Customizing Kube-Prometheus.
Kubernetes Deployment
To deploy this project, you can simply run kubectl apply -f examples/standard and a Kubernetes service and deployment will be created. (Note: Adjust the apiVersion of some resource if your kubernetes cluster's version is not 1.8+, check the yaml file for more information).
To have Prometheus discover kube-state-metrics instances it is advised to create a specific Prometheus scrape config for kube-state-metrics that picks up both metrics endpoints. Annotation based discovery is discouraged as only one of the endpoints would be able to be selected, plus kube-state-metrics in most cases has special authentication and authorization requirements as it essentially grants read access through the metrics endpoint to most information available to it.
Note: Google Kubernetes Engine (GKE) Users - GKE has strict role permissions that will prevent the kube-state-metrics roles and role bindings from being created. To work around this, you can give your GCP identity the cluster-admin role by running the following one-liner:
kubectl create clusterrolebinding cluster-admin-binding --clusterrole=cluster-admin --user=$(gcloud info --format='value(config.account)')
Note that your GCP identity is case sensitive but gcloud info as of Google Cloud SDK 221.0.0 is not. This means that if your IAM member contains capital letters, the above one-liner may not work for you. If you have 403 forbidden responses after running the above command and kubectl apply -f examples/standard, check the IAM member associated with your account at https://console.cloud.google.com/iam-admin/iam?project=PROJECT_ID. If it contains capital letters, you may need to set the --user flag in the command above to the case-sensitive role listed at https://console.cloud.google.com/iam-admin/iam?project=PROJECT_ID.
After running the above, if you see Clusterrolebinding "cluster-admin-binding" created, then you are able to continue with the setup of this service.
Healthcheck Endpoints
The following healthcheck endpoints are available (self refers to the telemetry port, while main refers to the exposition port):
/healthz(exposed onmain): Returns a 200 status code if the application is running. We recommend to use this for the startup probe./livez(exposed onmain): Returns a 200 status code if the application is not affected by an outage of the Kubernetes API Server. We recommend to using this for the liveness probe./readyz(exposed onself): Returns a 200 status code if the application is ready to accept requests and expose metrics. We recommend using this for the readiness probe.
Note that it is discouraged to use the telemetry metrics endpoint for any probe when proxying the exposition data.
Limited privileges environment
If you want to run kube-state-metrics in an environment where you don't have cluster-reader role, you can:
- create a serviceaccount
apiVersion: v1
kind: ServiceAccount
metadata:
name: kube-state-metrics
namespace: your-namespace-where-kube-state-metrics-will-deployed
- give it
viewprivileges on specific namespaces (using roleBinding) (note: you can add this roleBinding to all the NS you want your serviceaccount to access)
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: kube-state-metrics
namespace: project1
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: kube-state-metrics
namespace: your-namespace-where-kube-state-metrics-will-deployed
- then specify a set of namespaces (using the
--namespacesoption) and a set of kubernetes objects (using the--resources) that your serviceaccount has access to in thekube-state-metricsdeployment configuration
spec:
template:
spec:
containers:
- name: kube-state-metrics
args:
- '--resources=pods'
- '--namespaces=project1'
For the full list of arguments available, see the documentation in docs/developer/cli-arguments.md
Helm Chart
Starting from the kube-state-metrics chart v2.13.3 (kube-state-metrics image v1.9.8), the official Helm chart is maintained in prometheus-community/helm-charts. Starting from kube-state-metrics chart v3.0.0 only kube-state-metrics images of v2.0.0 + are supported.
Development
When developing, test a metric dump against your local Kubernetes cluster by running:
Users can override the apiserver address in KUBE-CONFIG file with
--apiservercommand line.
go install
kube-state-metrics --port=8080 --telemetry-port=8081 --kubeconfig=<KUBE-CONFIG> --apiserver=<APISERVER>
Then curl the metrics endpoint
curl localhost:8080/metrics
To run the e2e tests locally see the documentation in tests/README.md.
Developer Contributions
When developing, there are certain code patterns to follow to better your contributing experience and likelihood of e2e and other ci tests to pass. To learn more about them, see the documentation in docs/developer/guide.md.
Community
This project is sponsored by SIG Instrumentation.
There is also a channel for #kube-state-metrics on Kubernetes' Slack.
You can also join the SIG Instrumentation mailing list. This will typically add invites for the following meetings to your calendar, in which topics around kube-state-metrics can be discussed.
- Regular SIG Meeting: Thursdays at 9:30 PT (Pacific Time) (biweekly). Convert to your timezone.
- Regular Triage Meeting: Thursdays at 9:30 PT (Pacific Time) (biweekly - alternating with regular meeting). Convert to your timezone.