mjwrazor
mjwrazor

Reputation: 1964

How to use NodeSelector in kubernetes

The example code given in the documentation doesn't state which items it can be used on. Can you use node selector on deployments/statefulsets/persistentvolumes? Also when I put the node Selector under

.spec.nodeSelector as such

spec:
  nodeSelector:
    workload: node-selector-app

I get a validation error when attempting a dry run of the deployment/statefulset/persistentvolume. So can nodeSelector only be used on Pods?

Upvotes: 1

Views: 9573

Answers (1)

Arghya Sadhu
Arghya Sadhu

Reputation: 44559

nodeSelector can not be used in persistentVolumes.nodeSelector should be in the spec section of pod template. Example of deployment using nodeSelector

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
      nodeSelector:
        workload: node-selector-app

With persistentVolume you can use nodeAffinity

kubectl explain persistentVolume.spec.nodeAffinity
KIND:     PersistentVolume
VERSION:  v1

RESOURCE: nodeAffinity <Object>

DESCRIPTION:
     NodeAffinity defines constraints that limit what nodes this volume can be
     accessed from. This field influences the scheduling of pods that use this
     volume.

     VolumeNodeAffinity defines constraints that limit what nodes this volume
     can be accessed from.

FIELDS:
   required <Object>
     Required specifies hard node constraints that must be met.

An example:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: example-local-pv
spec:
  capacity:
    storage: 500Gi
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /mnt/disks/vol1
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - my-node

Upvotes: 4

Related Questions