要查看 指定 Pod 的資源限制(CPU/內存),可以通過以下 kubectl
命令實現:
1. 快速查看某個 Pod 的資源限制
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].resources}' | jq
輸出示例:
{"limits": {"cpu": "500m","memory": "1024Mi"},"requests": {"cpu": "100m","memory": "256Mi"}
}
2. 分步操作詳解
(1) 查看 Pod 的資源限制(直接查看)
kubectl describe pod <pod-name> | grep -A 5 "Containers:"
輸出示例:
Containers:my-container:...Resources:Limits:cpu: 500mmemory: 1024MiRequests:cpu: 100mmemory: 256Mi
(2) 通過 JSONPath 精準提取
kubectl get pod <pod-name> -o=jsonpath='{range .spec.containers[*]}{.name}{"\tLimits: "}{.resources.limits}{"\tRequests: "}{.resources.requests}{"\n"}{end}'
輸出示例:
my-container Limits: map[cpu:500m memory:1024Mi] Requests: map[cpu:100m memory:256Mi]
(3) 格式化輸出(需要 jq
工具)
kubectl get pod <pod-name> -o json | jq '.spec.containers[].resources'
輸出示例:
{"limits": {"cpu": "500m","memory": "1024Mi"},"requests": {"cpu": "100m","memory": "256Mi"}
}
3. 高階用法
(1) 查看所有 Pod 的資源限制
kubectl get pods -o custom-columns="NAME:.metadata.name,CPU_LIMIT:.spec.containers[*].resources.limits.cpu,MEMORY_LIMIT:.spec.containers[*].resources.limits.memory"
輸出示例:
NAME CPU_LIMIT MEMORY_LIMIT
my-pod-1234 500m 1024Mi
another-pod-5678 1 2Gi
(2) 結合標簽篩選
kubectl get pods -l app=my-app -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].resources.limits}{"\n"}{end}'
4. 常見問題
問題1:輸出為空
? 原因:Pod 未設置資源限制。
? 驗證:檢查 Deployment/YAML 是否配置了 resources
字段。
問題2:單位不匹配
? 示例錯誤:Error: cannot convert '2G' to a quantity
? 修復:使用標準單位(如 2Gi
代替 2G
)。
問題3:Pod 不存在
? 錯誤:Error from server (NotFound): pods "<pod-name>" not found
? 解決:
# 先列出所有 Pod
kubectl get pods --all-namespaces
# 再根據名稱查找
kubectl get pod <pod-name> -n <namespace>
通過這些命令,你可以快速定位 Kubernetes 中 Pod 的資源限制配置,確保應用按預期運行。