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 finds matching Pods in the same namespace and forwards traffic to them. A selector that does not match actual Pod labels, or a targetPort that differs from the application’s listening port, can prevent connections.

Declaring containerPort does not make an application listen on that port. Services without selectors can validly use separately managed EndpointSlices, so check the actual connection design.

Potential impact

  • Requests can fail when no ready target exists or traffic reaches the wrong port.
  • A Service can exist while its application does not respond, complicating diagnosis.

Remediation

  • Check the Service selector against actual Pod labels in the same namespace. For Pods created by a Deployment or another controller, check the template labels.
  • Match targetPort to the actual listening port number or a declared port name. Check EndpointSlice targets and readiness, and test actual connectivity.

Examples

The existing examples compare Pod labels. nginx listens on port 80 by default; declaring containerPort: 9377 does not change that. Configure the application to listen on 9377 or match targetPort to its actual port.

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 selector does not match this Pod’s labels, so this Pod is not selected. Check whether other matching Pods exist.

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

The labels now let the Service select this Pod. Readiness and the actual listening port still need to be verified.

References