k8s LimitRange

内容纲要

概述

在之前的文章中,我们写了k8s ResourceQuota的文档,ResourceQuota主要用于团队工程使用一个k8s集群和限制整个集群使用的最大资源以防止集群过载而崩溃。在这篇文章中,我们来看下LimitRange,LimitRange用来限制Pod,Container和PV的资源使用。
在 k8s 中,LimitRange 是用来限制资源使用的一种机制,它设定了 Namespace 内的 Pod 或容器所能使用的资源上下限。它确保在该 Namespace 中创建的每个 Pod 或容器都满足一些限制约束,因为默认Pod可以使用的资源是无限的。
通过ResourceQuota和LimitRange就可以完整定义整个集群资源的使用, ResourceQuota用来定义整体框架性质的数量,LimitRange用来定义框架内资源大小。
k8s 官网对LimitRange的描述如下:

By default, containers run with unbounded compute resources on a Kubernetes cluster. Using Kubernetes resource quotas, administrators (also termed cluster operators) can restrict consumption and creation of cluster resources (such as CPU time, memory, and persistent storage) within a specified namespace. Within a namespace, a Pod can consume as much CPU and memory as is allowed by the ResourceQuotas that apply to that namespace. As a cluster operator, or as a namespace-level administrator, you might also be concerned about making sure that a single object cannot monopolize all available resources within a namespace.

A LimitRange is a policy to constrain the resource allocations (limits and requests) that you can specify for each applicable object kind (such as Pod or PersistentVolumeClaim) in a namespace.

LimitRange类型

  1. Pod
  2. Container
  3. PVC

说明

  1. Pod 或容器的资源请求和限制的默认值: 如果 Pod 或容器没有设定资源请求和限制,LimitRange 可以自动为它们设定默认值。

  2. Pod 或容器的资源请求和限制的最小值和最大值: LimitRange 可以确保 Pod 或容器的资源请求和限制不会低于最小值或超过最大值。

  3. Pod 的最小和最大存储请求: LimitRange 可以确保每个 PersistentVolumeClaim 的存储容量请求不会低于最小值或超过最大值。

LimitRange示例

LimitRange 的定义需要在 YAML 文件中进行。以下是一个 LimitRange 的例子:

apiVersion: v1
kind: LimitRange
metadata:
  name: resource-limits
  namespace: default
spec:
  limits:
  - type: Pod
    max:
      cpu: "2"
      memory: "1Gi"
    min:
      cpu: "200m"
      memory: "6Mi"
  - type: Container
    default:
      cpu: "300m"
      memory: "200Mi"
    defaultRequest:
      cpu: "200m"
      memory: "100Mi"
    max:
      cpu: "2"
      memory: "1Gi"
    min:
      cpu: "100m"
      memory: "4Mi"
  - type: PersistentVolumeClaim
    min:
      storage: "1Gi"
    max:
      storage: "10Gi"

在这个例子中,type: Pod 是对整个 Pod 的限制,type: Container 是对每一个容器的限制。对于没有设定资源请求和限制的容器,会使用 defaultdefaultRequest 中的值。

应用LimitRange

将上面示例中的yaml内容保存到limitrange.yaml文件中,

kubectl apply -f limitrange.yaml

file

查看LimitRange

kubectl get limitrange

kubectl describe limitrange/resource-limits

file

注意

设置了LimitRange后,应用的Pod的HPA对应的CPU,内存和PVC申请的资源数量无法超过LimitRange中定义最大数量,否则会报错。
file

总结

LimitRange是一个很好的Pod资源限制策略,与ResourceQuota共同使用可以达到设置整个集群和命名空间资源使用的目的,防止资源过度使用或者资源浪费。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部