【问题标题】:Is there a way url redirect internally to particular service based on context path?有没有办法 url 根据上下文路径在内部重定向到特定服务?
【发布时间】:2019-11-25 19:41:23
【问题描述】:

在一个集群中运行多个相同的 pod,但命名空间不同。这是在 Kubernetes 中运行的 Web 应用程序。我有网址<HOSTNAME>:<PORT>/context/abc/def/.....。我想根据上下文重定向到特定服务。有没有办法使用入口控制器来实现它?或者有什么方法可以通过入口使用不同的端口来实现它?

如果 URL 是 <HOSTNAME>:<PORT>/abc/def/.....,我的 Web 应用程序可以正常工作。由于我必须使用相同的 URL 访问不同的 pod,因此我正在为其添加上下文。我们还有其他方法可以实现这个用例吗?

【问题讨论】:

    标签: kubernetes multi-tenant kubernetes-ingress nginx-ingress


    【解决方案1】:

    您可以使用rewrite-target 做到这一点。在下面的示例中,我使用了 rewrite.bar.com<HOSTNAME> 值和 <PORT> 的值 80

    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /$2
      name: rewrite
      namespace: default
    spec:
      rules:
      - host: rewrite.bar.com
        http:
          paths:
          - backend:
              serviceName: context-service
              servicePort: 80
            path: /context1(/|$)(.*)
          - backend:
              serviceName: context-service2
              servicePort: 80
            path: /context2(/|$)(.*)       
    

    例如,上面的入口定义将导致以下重写:

    rewrite.bar.com/context1 为上下文 1 服务重写为 rewrite.bar.com/

    rewrite.bar.com/context2 重写为 rewrite.bar.com/ 用于上下文 2 服务。

    rewrite.bar.com/context1/new 为上下文 1 服务重写为 rewrite.bar.com/new

    rewrite.bar.com/context2/new 重写为 rewrite.bar.com/new 用于上下文 2 服务。

    【讨论】:

    • 我已经编辑了我的答案以解决多个后端服务和固定代码块格式。
    • 如果我的 url 包含 host:port/context1/new/abc/def/,这行吗
    • 是的,但是您必须记住正确的servicePorthost 与您使用的主机和端口匹配。因此,例如http://example.com:80/context1/new/abc/def/ 将重定向到http://example.com:80/new/abc/def/ 上与hostexample.com 和targetPort 80 上的context1 标准选择器匹配的服务。
    • 这个解决方案对我不起作用。它没有重定向到 rewrite.bar.com/new
    【解决方案2】:

    您可以通过使用入口的规则配置来管理流量如何指向正确的服务,这是documentation的一个简单示例:

    apiVersion: networking.k8s.io/v1beta1
    kind: Ingress
    metadata:
      name: app-ingress
    spec:
      rules:
      - http:
          paths:
          - path: /abc
            backend:
              serviceName: abc-service
              servicePort: 80
          - path: /context
            backend:
              serviceName: context-service
              servicePort: 80
    

    【讨论】:

    • 我能做到。但我的网址在没有上下文的情况下工作。如果我要添加上下文,我的 api 将无法正常工作。因为我的休息终点发生了变化。有什么方法可以在不添加任何上下文的情况下进行。我只想使用命名空间分离来实现多租户。
    猜你喜欢
    • 2013-11-27
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多