Configuring Traefik for hostname and path-based routing in Docker Swarm

Hey everyone, I’m stuck with Traefik setup in my Docker Swarm cluster. I’ve got it working for hostname-based routing, but I’m trying to add path-based routing too. Here’s what I’ve done so far:

docker service create \
  --label "traefik.port=8080" \
  --label "traefik.docker.network=proxy-net" \
  --label "traefik.frontend.rule=Host:example.com" \
  --label="traefik.backend=myapp" \
  --constraint "node.role == manager" \
  -p 8080:8080 \
  --mount "type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock" \
  --name myapp \
  myapp/myapp

This works fine for http://example.com, but I want to access it at http://example.com/myapp. I know it’s possible with a toml file, but I’m using Docker labels. Any ideas on how to combine hostname and path rules in Traefik labels? Thanks!

hey mate, i had the same issue. try adding this label:

–label “traefik.frontend.rule=Host:example.com;PathPrefixStrip:/myapp”

it’ll strip the /myapp prefix before sending to ur service. works like a charm for me. good luck!

I’ve tackled a similar issue in my Traefik setup. To combine hostname and path-based routing using Docker labels, you can modify your existing configuration like this:

docker service create \
  --label "traefik.port=8080" \
  --label "traefik.docker.network=proxy-net" \
  --label "traefik.frontend.rule=Host:example.com;PathPrefix:/myapp" \
  --label="traefik.backend=myapp" \
  --constraint "node.role == manager" \
  -p 8080:8080 \
  --mount "type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock" \
  --name myapp \
  myapp/myapp

The key change is in the ‘traefik.frontend.rule’ label. By using a semicolon, you can combine multiple rules. This configuration will route traffic to your service when the hostname is ‘example.com’ and the path starts with ‘/myapp’. Remember to adjust your application to handle the ‘/myapp’ prefix if necessary.

hey there! have u considered using traefik’s PathPrefix and PathPrefixStrip together? something like this:

–label “traefik.frontend.rule=Host:example.com;PathPrefix:/myapp;PathPrefixStrip:/myapp”

this way, u can keep the original url structure but strip it b4 hitting ur service. what do u think? wanna give it a shot?