Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kubernetes, how does one select a pod by name in a service selector?

I am looking to spin up a specific number of pods that are independent and not load balanced. (The intent is to use these to send and receive certain traffic to and from some external endpoint.) The way I am planning to do this is to create the pods explicitly (yaml snippet as below)

    apiVersion: v1
    kind: Pod
    metadata:
      name: generator-agent-pod-1
      labels:
        app: generator-agent
        version: v1
    spec:
      containers:
        ...

(In this, the name will be auto-generated as generator-agent-pod-1, generator-agent-pod-2, etc.)

I am then looking to create one service per pod: so essentially, there'll be a generator-agent-service-1, generator-agent-service-2, etc., and so I can then use the service to be able to reach the pod from outside.

I now have two questions: 1. In the service, how do I select a specific pod by name (instead of by labels)? something equivalent to:

apiVersion: v1
kind: Service
metadata:
  name: generator-agent-service-1
  labels:
    app: agent-service
spec:
  type: NodePort
  ports:
  - port: 8085
    protocol: TCP
  selector:
    metadata.name: generator-agent-pod-1

(This service does not get any endpoints, so the selector is incorrect, I suppose.)

  1. Is there a better way to approach this problem (Kubernetes or otherwise)?

Thanks!

like image 329
Srinivas Avatar asked Mar 03 '23 20:03

Srinivas


1 Answers

I think you are using StatefulSet for controlling Pods. If so, you can use label statefulset.kubernetes.io/pod-name to select pods in a service.

For illustration:

apiVersion: v1
kind: Service
metadata:
  name: generator-agent-service-1
  labels:
    app: agent-service
spec:
  type: NodePort
  ports:
  - port: 8085
    protocol: TCP
  selector:
    statefulset.kubernetes.io/pod-name: generator-agent-pod-1
like image 139
DoroCoder Avatar answered Mar 05 '23 16:03

DoroCoder