How to make use of Kubernetes port names?

2/20/2018

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.

-- soosap
kubernetes
kubernetes-service

2 Answers

2/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.

-- Mir Shahriar Sabuj
Source: StackOverflow

2/20/2018

kube-dns is a DNS service that uses the same protocol as all the regular DNS servers. In this sense, DNS was not designed to resolve "port names", but domain names (which map to an IP address).

What several people do is to have a reverse proxy that would ProxyPass traffic from one port to another (provided that we are talking about HTTP/HTTPS traffic) https://serverfault.com/questions/85078/how-to-forward-dns-alias-to-hostnameport or use iptables rules https://www.digitalocean.com/community/tutorials/how-to-forward-ports-through-a-linux-gateway-with-iptables. However, these assume that you would forward traffic to a specific port in the first place (for example, 80)

As you wrote in the comment, using environment variables would be the option that fits your case.

-- Javier Salmeron
Source: StackOverflow