第 3 章:管理 Pod 上的資源分配
資源分配 Resource Quotas
- resource request
- resource limit:去限制某個 container 最多只能使用的資源
helloworld-deployment.yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
name: helloworld-deployment
spec:
replicas: 2
selector:
matchLabels:
app: helloworld-pod
template:
metadata:
labels:
app: helloworld-pod
spec:
containers:
- name: my-pod
image: zxcvbnius/docker-demo:latest
ports:
- containerPort: 3000
resources:
requests:
cpu: 200m
limits:
cpu: 400m
可以發現,在 spec.resource
的地方多了一個 limits
的欄位,
- spec.resources.limits.cpu該欄位代表,這個 container 最多能使用的 cpu 的資源為
400m 同等於 400milicpu(milicore)
若是透過 kubectl create
創建 hello-deployment
,可以從 Grafana 發現多了 limit ,
除了可以針對 CPU 與 Memory 等計算資源限制之外,也可以限制
- configmaps
- persistentvolumesclaims
- pods
- replicationscontrollers
- resourcequotas
- services
- services.loadbalancer
- secrets
等資源數量上的限制。
如果我們設置的數量超出指定的數量的範圍,Kubernetes 則會回傳 403 FORBIDDEN
提醒我們超出可使用的配置範圍。
Pod 資源限制 QoS
當 Kubernetes
創建一個 Pod
時,它會给 Pod
分配一個 QoS
等級,分為:
- Guaranteed
- Burstable
- BestEffort
Guaranteed
- 要给
Pod
分配QoS
等級為Guaranteed
Pod
裡的每個Container
都必須有memory limit和request,而且必須是一樣的。Pod
裡的每個Container
都必須有CPU limit和request,而且必須是一樣的。- 創建一個
Pod
$ kubectl run nginx --image=nginx --limits cpu=1,memory=200Mi --restart=Never --dry-run=client -o yaml > pod.yaml
$ kubectl apply -f pod.yaml
- 查看
Pod
訊息
kubectl describe po nginx
...
Limits:
cpu: 1
memory: 200Mi
Requests:
cpu: 1
memory: 200Mi
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-68jm7 (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-68jm7:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-68jm7
Optional: false
QoS Class: Guaranteed
- 最後一行顯示
QoS
為Guaranteed
等級,且 limit = request - 如果一個容器配置了cpu / memory limit,但是没有配置 cpu / memory request,那 Kubernetes 會自動给容器分配一個符合cpu/memory limit的request → K8s 為 Pod 提供 的預設 QoS 等級是 Guaranteed
Burstable
- 要给
Pod
分配QoS
等級為Burstable
: - 該
Pod
不滿足QoS
等级Guaranteed
的要求 Pod
裡至少有一個容器有 memory 或 CPU request。
Burstable
apiVersion: v1
kind: Pod
metadata:
name: qos-demo-2
namespace: qos-example
spec:
containers:
- name: qos-demo-2-ctr
image: nginx
resources:
limits:
memory: "200Mi"
requests:
memory: "100Mi"
2 containers Burstable
apiVersion: v1
kind: Pod
metadata:
name: qos-demo-4
namespace: qos-example
spec:
containers:
- name: qos-demo-4-ctr-1
image: nginx
resources:
requests:
memory: "200Mi"
- name: qos-demo-4-ctr-2
image: redis
這個 Pod
滿足了 QoS
等級為 Burstable
的要求。即,不滿足 Guaranteed
的要求,而且其中一個容器有memory request。
BestEffort
- 要给
Pod
分配QoS
等級為BestEffort
Pod
裡的容器必須沒有任何 memory 或者 CPU 的 limit 或 request
BestEffort
apiVersion: v1
kind: Pod
metadata:
name: qos-demo-3
namespace: qos-example
spec:
containers:
- name: qos-demo-3-ctr
image: nginx