Labels are created under the metadata section
apiVersion: V1
kind: Pod
metadata:
name: simple-app
labels:
app: my-app
function: front-end
version: 1.0
spec:
containers:
- name: my-web-app
image: my-web-app-nginx
ports:
-containerPort: 8080
In the above example, you can reference this pod by using any of the 3 labels specified:
kubectl get po --show-labels
kubectl get pods --selector app=my-app
This will select all the pods that have an app label with the value set to my-app
kubectl label po nginx2 app=v2 --overwrite
kubectl get po -L app
# or
kubectl get po --label-columns=app
kubectl get po -l app=v2
# or
kubectl get po -l 'app in (v2)'
# or
kubectl get po --selector=app=v2
In this example, any pod with the label of app: App1 will be part of the replica set and will have a min of 3 pods created. This is found under the selectors section or the definition
Note: The name and labels under the replicaSet Metadata section are ONLY for the ReplicaSet, not for the actual pods created for the ReplicaSet.
When the pods are created, they will be labeled with the information found under the template:metadata section and use the spec under the template section.
apiVersion: v1
kind: RepliaSet
metadata:
name: simple-webapp
labels:
app: App1
function: Front-end
spec:
replicas: 3
selectors:
matchLabels:
app: App1
template:
metadata:
labels:
app: App1
function: Front-end
spec:
containers:
- name: simple-webapp
image: simple-webapp
Newer resources, such as Job, Deployment, ReplicaSet, and DaemonSet, support set-based requirements as well.
selector:
matchLabels:
component: redis
matchExpressions:
- {key: tier, operator: In, values: [cache]}
- {key: environment, operator: NotIn, values: [dev, test]}
matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is “key”, the operator is “In”, and the values array contains only “value”. matchExpressions is a list of pod selector requirements.
The values set must be non-empty in the case of In and NotIn. All of the requirements, from both matchLabels and matchExpressions are ANDed together – they must all be satisfied in order to match.
Selectors are also used in things like services and network policies and can be applied to specific pods utilizing the selector section.
apiVersion: v1
kind: Service
metadata:
name: my-service
labels:
function: Service
spec:
selector:
app: App1 #this will apply this service to all pods that are labeled "app: App1"
ports:
- protocol: TCP
port: 8080
targetPort: 9376
Annotations can provide additional information about the running of the pod
apiVersion: v1
kind: RepliaSet
metadata:
name: simple-webapp
labels:
app: App1
function: Front-end
annotations:
build version: 1.34
spec:
replicas: 3
selectors:
matchLabels:
app: App1
template:
metadata:
labels:
app: App1
function: Front-end
spec:
containers:
- name: simple-webapp
image: simple-webapp