Перейти к основному содержимому
  • Урок 8 из 18

Планирование: ресурсы и размещение

После урока вы сможете

  • Задать requests/limits и понять классы QoS
  • Использовать nodeSelector, affinity и taints/tolerations
  • Разложить реплики по зонам через topology spread

Как scheduler выбирает узел​

  1. Filtering — отбросить узлы, где Pod не помещается (ресурсы, taints, affinity hard).
  2. Scoring — выбрать лучший из оставшихся (баланс загрузки, topology soft).
  3. Binding — записать spec.nodeName через API.
kubectl get pods -o wide
kubectl describe pod POD_NAME | sed -n '/Events/,$p'
kubectl get nodes --show-labels
kubectl get nodes --show-labels

requests и limits​

apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: ghcr.io/example/api:1.4.2
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 1
memory: 512Mi

Единицы:

РесурсПримеры
CPU100m = 0.1 ядра, 1 = 1 ядро
Memory256Mi, 1Gi
kubectl describe node NODE | sed -n '/Allocated resources/,/Events/p'
kubectl top nodes
kubectl top pods

LimitRange и ResourceQuota​

apiVersion: v1
kind: LimitRange
metadata:
name: defaults
namespace: shop
spec:
limits:
- type: Container
defaultRequest:
cpu: 100m
memory: 128Mi
default:
cpu: 500m
memory: 256Mi
max:
cpu: "2"
memory: 2Gi
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-quota
namespace: shop
spec:
hard:
requests.cpu: "8"
requests.memory: 16Gi
limits.cpu: "16"
limits.memory: 32Gi
pods: "40"

QoS-классы​

Kubernetes вычисляет QoS по соотношению requests/limits:

QoSУсловиеПри выселении
Guaranteedrequests == limits по CPU и memory для всех контейнеровПоследними
BurstableЕсть requests, но не GuaranteedСредний приоритет
BestEffortНет requests/limitsПервыми под нож
# Guaranteed
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 500m
memory: 512Mi
kubectl get pod api-xxx -o jsonpath='{.status.qosClass}{"\n"}'

nodeSelector​

Простейшая привязка к меткам узла:

spec:
nodeSelector:
disktype: ssd
node.kubernetes.io/instance-type: m5.large
kubectl label node worker-1 disktype=ssd
kubectl get nodes -l disktype=ssd

Affinity и anti-affinity​

Node affinity​

apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values: ["eu-central-1a", "eu-central-1b"]
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 80
preference:
matchExpressions:
- key: node-type
operator: In
values: ["compute"]
containers:
- name: api
image: ghcr.io/example/api:1.4.2
resources:
requests:
cpu: 200m
memory: 256Mi
ТипСмысл
requiredDuringScheduling...Hard: иначе Pending
preferredDuringScheduling...Soft: желательно

IgnoredDuringExecution — после старта правила не выселяют Pod при смене labels (для этого нужны другие механизмы).

Pod anti-affinity — разнести реплики​

affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: api
topologyKey: kubernetes.io/hostname

Так две реплики api не окажутся на одном узле (если узлов хватает). Soft-вариант с preferred... гибче для маленьких кластеров.

affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: api
topologyKey: kubernetes.io/hostname

Taints и tolerations​

kubectl taint nodes gpu-1 dedicated=gpu:NoSchedule
kubectl taint nodes gpu-1 dedicated=gpu:NoSchedule-
apiVersion: v1
kind: Pod
metadata:
name: train
spec:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
nodeSelector:
accelerator: nvidia
containers:
- name: train
image: ghcr.io/example/trainer:2.0.0
resources:
requests:
nvidia.com/gpu: 1
limits:
nvidia.com/gpu: 1
EffectПоведение
NoScheduleНовые Pod без toleration не ставятся
PreferNoScheduleSoft
NoExecuteСуществующие без toleration выселяются

Системные taints: node.kubernetes.io/not-ready, unreachable, disk-pressure…

kubectl describe node NODE | grep -A5 Taints

Topology spread constraints​

Разложить Pod равномерно по зонам / хостам:

apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 6
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: api
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: api
containers:
- name: api
image: ghcr.io/example/api:1.4.2
resources:
requests:
cpu: 100m
memory: 128Mi
ПолеСмысл
maxSkewДопустимый перекос между доменами
topologyKeyКлюч метки узла (zone, hostname…)
whenUnsatisfiableDoNotSchedule или ScheduleAnyway
kubectl get nodes -L topology.kubernetes.io/zone
kubectl get pods -l app=api -o wide

PriorityClass​

apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: high-priority
value: 100000
globalDefault: false
description: "Critical user-facing services"
spec:
priorityClassName: high-priority

Высокий приоритет помогает при вытеснении (preemption), когда места нет. Подробнее вместе с PDB — в уроке DaemonSet/Priority.

Полный пример «аккуратного» Deployment​

apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout
namespace: shop
spec:
replicas: 4
selector:
matchLabels:
app: checkout
template:
metadata:
labels:
app: checkout
tier: backend
spec:
priorityClassName: high-priority
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: checkout
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: checkout
topologyKey: kubernetes.io/hostname
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: node-pool
operator: In
values: ["general"]
tolerations:
- key: "node-pool"
operator: "Equal"
value: "general"
effect: "NoSchedule"
containers:
- name: checkout
image: ghcr.io/example/checkout:3.1.0
resources:
requests:
cpu: 300m
memory: 384Mi
limits:
cpu: "1"
memory: 768Mi
readinessProbe:
httpGet:
path: /readyz
port: 8080

Диагностика Pending​

kubectl describe pod PENDING_POD
kubectl get events -n shop --field-selector reason=FailedScheduling
kubectl describe node | grep -E 'Name:|Taints:|Allocatable:|Allocated'

Частые причины:

Events / симптомЧто проверить
Insufficient cpu/memoryrequests vs свободные ресурсы
didn't tolerate tainttolerations
node affinity mismatchlabels узлов
PVC not boundWaitForFirstConsumer + зона
maxSkew unsatisfiabletopology / число доменов
# Сколько реально «забронировано»
kubectl describe node NODE_NAME | sed -n '/Allocated resources/,/Events/p'
kubectl describe pod

Практические правила​

  1. Всегда задавайте requests; limits — осознанно (особенно memory).
  2. Для HA: topology spread по zone + soft anti-affinity по hostname.
  3. Taints — для выделенных пулов (GPU, ingress, system).
  4. Hard affinity в маленьком кластере легко приводит к Pending — начинайте с soft.
  5. Смотрите kubectl describe Events, не гадайте.

Чем requests отличается от limits при планировании и рантайме?

Чеклист готовности​

Я уверенно умею

0 / 3 выполнено

Дочитали до конца?

Отметьте урок пройденным — так проще вернуться туда, где остановились.

Kubernetes и k3s: 0 из 18