想通过kubectl patch更新deploy的资源,但是出现如下错误:
k8smaster01@/app/tools>kubectl -n ${NAMESPACE} patch deploy aim-realnamegw-1-0-0 -p '{"spec":{"template":{"spec":{"containers":{"resources":{"limits":{"cpu":"0.5","memory":"256Mi"},"requests":{"cpu":"0.5","memory":"256Mi"}}}}}}}'
Error from server: cannot restore slice from map
但是执行explain路径是正确的呀:
k8smaster01@/home/betadmin>kubectl explain pod.spec.containers.resources
RESOURCE: resources <Object>
DESCRIPTION:
Compute Resources required by this container. Cannot be updated. More info:
https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources
ResourceRequirements describes the compute resource requirements.
FIELDS:
limits <map[string]string>
Limits describes the maximum amount of compute resources allowed. More
requests <map[string]string>
Requests describes the minimum amount of compute resources required. If
Requests is omitted for a container, it defaults to Limits if that is
explicitly specified, otherwise to an implementation-defined value. More
实际上这个错误的意思是:值的类型错误,不符合deploy的预定,具体来说是containers的值,这里直接是:
{"resources":{"limits":{"cpu":"0.5","memory":"256Mi"},"requests":{"cpu":"0.5","memory":"256Mi"}}}
这表示containers是对象类型,而实际上container是对象数组类型,可通过explain查看:
k8smaster01@/home/betadmin>kubectl explain pod.spec
containers <[]Object> -required-
List of containers belonging to the pod. Containers cannot currently be
added or removed. There must be at least one container in a Pod. Cannot be
updated.
其中类型是<[ ]Object>表示对象数组。
解决方案:加上数组标识 [ ]
k8smaster01@/app/tools>kubectl -n ${NAMESPACE} patch deploy aim-realnamegw-1-0-0 -p '{"spec":{"template":{"spec":{"containers":[{"name": "aim-realnamegw","resources":{"limits":{"cpu":"0.5","memory":"256Mi"},"requests":{"cpu":"0.5","memory":"256Mi"}}}]}}}}'
deployment "aim-realnamegw-1-0-0" patched
注意需要指定name来指定要修改的元素!
下面附录一个容器环境瘦身的shell脚本:
开发和测试环境常常因资源不足导致部署Pending,可通过如下脚本进行瘦身
#系统瘦身:所有deploy replicas缩为1,所有pod资源缩为 0.5cpu 256M
#适用于一个deploy中只有一个container的deploy
#参数1:namespace环境变量
#环境瘦身
function Slimming()
{
deployments=$(kubectl get deploy -n ${NAMESPACE} | grep -v 'NAME' | cut -d ' ' -f 1)
for element in ${deployments[@]}
do
containerName=$(kubectl -n ${NAMESPACE} get deploy $element -owide | grep -v 'NAME' | awk '{print $7}')
#${containerName}在json中是字符串类型,json串中必须使用双引号应用
#不能直接包含在双引号中,否者shell不会替换为参数值
#通过前后字符串来拼接,注意不要前后字符串都别缺少双引号
kubectl -n ${NAMESPACE} patch deploy ${element} -p '{"spec":{"template":{"spec":{"containers":[{"name": "'${containerName}'","resources":{"limits":{"cpu":"1","memory":"1Gi"},"requests":{"cpu":"1","memory":"1Gi"}}}]}}}}'
kubectl -n ${NAMESPACE} patch hpa ${element} -p '{"spec":{"minReplicas":1,"maxReplicas":1}}'
done
}