Kubernetes Ingress ROOT Path to Different Service

Viewed 3180

I would like to route certain paths of my host to a different backend.

Assuming I have 2 backend services:

  • backend-one
  • backend-two

All of the requests were routed to backend-one initially, like in the example below.

rules:
    - host: example.com
      http:
        paths:
          - path: /
            backend:
              serviceName: backend-one
              servicePort: 3000

Now, I have backend-two as the new service, which should be serving content for specific paths, but most importantly the / (root) page as well.

So, my goal would be the following:

  • Paths /, /abc, /xyz, /12345 to be served by ====> backend-two (the new service).
  • Everything else to be served by backend-one the old service.

What would be the simplest approach for achieving this?

1 Answers

As per Kubernetes CHANGELOG-1.18.md:

In Kubernetes 1.18, there are two significant additions to Ingress: A new pathType field and a new IngressClass resource. The pathType field allows specifying how paths should be matched. In addition to the default ImplementationSpecific type, there are new Exact and Prefix path types.

You can use Kubernetes 1.18+ with Path types to achieve what you want. Use the following config:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress
spec:
  rules:
  - host: example.com
    http:
      paths:
      # Proxy to backend-two when the request is EXACT the root path
      - path: /
        pathType: Exact
        backend:
          serviceName: backend-two
          servicePort: 3000
      # Proxy specic paths (including subpaths) to backend-two
      - path: /abc
        pathType: Prefix
        backend:
          serviceName: backend-two
          servicePort: 3000
      - path: /xyz
        pathType: Prefix
        backend:
          serviceName: backend-two
          servicePort: 3000
      - path: /12345
        pathType: Prefix
        backend:
          serviceName: backend-two
          servicePort: 3000
      # If no rules above match, Proxy to backend-one
      - path: /
        pathType: Prefix
        backend:
          serviceName: backend-one
          servicePort: 3000

Remember that you can also use Regular Expressions to improve your Ingress config in case you have multiple paths to handle.

Related