blog
Route Paths in URL to sperarate Docker Services in Traefik using PathPrefix and StripPrefix
Consider the following scenario: you run a frontend webserver, such as nginx, to serve a JavaScript-enabled website that populates its content via a backend API. Instead of serving the API using a subdomain like api.example.com, it is ideal to use a subdirectory on the same domain, such as example.com/api/.
Traefik enables such differentiation with paths using the Routing rule PathPrefix and the Middleware StripPrefix. PathPrefix is an addition to the routing rule of the base domain, indicating that a service requires the given prefix to be accessed. However, many services require this prefix to be removed before receiving requests, so that /api/request becomes /request again. If redirection links are served from the API to itself, it’s important that the API can add this prefix to its own URLs. Some services offer configuration options for this purpose.
Here’s an example of how to apply this in a docker-compose.yml file:
Here is how this is applied in a docker-compose.yml:
version: "3"
services:
frontend:
image: nginx
labels:
# defining the frontend service with its routing and name serviceName
- traefik.http.routers.serviceName.rule=Host(`example.com`)
backend-api:
image: yourbackend
labels:
# defining the backend service with its extended routing including the prefix /api
- traefik.http.routers.serviceName.rule=Host(`example.com`) && PathPrefix(`/api`)
# defining a middleware of type stripprefix with the name middlewareName-stripprefix that strips /api
- traefik.http.middlewares.middlewareName-stripprefix.stripprefix.prefixes=/api
# enabling this defined middleware in the current service
- traefik.http.routers.serviceName.middlewares=middlewareName-stripprefix
Example docker-compose.yml file
As shown here, we can combine routing rules with && (|| is also possible) and define and enable middlewares within the docker labels. Remember to define your own names for services and middleware and double check the setup in the traefik dashboard if you have it set it up.