Traefik Segments #
A true power feature and usually under estimated: (almost) everything with Traefik can be done using labels.
As an application grows, the use of a lot of labels can result in your compose/stack files getter longer (and wider) and they feel a bit messy over time.
A solution to stay on top and to improve readability can be to break up the labels (and rules) into multiple segments. Each segment has a name, hopefully telling future you what is going on.
Example #
Consider the following example:
- one service
- multiple domains are mapped on the service
- for SEO we want to redirect all domains to the final domain
service:
app:
image: example/app:v1.0.0
deploy:
labels:
- traefik.enable=true
- traefik.docker.network=public
- traefik.port=80
- traefik.frontend.rule='Host:example.org,foo.example.org,bar.example.org,www.example.org,another-domain.org'
- traefik.frontend.redirect.regex='https://((foo|bar).example.org|another-domain.org)/(.*)'
- traefik.frontend.redirect.replacement='https://example.org/$${2}'
Our example uses only five hosts for brevity — consider that there could be a lot more rules.
In order to improve readability and maintainability, we can use multiple segments (or categories):
- a segment called
sub-domains
to redirectfoo.example.org
,bar.example.org
andwww.example.org
- a segment called
another
to redirectanother-domain.org
- a segment called
www
for the default
service:
app:
image: example/app:v1.0.0
deploy:
labels:
- traefik.enable=true
- traefik.docker.network=public
- traefik.sub-domains.frontend.rule='Host:foo.example.org,bar.example.org,www.example.org'
- traefik.sub-domains.frontend.redirect.regex='https://(.*).example.org/(.*)'
- traefik.sub-domains.frontend.redirect.replacement='https://example.org/$${2}'
- traefik.sub-domains.port=80
- traefik.another.frontend.rule='Host:another-domain.org`
- traefik.another.frontend.redirect.regex='https://another-domain.org/(.*)'
- traefik.another.frontend.redirect.replacement='https://example.org/$${1}'
- traefik.another.port=80
- traefik.www.frontend.rule='Host:example.org'
- traefik.www.port=80
This is slightly longer, but a lot more readable and extensible. The segments will show up as individual services on your Traefik dashboard. There are virtually no limits to the number of segments a service can have, but consider that adding each segment also has to be maintained by your Traefik loadbalancer.