大网数据广告活动
服务器运维问答

How do I create a Kubernetes service that routes traffic to different pods based on the port?

· 52CE 我爱测

I would like to have a Service of LoadBalancer type that points to an nginx on port 80, and point to a separate sshd pod for port 22. However I can't route based on the port with a single selector. The use case I'm going for is s…

问题原文

原帖链接 · Matt · CC BY-SA 4.0

I would like to have a Service of LoadBalancer type that points to an nginx on port 80, and point to a separate sshd pod for port 22. However I can't route based on the port with a single selector.

The use case I'm going for is similar to github.com which accepts traffic to github.com for port 80 as well as 22 for ssh traffic. So DNS would point to a set of k8s loadbalancers in this case that I would assume would route to the appropriate pods per port. So if I'm going at it the wrong way, lemme know. I'm open to other solutions.

What I would like to avoid doing is setting up a separate pod like HAProxy that routes per port.

I looked into using an Ingress, but that is only for HTTP traffic.

An Ingress does not expose arbitrary ports or protocols. Exposing services other than HTTP and HTTPS to the internet typically uses a service of type Service.Type=NodePort or Service.Type=LoadBalancer.

https://kubernetes.io/docs/concepts/services-networking/ingress/

已采纳解答

原帖链接 · Matt · CC BY-SA 4.0

Thanks to @Ivan M. who pointed me in the right direction, I just want to add a code example of the solution here:

First of all, the confusing thing is that the kubernetes documentation lead me down the wrong path thinking that you can't use an ingress for non http traffic. The thing that you have to know about is that you can use a different ingress controller. With the nginx ingress controller, you can proxy arbitrary tcp or even udp traffic.

The second hurdle is that there are two separate repos for the nginx ingress. Those are:

I ended up using the kubernetes/ingress-nginx controller.

nginx-values.yaml

controller:
  service:
    enableHttp: true

tcp:
  "22": "other-namespace/service-name:22"

Then we have the helm install

helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo update
helm -n nginx -f nginx-values.yaml install ingress-nginx ingress-nginx/ingress-nginx

Then I install the Ingress into k8s. Notice the ingressClassName

ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  namespace: nginx
spec:
  ingressClassName: nginx
  defaultBackend:
    service:
      name: my-http-service
      port:
        number: 80

And then you kubectl that bad boy

kubectl apply -f ingress.yaml

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-02-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。