Can I target a K8s service to a Pod without labels?
That is, I have a K8s Pod created with the following configuration.
apiVersion: v1
kind: Pod
metadata:
name: nofrills-first-pod
spec:
containers:
- name: nofrills-container
image: nofrills/to-deploy:0.0.1
ports:
- containerPort: 3000
I would like to expose this pod as a K8s service. Normally, I would do this by creating a Service configuration that looked something like this
apiVersion: v1
kind: Service
metadata:
name: test-nofrills-service
spec:
type: NodePort
selector:
## ?????? no labels to target?
ports:
- protocol: TCP
port: 3000
targetPort: 3000
nodePort: 32525
However, since the pod doesn’t have any labels I don’t know how to tell the Service which pod to use. I suppose another way of asking this questions is "Can a K8s selector target an object without any labels?"
I realize I could (in many scenarios) easily add labels to the Pod — but I’m specifically interested in the abilities of K8s selectors here.
>Solution :
You can define a Service without specifying a selector to match Pods. Because this Service has no selector, the corresponding EndpointSlice (and legacy Endpoints) objects are not created automatically.
You can map the Service to the network address and port where it’s running, by adding an EndpointSlice object manually.