Newbie question about labels

This is my first foray in this forum so apologies if you consider a beginner’s question inappropriate. But if this is the case, please let me know where are the suitable forums for us to learn.

I am looking at an example provided during some Kubernetes training and I see too many labels here:

apiVersion: v1
kind: Service
metadata:
  name: my-stateful-set
  labels:
    **app: my-stateful-set**
spec:
  ports:
    - port: 80
  clusterIP: None
  selector:
    **app: my-stateful-set**
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: my-stateful-set
spec:
  serviceName: my-stateful-set
  replicas: 3
  selector:
    matchLabels:
      **app: my-stateful-set**
  template:
    metadata:
      labels:
        app: my-stateful-set
    spec:
      terminationGracePeriodSeconds: 0
    [...rest omitted for brevity...]

This is what I understood:

  1. Service.metadata.labels.app - is the label we give to the service so we can group/find similar services
  2. Service.spec.selector.app - apps with this label will be linked to the service my-stateful-set
  3. StatefulSet.spec.serviceName - specifies by (unique) name the service to bind to each pod created
  4. StatefulSet.spec.selector.matchLabels.app - what is this label needed for?
  5. StatefulSet.spec.template.metadata.labels.app - what is this label needed for?

Also, given point 3, why would you need a label in the service specification if the service name has been unambiguously specified through serviceName in the stateful set?

@QuietRanger, if I’m not wrong, when you define specs in Service resources you are setting up the pod configuration. So, the Service.spec.selector.app is the label of your pod.

Thank you for your reply @rafamttz! Indeed that is what I understand too. I believe that any pod that contains that label would be bound to that service.

However, I am getting confused with the entry StatefulSet.spec.serviceName as the value assigned to it seems to name a specific service. This would imply that the control pane no longer needs to check labels: it already knows which service should be bound to the pod.

You can have many Services which are mapped to different or the same pods, pods from the same or different application etc.

This spec.ServiceName is for Headless services where you need to connect to the pod directly via dns name. This field will be used to create an internal domain name. Doc: StatefulSets - Kubernetes

1 Like