Label Selectors
Label selectors allow you to select a subset of pods or nodes tagged with certain labels and perform an operation on these pods. See section 3.4. of Kubernetes In Action.
The Label Selector is the core grouping primitive in Kubernetes. Label Selectors can have multiple logical AND requirements which are comma-separated.
The API supports two types of selectors: equality and set based.
Note that Node Selector are similar to Label Selectors except that NodeSelectors only allow for one label value to be matched. For more complex node selection, Equality-based requirements affinity should be used. You can label a node with
$ kubectl label nodes <node-name> <label-key>=<label-value>
Equality-based requirements
Supported operators are =, ==, !=
. =
and ==
are the same. E.g., env=production
or tier != frontend
. So, as another variation of this, you can select all objects in production that are not in the frontend tier with env=production,tier!=frontend
.
Set-based requirements
E.g.
environment in (production, qa)
ortier notin (frontend, backend)
.New resources such as Job, Deployment, ReplicaSet and DaemonSet support set-based requirements (and thus
matchLabels
). It doesn’t apply for older resources such as service and ReplicationControllers. Thus,matchLabels
is not allowed in the yaml configuration for these older resource types.
matchLabel
In a yaml configuration, it tells Kubernetes what pods the deployment will apply to.