- 目前最新版V1.24.0版本的k8s会导致metircs-server无法正常工作
issue - 如果没有正常安装metrics-server的话,kubectl top的命令会报错
$ kubectl top pod
error: Metrics API not available
或者
$ kubectl top pod
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)
install metrics-server
- kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
- 如果这时候查看deployment提示出错:
$ kubectl describe pod metrics-server-65b979d49c-bm4vz -n kube-system
······
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 5m14s default-scheduler Successfully assigned kube-system/metrics-server-65b979d49c-bm4vz to docker-desktop
Normal Pulling 5m13s kubelet Pulling image "k8s.gcr.io/metrics-server/metrics-server:v0.6.0"
Normal Pulled 5m kubelet Successfully pulled image "k8s.gcr.io/metrics-server/metrics-server:v0.6.0" in 12.7280389s
Normal Created 5m kubelet Created container metrics-server
Normal Started 5m kubelet Started container metrics-server
Warning Unhealthy 4s (x28 over 4m34s) kubelet Readiness probe failed: HTTP probe failed with statuscode: 500
可以修改yaml文件添加–kubelet-insecure-tls,更改后如下所示:
containers:
- args:
- --cert-dir=/tmp
- --secure-port=4443
- --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
- --kubelet-use-node-status-port
- --metric-resolution=15s
- --kubelet-insecure-tls
并保存,修改更新指令如下
$ kubectl edit deploy metrics-server --save-config -n kube-system
安装完之后,便可以通过api访问:
package main
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
metrics "k8s.io/metrics/pkg/client/clientset/versioned"
"os"
"os/user"
"strings"
)
func main() {
u, err := user.Current()
if err != nil {
fmt.Println(err)
}
fmt.Println("Home dir:", u.HomeDir)
cmdapi, err := clientcmd.LoadFromFile(u.HomeDir + "/.kube/config")
if err != nil {
fmt.Println("LoadFromFile err:", err)
}
// 当前集群名称
fmt.Printf("current cluster: [%s]\n", cmdapi.CurrentContext)
// uses the current context in kubeconfig
// path-to-kubeconfig -- for example, /root/.kube/config
// 需要传入url,否则有可能会访问失败
masterUrl := strings.Replace(os.Getenv("KUBERNETES_PORT"), "tcp", "https", -1)
config, err := clientcmd.BuildConfigFromFlags(masterUrl, u.HomeDir + "/.kube/config")
if err != nil {
fmt.Printf("build config fail: %s", err)
return
}
// build metrics
mc, err := metrics.NewForConfig(config)
if err != nil {
fmt.Println("NewForConfig metrics err is ", err)
}
nodeMC, err := mc.MetricsV1beta1().NodeMetricses().Get(context.TODO(), cmdapi.CurrentContext, metav1.GetOptions{})
if err != nil {
fmt.Println("node get metrics error: ", err)
}
fmt.Println("node[", nodeMC.Name, "] cpu usage: ", nodeMC.Usage.Cpu().String())
//mc.MetricsV1beta1().NodeMetricses().List(metav1.ListOptions{})
//mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).List(metav1.ListOptions{})
//mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).Get("your pod name", metav1.GetOptions{})
}