首页 > 解决方案 > 使用 docker 使用 traefik v2 转发 url

问题描述

我想用 traefik(version 2) 转发 url,比如如果我点击 URL http://localhost/1然后它被转发到http://localhost:8081/1

我尝试了几种配置,但没有一个可以工作。请在下面找到我已经完成但没有成功的配置。

version: "3.3"

services:
  traefik:
    image: "traefik:v2.0.0-rc3"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
      - "8081:8081"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

  whoami:
    #image: "containous/whoami"
    #container_name: "simple-service"
    #command:
    #  - "--port=8081"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`localhost`)"
      - "traefik.http.routers.whoami.entrypoints=web"
      - "traefik.http.services.whoami.loadbalancer.server.port=8081" 

标签: dockerdocker-composetraefik

解决方案


我认为你不需要转发,因为你已经定义了负载均衡器端口,添加PathPrefix到你的 whoami 路由器规则应该可以工作。像这样

- "traefik.http.routers.whoami.rule=Host(`localhost`) && PathPrefix(`/1`)"

如果你确实需要转发请求,你可以使用 middlewares.redirectregex。

- "traefik.http.routers.whoami.middlewares=whoami-redirectregex"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.regex=^http://localhost/(.*)"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.replacement=http://localhost:8081/$${1}"

供参考。中间件文档


推荐阅读