跳转至

8. 性能调优

K3s 虽然轻量,但如果不加限制,单个应用可能耗尽整个节点资源。本章介绍如何通过 QoS 和调度策略优化性能。

8.1 资源限制 (Resource Quota)

为防止“邻居干扰”(Noisy Neighbor),必须为每个 Pod 设置 Request 和 Limit。

8.1.1 QoS 等级

Kubernetes 根据资源配置自动分配 QoS 等级:

  1. Guaranteed (最高): Request == Limit (CPU & Memory)。
  2. Burstable (中等): Request < Limit。
  3. BestEffort (最低): 未设置资源限制。节点压力大时最先被驱逐。

manifests/08-performance/guaranteed-pod.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: important-app
spec:
  containers:
  - name: app
    image: nginx
    resources:
      limits:
        memory: "200Mi"
        cpu: "500m"
      requests:
        memory: "200Mi"
        cpu: "500m"

8.2 节点亲和性 (Affinity)

让特定的应用跑在特定的节点上(例如:AI 任务跑在 GPU 节点,Web 服务跑在边缘节点)。

8.2.1 节点打标

kubectl label nodes k3s-worker-1 disktype=ssd

8.2.2 亲和性配置

spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd

8.3 自动扩缩容 (HPA)

根据 CPU 利用率自动增加 Pod 副本数。

8.3.1 启用 HPA

前提:必须安装 Metrics Server(K3s 默认已安装)。

# 检查 metrics 是否正常
kubectl top pods

创建一个 HPA 策略:

kubectl autoscale deployment nginx-deployment --cpu-percent=50 --min=1 --max=10
当 Pod CPU 平均使用率超过 50% 时,自动扩容,最多 10 个副本。

8.4 内核调优

对于高并发场景,需调整宿主机内核参数。

创建 /etc/sysctl.d/99-k8s.conf:

net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward                 = 1
net.ipv4.conf.all.forwarding        = 1
fs.file-max                         = 1000000
执行 sysctl -p 生效。