亲和性和反亲和性
node 亲和性
node亲和性策略表示pod部署到符合某些条件的node上.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels:
app: nginx
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: name
operator: In
values:
- nginx1
- nginx2
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: app
operator: In
values:
- nginx
containers:
- name: nginx-server
image: nginx:latest
上面的这个例子表示pod必须部署到满足nodeSelectorTerms中的条件,尽量满足preference中的条件.
- nodeAffinity表示pod和node的亲和性策略
- nodeSelectorTerms 表示打了这些标签的node上才能部署pod,这里的key values都可以指定多个值,可以实现类似nodeSelector的或的操作.
- preference 表示最好部署到满足这些条件的node上.
策略
requiredDuringSchedulingIgnoredDuringExecution 硬策略表示调度过程必须满足执行过程忽略
preferredDuringSchedulingIgnoredDuringExecution 软策略表示调度过程尽量满足执行过程忽略
表达式
label 的值可选的操作符有:
- In:label 的值在某个列表中
- NotIn:label 的值不在某个列表中
- Exists:某个 label 存在
- DoesNotExist: 某个 label 不存在
- Gt:label 的值大于某个值(字符串比较)
- Lt:label 的值小于某个值(字符串比较
pod 亲和性和非亲和性
pod亲和性和非亲和性表示pod部署到或不部署到满足某些label的pod所在的node上.
- 使用pod非亲和性硬策略,实现相同lable pod一定不能调度到同一节点
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels:
app: nginx
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- nginx
topologyKey: "kubernetes.io/hostname"
containers:
- name: nginx-server
image: nginx:latest
- podAntiAffinity 表示pod的非亲和性策略
- matchExpressions 表示符合label条件的pod
- topologyKey 表示作用域key,这里使用 kubernetes.io/hostname表示所有的节点,因为所有的节点默认都会打上这个标签
这个例子表示所有有app:nginx标签的pod非亲和性,就是不能部署在同一节点,并且在调度过程中是硬策略.
- 使用pod非亲和性软策略实现相同label pod尽量不要调度到同一节点
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels:
app: nginx
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
nodeSelector:
app: nginx
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- nginx
topologyKey: kubernetes.io/hostname
containers:
- name: nginx
image: nginx
- podAntiAffinity 亲和性策略
表示尽量把有label app:nginx的pod部署在同一节点