可在不重启 Pod 或其容器的情况下,动态调整分配给运行中 Pod 容器的 CPU 和 Memory 资源,原地更新底层 c-group 分配,从而使 pod 资源定义可变,适用于垂直动态扩展 pod 工作负载
特性状态: Kubernetes v1.27+ [alpha] 开始被支持
环境介绍
- 系统环境:Anolis OS release 8.8
- 内核版本:Linux Kernel 5.10.134-13.an8.x86_64
- Kubernetes 版本:v1.28.3
启用特性门控
1、启用 k8s 控制平面组件特性门控 InPlacePodVerticalScaling
编辑如下路径 /etc/kubernetes/manifests/{kube-apiserver.yaml, kube-controller-manager.yaml, kube-scheduler.yaml} 配置文件,在各自容器启动命令行参数添加配置项 - --feature-gates=InPlacePodVerticalScaling=true
以启用 Pod 垂直弹性伸缩的特性门控。编辑该配置后无需重启控制平面组件,该特性门控会自动生效
spec:
containers:
- command:
- kube-apiserver
- --feature-gates=InPlacePodVerticalScaling=true
- --advertise-address=192.168.31.31
...
2、启用 kubelet 组件特性门控 InPlacePodVerticalScaling
# 配置文件路径 /var/lib/kubelet/config.yaml
apiVersion: kubelet.config.k8s.io/v1beta1
featureGates:
InPlacePodVerticalScaling: true
...
# 同理还需修改 configmap 形式的 kubelet 配置,修改方式同上
kubectl -n kube-system edit configmaps kubelet-config
3、启用 kubeproxy 组件特性门控 InPlacePodVerticalScaling
# kubectl -n kube-system edit configmaps kube-proxy
apiVersion: kubeproxy.config.k8s.io/v1alpha1
featureGates:
InPlacePodVerticalScaling: true
...
创建 Pod
1、通过在容器 spec 中指定 resizePolicy
,针对 CPU 和 Memory 调整设置以下重启策略:
- NotRequired 在运行时调整容器资源
- RestartContainer 调整容器资源后需重启生效
2、以 Nginx 镜像为例,通过命令 kubectl create -f nginx.yml
创建该 pod 资源
apiVersion: v1
kind: Pod
metadata:
name: nginx
namespace: default
spec:
containers:
- name: nginx
image: nginx:1.25.3
resizePolicy:
- resourceName: cpu
restartPolicy: NotRequired
- resourceName: memory
restartPolicy: NotRequired
resources:
limits:
memory: "200Mi"
cpu: "700m"
requests:
memory: "200Mi"
cpu: "700m"
动态更新 Pod 资源
对 Pod 中的 Container 执行 patch 命令,实现对容器资源 CPU 和 Memory 的动态调整
1、降低 CPU 资源,由 0.7 cpu 降低至 0.6 cpu
kubectl patch pod nginx --patch '{"spec":{"containers":[{"name":"nginx", "resources":{"requests":{"cpu":"600m"}, "limits":{"cpu":"600m"}}}]}}'
2、提高 Memory 容量,由 200Mi 增加至 500Mi
kubectl patch pod nginx --patch '{ "spec" :{ "containers" :[{ "name" : "nginx" , "resources" :{"requests":{"memory":"500Mi"}, "limits" :{ "memory" : "500Mi" }}}]} }'
备注:当部分组件特性门控 InPlacePodVerticalScaling 未启用时,执行如上 pod 资源动态变更,会提示如下错误
The Pod “nginx” is invalid: spec: Forbidden: pod updates may not change fields other than
spec.containers[*].image
,spec.initContainers[*].image
,spec.activeDeadlineSeconds
,spec.tolerations
(only additions to existing tolerations),spec.terminationGracePeriodSeconds
(allow it to be set to 1 if it was previously negative)