Review Kubernetes Service targets and port mapping

Check selectors, ready Pods and the application’s actual listening port together.

Description

A Service with a selector routes traffic to Pods with matching labels in its namespace. A Service without a selector can use separately managed EndpointSlices.

Potential impact

Requests can fail even when the Service exists if it has no ready backend or the application does not listen on the targetPort.

Remediation

  • Compare the Service selector with the actual Pod labels. For a Deployment, check the labels on its Pod template.
  • Set targetPort to the application’s listening port number or its declared port name. Check the targets and readiness in EndpointSlices, then test a connection through the Service.

Examples

Both examples use targetPort: 9377. nginx listens on port 80 by default. Configure nginx to listen on 9377 or set targetPort to 80.

Before

yaml
apiVersion: v1
kind: Service
metadata:
  name: helloworld
spec:
  selector:
    app: helloworld
  ports:
    - port: 9377
      targetPort: 9377
---
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: different-label
spec:
  containers:
    - name: nginx
      image: nginx
      ports:
        - containerPort: 9377

The Pod labeled app: different-label is excluded. Check for other matching Pods in the namespace.

After

yaml
apiVersion: v1
kind: Service
metadata:
  name: helloworld
spec:
  selector:
    app: helloworld
  ports:
    - port: 9377
      targetPort: 9377
---
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: helloworld
spec:
  containers:
    - name: nginx
      image: nginx
      ports:
        - containerPort: 9377

app: helloworld matches the selector. Declaring containerPort: 9377 still does not change where nginx listens.

References