Search code examples
kubernetestraefiktraefik-ingress

Traefik Ingress match uri prefix and route to a path in the backend k8s service


I have traefik v1.7 installed and I am very new to it. I have 3 microservices, that have to be available for external traffic.

The 3 microservices are M1 (being the UI), M2, M3. Each of these microservices have their own k8s deployment and service. M1 is up on 80 port, M2 on port 8000 and M3 on port 5000. M1, which is the UI responds on "/" path, M2 responds on "/api" and M3 also responds on "/api" path. Both M2 and M3 is not listening on "/" path.

So,

mytest.com/ -> Should go to M1 at "/"
mytest.com/api -> Should go to M2 at "/api"
mytest.com/foo -> Should go to M3 at "/api"

How do I go about writing the Traefik Ingress file for this? I have the below as of now but I am confused about what to do for M3..

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.frontend.rule.type: PathPrefixStrip
spec:
  rules:
  - host: mytest.com
    http:
      paths:
      - path: /
        backend:
          serviceName: M1
          servicePort: 80
      - path: /api
        backend:
          serviceName: M2
          servicePort: 8000
      - path: /foo ## Not sure what to do here..?
        backend:
          serviceName: M3
          servicePort: 5000

Solution

  • So after @larsks recommendation I re-installed traefik using the "traefik-helm-chart-23.0.1" helm chart. I was able to get my requirement working using the below middleware and IngressRoute. I also deployed the traefik whoami service (I am treating this as M1 in my example) just to make sure PathPrefix works as intended.

    apiVersion: traefik.io/v1alpha1
    kind: Middleware
    metadata:
      name: test-replacepath-m2
    spec:
      replacePath:
        path: /api
    
    ---  
    apiVersion: traefik.io/v1alpha1
    kind: Middleware
    metadata:
      name: test-replacepath-m3
    spec:
      replacePath:
        path: /api
    ---
    
    apiVersion: traefik.containo.us/v1alpha1
    kind: IngressRoute
    metadata:
      name: test-ingress
      namespace: default
    spec:
      entryPoints:
        - web
        - websecure
    routes:
    - match: Host(`mytest.com`) && PathPrefix(`/whoami-app-api`)
      kind: Rule
      services:
      - name: whoami
        port: 80
    - match: Host(`mytest.com`) && PathPrefix(`/api`)
      kind: Rule
      services:
      - name: M2
        port: 8000
      middlewares:
      - name: test-replacepath-m2
    - match: Host(`mytest.com`) && PathPrefix(`/foo`)
      kind: Rule
      services:
      - name: M3
        port: 5000
      middlewares:
      - name: test-replacepath-m2