'Traefik 2.0 and Docker set middleware without naming the router

I'm using traefik 2.0 with docker provider (swarm mode) and I wish to provide a default way for services publishing themselves on traefik avoiding conflicts.

I managed to create a default rule matching my needs, but I'm now struggling because I don't see a way to provide a default middleware to strip away prefixes.

Is there a way to add a docker service label without having to provide a specific router name, but still adding a middleware to whatever router was implicitly created by traefik? Or is there a way to define a default middleware as there is for the default rule?

The solution I'm trying to approach is to remove all the variable substitutions in the following labels, thus reducing the verbosity of the whole definition but without exposing myself to naming conflicts:

        - traefik.enable=true
        - traefik.http.services.${ENV:-dev}_${STACK}_whoami.loadbalancer.server.port=80
        - traefik.http.middlewares.${ENV:-dev}_${STACK}_whoami.stripprefix.prefixes=/${STACK}
        - traefik.http.routers.${ENV:-dev}_${STACK}_whoami.entrypoints=http
        - traefik.http.routers.${ENV:-dev}_${STACK}_whoami.rule=PathPrefix(`/${STACK}/whoami`)
        - traefik.http.routers.${ENV:-dev}_${STACK}_whoami.middlewares=${ENV:-dev}_${STACK}_whoami@docker

Hoping it could become something like the following, where default is the magic word for using the implicit service name assigned by Docker when deploying the stack:

        - traefik.enable=true
        - traefik.http.services.default.loadbalancer.server.port=80
        - traefik.http.middlewares.default.stripprefix.prefixes=/${STACK}
        - traefik.http.routers.default.entrypoints=http
        - traefik.http.routers.default.rule=PathPrefix(`/${STACK}/whoami`)
        - traefik.http.routers.default.middlewares=default@docker

I tried the following, but apparently the go template doesn't get replaced:

        - traefik.enable=true
        - traefik.http.services.{{ .Name }}.loadbalancer.server.port=80
        - traefik.http.middlewares.{{ .Name }}.stripprefix.prefixes=/${STACK}
        - traefik.http.routers.{{ .Name }}.entrypoints=http
        - traefik.http.routers.{{ .Name }}.rule=PathPrefix(`/${STACK}/whoami`)
        - traefik.http.routers.{{ .Name }}.middlewares={{ .Name }}@docker


Solution 1:[1]

I didn't tested it but according to this doc, Go templating is only supported in dynamic (Yaml/Toml) configuration file.

So I suggest you try to add a dynamic configuration file (see here) and write something like :

http:
  routers:
    {{range $i, $e := until 100 }}
    router{{ $e }}:
      middlewares = {{ $e }}
    {{end}}

Hopes this can help

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corentin Jacquet