【问题标题】:Kubernetes do I need to include port when directing?Kubernetes 定向时是否需要包含端口?
【发布时间】:2019-11-04 01:35:09
【问题描述】:

我有一个在 K8s 中运行的应用程序。它前面有 3 个微服务和 nginx。 每个重定向首先通过 nginx 并按指定进行代理。 我的烧瓶应用程序在没有端口号的情况下重定向问题。我通过 minikube 在本地运行 k8s。每当我重定向到另一个页面时,url 不包含端口号,这会引发错误。

if usernamedata == None:
    print("Could not log in")   
else:
    if passworddata == password:
        print("Logged in")
        return redirect("/user/{0}".format(username))

Nginx 是唯一暴露的服务,它的 url 是 http://192.168.99.107:31699 通过我在烧瓶中的重定向,我被重定向到http://192.168.99.107/user/David,这使我连接被拒绝。 如果我添加端口号并将其设为http://192.168.99.107:31699/user/David,它可以正常工作。 重定向时是否需要指定端口号?如果服务关闭并重新创建怎么办? 另外,这是我对 nginx 的服务定义:

kind: Service
apiVersion: v1
metadata:
  name: nginx
  labels:
    svc: nginx
spec:
  selector:
    app:  nginx-app
  type: LoadBalancer
  ports:
   - port:  80

如何在烧瓶应用程序中进行重定向?

【问题讨论】:

  • 您是否在 minikube 中正确设置了负载均衡器? $ minikube service nginx --url 返回什么?
  • 它返回http://192.168.99.107:31699
  • 您的高端口号是由 Kubernetes 动态(随机)设置的,因为您没有明确指定它。有关如何设置,请参阅下面的答案。

标签: nginx flask kubernetes


【解决方案1】:

如果服务关闭并重新创建,并且您希望为您的服务保留相同的高端口号,您需要指定 nodePort 并将服务类型更改为 NodePort

apiVersion: v1
kind: Service
metadata:
  name: my-service
  labels:
    svc: nginx
spec:
  type: NodePort # type is set to NodePort
  ports:
  - port: 80 # Service's internal cluster IP
    targetPort: 80 # target port of the backing pods
    nodePort: 31699 # service will be only available via this port for each cluster node if recreated
  selector:
    app:  nginx-app

在您的 Python 代码中(如果 Service 在 Pod 之前启动):

import os 

...
service_host = os.environ.get("NGINX_SERVICE_HOST")
service_port = os.environ.get("NGINX_SERVICE_PORT")
...
redirect(f"http://{service_host}:{service_port}/user/{username}")

【讨论】:

  • 那么在烧瓶中我是否也需要明确指定端口?
  • 是的,您的选择:硬编码、通过环境变量传递、向下 API 或查询内部 DNS。
  • 那么我应该在return redirect("/user/{0}".format(username)) 的哪里添加端口?在开头添加它会导致我被重定向到http://192.168.99.107/31699/user/david
  • 抱歉,不确定我是否理解您的问题。不能做redirect("http://192.168.99.107:31699/user/{0}".format(username)) 吗?您也可以尝试通过 DNS 名称而不是 IP 地址重定向,即http://nginx?
  • redirect("http://192.168.99.107:31699/user/{0}".format(username)) 有效,但对我来说不是理想的解决方案。感谢您的帮助,我将暂时保留它,并在我更好地了解 k8s 后尝试更多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2022-07-06
  • 2011-04-17
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
相关资源
最近更新 更多