动态

详情 返回 返回

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 選擇器匹配

  1. 先找到 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
  1. 根據標籤查找服務
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

解釋説明:

  1. Endpoints 方法

    • 直接查詢 Kubernetes 的 Endpoints 對象(存儲了 Service 到 Pod IP 的映射)
    • 需要安裝 jq 工具(可通過 apt-get install jqbrew install jq 安裝)
  2. Service 選擇器方法

    • 先定位 Pod 的標籤(LABELS 列)
    • 然後查找使用相同選擇器(selector)的 Service
  3. 如果找不到服務可能的原因

    • 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

Add a new 评论

Some HTML is okay.