In Kubernetes, is it possible to reference a pod by its metadata fields in a service selector?

11/8/2018

I am writing sample YAML files that will serve as examples to bring my coworkers on Kubernetes. This is what my very first "Pod + Service" example looks like so far:

apiVersion: v1
kind: Pod
metadata:
  name: foobar
  labels:
    app: foobar
spec:
  containers:
    image: foobar
    name: foobar
    ports:
    - containerPort: 5000
      protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: foobar
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 5000
  selector:
    app: foobar
  type: LoadBalancer

My point being to provide an example as short and as simple as possible, but still fully functional, I was wondering if the service's spec.selector could use the pod name rather than having to define a label which just repeats the name of the pod.

I have searched quite a bit on Kubernetes GitHub issues, StackOverflow and others, but genuinely did not find any answer other than the Labels and Selectors documentation page which seems to imply, by mostly referring to "label selectors", that only labels can be used in all selectors.

I also tried some random things like spec.selector.name = foobar or, inspired by other features of Kubernetes, spec.selector.metadata.name = foobar, but none of those work, obviously (the service can not find any endpoint).

Also, I've come across a lot of manifests that keep repeating that kind of structure for all their declared resources:

name: foobar
labels:
  name: foobar

I really feel that it would make a lot of sense to be able to use any metadata field in selectors. Am I right to assume that it is not currently possible? If so, what is the rationale?

-- ramnes
kubernetes

1 Answer

11/8/2018

The service is backed by one or more pods that all provide same functionality. Services are automatically configured to load balance the traffic to pods matching the label query. A random algorithm is used and currently is the only option.

When you want to provide the pod name to bind services instead of labels, then the pod name will be unique entity in kubernetes cluster and there will be only single pod with that name. Hence one service will bound with only one pod and effectively losing the services ability to be in front of one or more pods serving the same functionality.

-- Prafull Ladha
Source: StackOverflow