Kubernetes中如何指定各类资源请求?Go语言计算CPU请求方法
Hey there! Let's tackle your two Kubernetes-related questions with clear, practical answers.
Kubernetes offers several flexible ways to define resource requests (like CPU or memory) for different resource types. Here are the most common approaches:
Define directly at the Pod/container level
This is the most basic method. In your Pod YAML, set theresources.requestsfield for each container with specific resource values. For example:apiVersion: v1 kind: Pod metadata: name: my-demo-pod spec: containers: - name: demo-container image: nginx:alpine resources: requests: cpu: "100m" # Equals 0.1 CPU cores memory: "256Mi" # Equals 256MB of memoryCPU units can be full cores (e.g.,
1) or millicores (m, 1 core = 1000 millicores). Memory units supportMi,Gi,Ki, etc.Batch-set via controllers like Deployment/StatefulSet
If you manage Pods with controllers (e.g., Deployment), define resource requests in the Pod template. All Pods created by the controller will inherit these settings:apiVersion: apps/v1 kind: Deployment metadata: name: my-deployment spec: replicas: 3 template: spec: containers: - name: app-container image: my-app:v1 resources: requests: cpu: "150m" memory: "384Mi"Enforce default requests with LimitRange
To set default resource requests for all containers in a namespace that don't explicitly define them, create aLimitRangeresource:apiVersion: v1 kind: LimitRange metadata: name: default-resource-requests namespace: default spec: limits: - defaultRequest: cpu: "50m" memory: "128Mi" type: ContainerAny container in this namespace without explicit
resources.requestswill automatically use these defaults.Restrict total namespace requests with ResourceQuota
To control the sum of resource requests across all Pods in a namespace, useResourceQuota:apiVersion: v1 kind: ResourceQuota metadata: name: namespace-resource-limit namespace: default spec: hard: requests.cpu: "2" # Total CPU requests can't exceed 2 cores requests.memory: "4Gi" # Total memory requests can't exceed 4GB
To calculate the total resource requests (e.g., CPU) for all Pods in a cluster, we'll use Kubernetes' official Go client library client-go. Below is a complete, annotated example:
Key Steps
- Initialize a Kubernetes client using your cluster's
kubeconfig(local development typically uses~/.kube/config) - List all Pods across all namespaces
- Iterate through each Pod's containers, extract and sum the target resource requests
- Handle cases where containers don't have explicit resource requests
Code Example
package main import ( "context" "fmt" "log" "path/filepath" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" ) func main() { // Load kubeconfig file var kubeconfig string if homeDir := homedir.HomeDir(); homeDir != "" { kubeconfig = filepath.Join(homeDir, ".kube", "config") } else { log.Fatal("Failed to find kubeconfig file: home directory not detected") } // Build client configuration config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { log.Fatalf("Failed to build kubeconfig: %v", err) } // Create Kubernetes client set clientSet, err := kubernetes.NewForConfig(config) if err != nil { log.Fatalf("Failed to create Kubernetes client: %v", err) } // Fetch all Pods across all namespaces pods, err := clientSet.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf("Failed to fetch Pod list: %v", err) } // Calculate total CPU requests totalCPU := resource.NewQuantity(0, resource.DecimalSI) for _, pod := range pods.Items { for _, container := range pod.Spec.Containers { // Check if CPU request is set for the container if cpuReq, exists := container.Resources.Requests[corev1.ResourceCPU]; exists { totalCPU.Add(cpuReq) } else { // Handle containers without explicit CPU requests (customize as needed) fmt.Printf("Warning: Container %s in Pod %s/%s has no CPU request defined\n", container.Name, pod.Namespace, pod.Name) } } } // Print the final total fmt.Printf("\nTotal CPU requests across all Pods: %s\n", totalCPU.String()) }
Notes
- The
resource.Quantitytype handles Kubernetes resource units (like100m) automatically, including unit conversion and safe arithmetic. - For containers without explicit requests, you can adjust the logic to use default values (e.g., from a
LimitRangein their namespace) instead of just printing a warning. - To run this code, install dependencies first:
go get k8s.io/client-go@latest
内容的提问来源于stack exchange,提问作者HamiBU

