Search code examples
kubernetestraefik

Can you forward traffic to a dynamic service using Traefik?


Below is an example IngressRoute.

I would like to have something like this where the first part of the domain would map to a Kubernetes service without having to statically define the service name.

service1.api.test.com -> service1

service2.api.test.com -> service1

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingressroute
  namespace: default
spec:
  entryPoints:
    - web
  routes:
  - match: "HostRegexp(`{subdomain:[a-z]+}.api.test.com`)"
    kind: Rule
    services:
    - name: whoami  # can this be dynamic?
      port: 80

Solution

  • No it's not possible. Because even if you are able to match the host regular expression it will not know under the hood which service the request needs to go to.

    So you will need create two separate matches for different services in the same ingressRoute

    apiVersion: traefik.containo.us/v1alpha1
    kind: IngressRoute
    metadata:
      name: ingressroute
      namespace: default
    spec:
      entryPoints:
        - web
      routes:
      - match: "HostRegexp(`someservice.yourdomain.com`) && PathPrefix(`/`)"
        kind: Rule
        services:
        - name: whoamiV1
          port: 80
      - match: "HostRegexp(`yourdomain.com`,`{subdomain:[a-zA-Z0-9-]+}.yourdomain.com`) &&PathPrefix(`/api/someservice/`)"
        kind: Rule
        services:
        - name: whoamiV2
          port: 80
    

    For more details you can refer the docs