How to make use of Kubernetes port names?

允我心安 提交于 2019-12-08 17:32:05

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/48886837/how-to-make-use-of-kubernetes-port-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!