如何列出Kubernetes所有Service及其关联的活跃Pod数量?
列出Kubernetes Service并显示关联活跃Pod数量
你可以通过结合kubectl的自定义列输出和shell脚本,实现同时展示Service信息及关联的活跃(Running状态)Pod数量,以下是两种可行方案:
方案一:基础shell循环实现
直接通过kubectl输出Service的核心信息和关联selector,再逐行查询对应Pod数量:
kubectl get services -o custom-columns='NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,EXTERNAL-IP:.status.loadBalancer.ingress[0].ip,PORT(S):.spec.ports[*].port,SELECTOR:{range .spec.selector}{.} {end}' --no-headers | while read -r name type cluster_ip external_ip ports selector; do # 查询selector匹配的Running状态Pod数量 pod_count=$(kubectl get pods --selector="$selector" --field-selector=status.phase=Running --no-headers 2>/dev/null | wc -l) # 格式化输出,空的EXTERNAL-IP用"-"填充 echo "$name $type ${cluster_ip:-"-"} ${external_ip:-"-"} $ports $pod_count" done | column -t
方案二:结合jq简化字段处理
如果你的环境安装了jq,可以用它更优雅地解析Service的JSON输出,再处理Pod数量:
kubectl get services -o json | jq -r '.items[] | [ .metadata.name, .spec.type, .spec.clusterIP, (.status.loadBalancer.ingress[]?.ip // "-"), .spec.ports[].port, (.spec.selector | to_entries | map("\(.key)=\(.value)") | join(",") // "-") ] | @tsv' | while IFS=$'\t' read -r name type cluster_ip external_ip port selector; do pod_count=$(kubectl get pods --selector="$selector" --field-selector=status.phase=Running --no-headers 2>/dev/null | wc -l) echo -e "$name\t$type\t$cluster_ip\t$external_ip\t$port\t$pod_count" done | column -t -s $'\t'
注意事项
- 对于没有selector的Service(比如手动绑定Endpoint的Service),上述脚本会返回
0,因为没有自动关联的Pod - 若需要统计所有状态的Pod而非仅Running,去掉命令中的
--field-selector=status.phase=Running参数 column命令用于对齐输出列,若你的系统未安装该工具,可忽略此部分,直接查看原始输出
内容的提问来源于stack exchange,提问作者MTS
相关产品推荐
相关产品推荐

