How to make use of Kubernetes port names?

Kubernetes DNS service provides SRV records for all named ports of services using below format

_my-port-name._my-port-protocol.my-svc.my-namespace.svc.cluster-domain.example

In your case, you should be able to access it by querying below domain

_nginx-port._tcp.nginx-service.default.svc.cluster.local

Example

nslookup -type=SRV _nginx-port._tcp.nginx-service.default.svc.cluster.local

And the result:

_nginx-port._tcp.nginx-service.default.svc.cluster.local   service = 0 100 80 nginx-service.default.svc.cluster.local.

In the above output, nginx-service.default.svc.cluster.local is the target domain and 80 is the target port that you should connect to, i.e. nginx-service.default.svc.cluster.local:80


No. You can't use port name instead of port number. Name field in ServicePort has different purpose.

All ports within a ServiceSpec must have unique names. This name maps to the 'Name' field in EndpointPort objects.

For each Service, one Endpoint object is generated. Every port of that Endpoint corresponds to a Service port. Name field in both ServicePort and EndpointPort is used for this matching.


Usually, you refer to a target port by its number. But you can give a specific name to each pod`s port and refer to this name in your service specification.

This will make your service clearer. Here a small example:

apiVersion: v1
kind: Pod
metadata:
  name: named-port-pod
  labels:
    app: named-port-pod
spec:
  containers:
    - name: echoserver
      image: gcr.io/google_containers/echoserver:1.4
      ports:
      - name: pod-custom-port
        containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: named-port-svc
spec:
  ports:
    - port: 80
      targetPort: pod-custom-port
  selector:
    app: named-port-pod