Labels in Deployment Spec & template

7/27/2021

In the below yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  labels:
    app: my-nginx # Line 6
spec:             # Line 7  
  replicas: 2
  selector:
    matchLabels:
      app: my-nginx    # line 11
  template:
    metadata:
      labels:
        app: my-nginx   # Line 15
    spec:                # Line 16
      containers:
      - name: my-nginx
        image: nginx:alpine
        ports:
        - containerPort: 80
        resources:
          limits:
            memory: "128Mi" #128 MB
            cpu: "200m" #200 millicpu (.2 cpu or 20% of the cpu)

Deployment is given a label(app: nginx) at Line 6.

Deployment spec at Line 7 uses the Pod spec mentioned in Line 16


1) What is the purpose of selector field with matchLabels?

2) What is the purpose of template field with labels?

-- overexchange
kubernetes
kubernetes-pod

1 Answer

7/27/2021

Tried to add comments to explain the role of labels:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  labels:
    app: my-nginx # LABEL-A: <--this label is to manage the deployment itself. this may be used to filter the deployment based on this label. 
spec:              
  replicas: 2
  selector:
    matchLabels:
      app: my-nginx    #LABEL-B:  <--  field defines how the Deployment finds which Pods to manage.
  template:
    metadata:
      labels:
        app: my-nginx   #LABEL-C: <--this is the label of the pod, this must be same as LABEL-B
    spec:                
      containers:
      - name: my-nginx
        image: nginx:alpine
        ports:
        - containerPort: 80
        resources:
          limits:
            memory: "128Mi" #128 MB
            cpu: "200m" #200 millicpu (.2 cpu or 20% of the cpu)

LABEL-A: <--this label is to manage the deployment itself. this may be used to filter the deployment based on this label. Example usage of LABEL-A is for deployment management, such as filtering.

k get deployments.apps -L app=my-nginx

LABEL-B: <-- There must be some place where we tell replication controller to manage the pods. This field defines how the Deployment finds which Pods to manage. Based on these labels of the pod, replication controller ensure they are ready.

LABEL-C: <--this is the label of the pod, which LABEL-B use to monitor. this must be same as LABEL-B

-- P....
Source: StackOverflow