Traefik v2.2 + Docker - define a middleware to be re-used across multiple routers

Is it possible to define a middleware in traefik.toml or dynamic configuration file and re-use it in individual routers (with docker-compose labels)?

This is what I'm currently using:
docker-compose.yml
....
- "traefik.http.middlewares.cf-whitelist.ipwhitelist.sourcerange=173.245.48.0/20, 103.21.244.0/22, ..."
- "traefik.http.routers.example_com.middlewares=cf-whitelist@docker"
....

What I would like to have

traefik.toml
  [http.middlewares]
    [http.middlewares.cf-whitelist.ipWhiteList]
       sourceRange = [
          "173.245.48.0/20",
           "103.21.244.0/22",
            ...
        ]

and reference only the middleware in docker-compose files:
- "traefik.http.routers.example_com.middlewares=cf-whitelist@docker"

This IP list might be due to change, so it would be best to have it managed in a single file.

Middlewares can be defined for an entry point, right? However, that wouldn't probably work as I can only have one entry point for port 443, and I don't want this whitelist to be enabled for every single router on that entry point.

Is defining a global middleware this way possible? Am I doing something wrong here? I have tried adding this middleware to both the static configuration file, and dynamic configuration file and it didn't work for either. It only works if it's defined in docker-compose.

Thank you.

Yes you can. But you will need to reference it with @file if you define it in the file provider.

2 Likes

Thanks for your help!

1 Like