k8s~根據podIP查看pod信息
在 Kubernetes 集群中查找與特定 Pod IP(如 10.10.5.7)關聯的服務,可以通過以下步驟操作:
方法 1:通過 Endpoints 查詢(推薦)
kubectl get endpoints --all-namespaces -o json | \
jq -r '.items[] | select(.subsets[].addresses[].ip == "10.10.5.7") | .metadata.namespace + "/" + .metadata.name'
方法 2:通過 Service 選擇器匹配
- 先找到 Pod 的標簽:
kubectl get pod --all-namespaces -o wide --field-selector status.podIP=10.10.5.7
# 輸出示例:
# NAMESPACE NAME READY STATUS IP NODE LABELS
# my-namespace my-pod-1 1/1 Running 10.10.5.7 node-1 app=myapp,env=prod
- 根據標簽查找服務:
kubectl get svc --all-namespaces -o json | \
jq -r '.items[] | select(.spec.selector.app == "myapp" and .spec.selector.env == "prod") | .metadata.namespace + "/" + .metadata.name'
方法 3:直接檢查網絡策略
kubectl get networkpolicy --all-namespaces -o json | \
jq -r '.items[] | select(.spec.podSelector.matchLabels.app == "myapp") | .metadata.namespace + "/" + .metadata.name'
方法 4:使用 IP 直接查詢(需安裝 IPVS 工具)
# 在運行 kube-proxy 的節點上執行
sudo ipvsadm -Ln | grep -B1 10.10.5.7
# 輸出示例:
# TCP 10.96.123.45:80 rr
# -> 10.10.5.7:80 Masq 1 0 0
解釋說明:
-
Endpoints 方法:
- 直接查詢 Kubernetes 的 Endpoints 對象(存儲了 Service 到 Pod IP 的映射)
- 需要安裝
jq工具(可通過apt-get install jq或brew install jq安裝)
-
Service 選擇器方法:
- 先定位 Pod 的標簽(LABELS 列)
- 然后查找使用相同選擇器(selector)的 Service
-
如果找不到服務可能的原因:
- Pod 沒有關聯任何 Service
- Service 的選擇器與 Pod 標簽不匹配
- Pod 處于未就緒狀態(檢查 readinessProbe)
額外診斷命令:
# 檢查 Pod 是否就緒
kubectl get pod -o wide -A | grep 10.10.5.7
# 檢查服務的 Endpoints
kubectl describe svc <service-name> -n <namespace> | grep -A10 Endpoints
# 檢查網絡連通性(在集群內節點執行)
kubectl run debug-tool -it --rm --image=nicolaka/netshoot -- bash
curl -v http://10.10.5.7:<port>
根據您的集群規模,推薦優先使用 方法 1(Endpoints 查詢),這是最直接有效的方式。如果未安裝 jq,可以使用以下替代命令:
kubectl get endpoints -A -o jsonpath='{range .items[?(@.subsets)]}{.metadata.namespace}{" "}{.metadata.name}{"\n"}{range .subsets[*].addresses[*]}{.ip}{"\n"}{end}{end}' | \
grep -B1 10.10.5.7
浙公網安備 33010602011771號