How to make use of Kubernetes port names?

soosap picture soosap · Feb 20, 2018 · Viewed 13k times · Source

In a kubernetes deployment I specify a port like so:

 containers:
 - name: nginx
   image: nginx:latest
   ports:
    - name: nginx-port
      containerPort: 80
      protocol: TCP

Now in a service I can reference that port like so (allows me to only specify the external port in the service):

spec:
  type: ClusterIP
  ports:
  - name: nginx-port
    port: 80
    targetPort: nginx-port
    protocol: TCP

Now the question, can I reference service and port elsewhere using the following syntax nginx-service.default.svc.cluster.local:nginx-port? You know I can make reference to services using this special names, but I find myself hardcoding the port number like so nginx-service.default.svc.cluster.local:80.

Answer

Shahriar picture Shahriar · Feb 20, 2018

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.