Docker Compose中Traefik的PathRegexp路由配置报错问题
解决Traefik路由配置错误及路径分流需求
错误原因
Traefik v2.x版本已移除PathRegexp函数,需使用PathPrefix或Regexp函数替代进行路径匹配。
解决方案
要实现localhost:80映射UI容器、localhost/api/xxx映射API容器、localhost/api由UI容器处理的需求,需对配置做以下调整:
1. 修正API路由规则并设置优先级
使用Regexp匹配/api/开头的路径,同时给API路由设置更高优先级,避免UI的通配规则先拦截/api/xxx请求。
2. 添加路径剥离中间件
API容器通常监听根路径(/),需通过中间件剥离请求路径中的/api前缀后再转发给API容器。
3. 优化端口配置
UI和API容器无需暴露端口给主机,Traefik会通过Docker网络内部转发,避免端口冲突。
修改后的完整Docker Compose配置:
version: "3" services: api: build: context: . dockerfile: ./api/dockerfile depends_on: - db - traefik labels: # 匹配所有/api/开头的子路径,不匹配/api本身 - "traefik.http.routers.api.rule=Host(`localhost`) && Regexp(`Path`, `^/api/.*`)" # 设置更高优先级,确保/api/xxx请求先匹配API路由 - "traefik.http.routers.api.priority=10" # 配置路径剥离中间件 - "traefik.http.middlewares.api-strip-prefix.stripprefix.prefixes=/api" - "traefik.http.routers.api.middlewares=api-strip-prefix@docker" # 指定API容器内部监听的端口(假设为5000) - "traefik.http.services.api.loadbalancer.server.port=5000" # 移除主机端口映射,由Traefik内部转发 # ports: # - 5000:5000 ui: build: context: . dockerfile: ./ui/dockerfile depends_on: - api - db - traefik volumes: - ./ui/html/:/var/www/html labels: - "traefik.http.routers.ui.rule=Host(`localhost`)" # 指定UI容器内部监听的端口(假设为81) - "traefik.http.services.ui.loadbalancer.server.port=81" # 移除主机端口映射 # ports: # - 81:81 # - 443:443 db: image: mysql restart: always env_file: .env environment: MYSQL_ROOT_PASSWORD: $ROOT_PASS_MYSQL MYSQL_DATABASE: $PRACTICE_DB ports: - 3307:3306 volumes: - ./db/mysql:/docker-entrypoint-initdb.d/:ro traefik: image: traefik:v2.9 command: - --api.insecure=true - --providers.docker - --providers.docker.exposedbydefault=false # 仅处理配置了Traefik标签的容器 ports: - 80:80 - 8080:8080 volumes: - /var/run/docker.sock:/var/run/docker.sock
关键说明
Regexp(Path,^/api/.*):精准匹配/api/开头的子路径,不会匹配/api本身,确保该请求被UI容器处理。priority=10:API路由优先级高于UI的默认0值,保证/api/xxx请求优先被API路由匹配。stripprefix中间件:转发请求给API容器时自动移除/api前缀,适配API的根路径监听逻辑。exposedbydefault=false:避免Traefik自动代理所有容器,仅处理显式配置标签的服务,提升安全性。
内容的提问来源于stack exchange,提问作者psova
相关产品推荐
相关产品推荐

