How is a service connected to a pod? In yaml, what fields need to match between service and pod?

3/29/2021

When creating a Kubernetes service, I'm trying to understand what fields in the YAML service definition need to match to a PODs definition.

For example, given the service:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx-selector
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

What field in the Pod definition needs to say nginx-selector. I think it's the field I've labeled (metadata.labels.app = nginx-selector).

So given this Pod definition

apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: nginx-selector
spec:
  containers:
    - name: myapp
      image: pats2265/myapp
      labels:
        app: does-this-matter
      ports:
        - containerPort: 8080

So many examples use names that are identical between several fields so I wanted a trivial example to spell it out.

This was a good diagram: enter image description here Taken from https://matthewpalmer.net/kubernetes-app-developer/articles/service-kubernetes-example-tutorial.html

But it didn't show the corresponding Pod definition.

Searches came up with this question:

-- PatS
kubernetes

1 Answer

3/29/2021

You are right...its the label of pod which should match with selector defined in service. Check this link for more understanding- https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/

-- subudear
Source: StackOverflow