You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes中如何指定各类资源请求?Go语言计算CPU请求方法

Hey there! Let's tackle your two Kubernetes-related questions with clear, practical answers.

1. 如何在Kubernetes中为每种资源类型指定资源请求?

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 the resources.requests field 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 memory
    

    CPU units can be full cores (e.g., 1) or millicores (m, 1 core = 1000 millicores). Memory units support Mi, 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 a LimitRange resource:

    apiVersion: v1
    kind: LimitRange
    metadata:
      name: default-resource-requests
      namespace: default
    spec:
      limits:
      - defaultRequest:
          cpu: "50m"
          memory: "128Mi"
        type: Container
    

    Any container in this namespace without explicit resources.requests will automatically use these defaults.

  • Restrict total namespace requests with ResourceQuota
    To control the sum of resource requests across all Pods in a namespace, use ResourceQuota:

    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
    
2. Implementing resource request calculation for all Pods with Go

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

  1. Initialize a Kubernetes client using your cluster's kubeconfig (local development typically uses ~/.kube/config)
  2. List all Pods across all namespaces
  3. Iterate through each Pod's containers, extract and sum the target resource requests
  4. 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.Quantity type handles Kubernetes resource units (like 100m) 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 LimitRange in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:57:58