Appearance
Traefik
why
很多时候,需要在一个域名 example.com 底下关联很多服务,这样用户使用各服务的时候都知道它属于 example,强化了品牌认知。
同域名关联多服务,一种方式是使用子域名 doc.example.com,另一种方式是使用子路径 example.com/doc。
通过服务发现和反向代理路由,Traefik 很好地实现了上述能力。
how
scenario 通用反向代理路由
- given 真正处理请求的服务启动(对应 Traefik 中的 Services 概念)
- and 反向代理规则配置(请求 -> 真正服务)(对应 Traefik 中的 Providers 和 Routes 概念)
- and 反向代理服务器启动(Traefik)
- when 用户请求到反向代理服务器(Traefik Endpoints 入口接收)
- then 反向代理服务器分析请求
- when 请求匹配某个路由规则
- then 将请求转发到路由规则对应的真正服务
scenario 启动 Traefik
- given 系统中 docker 可用
- and 添加 Traefik 启动对应的 docker-compose.yml
- when 执行
docker-compose up -d - then 启动 Traefik(占用对应端口)
- when 浏览器中打开 dashboard 地址(
http://localhost:8180/dashboard/) - then 查看 Traefik 运行状态
yml
# docker-compose.yml
services:
traefik:
image: traefik:v3.6
command:
- "--api.insecure=true" # 不安全模式,无需身份认证即可访问仪表盘
- "--providers.docker=true"
- "--entrypoints.web.address=:80" # http endpoint
# - "--entryPoints.websecure.address=:443" # https endpoint
# - "--entryPoints.websecure.http.tls=true" # https
ports:
- "8100:80" # endpoint
- "8180:8080" # dashboard
volumes:
- /var/run/docker.sock:/var/run/docker.sockscenario 根据请求头 Host 分流到新服务
- given Traefik 已启动
- and 添加新服务对应配置 whoami.yml,其中分流标签为
Host(`whoami.localhost`) - when 执行
docker-compose -f whoami.yml up -d - then 新服务启动
- when 执行
curl -H "Host: whoami.localhost" http://localhost:8100 - then 得到响应结果,证明已被 Traefik 路由成功
- when 浏览器进入 Traefik 面板的 HTTP 页面
- then 看到新服务及其路由规则展示
yml
# whoami.yml
services:
whoami:
image: traefik/whoami
labels:
- "traefik.http.routers.whoami.rule=Host(`whoami.localhost`)"scenario 根据子路径分流到新服务
- given Traefik 已启动
- and 添加新服务对应配置 whoami.yml,其中分流标签为
PathPrefix(`/whoami`) - when 执行
docker-compose -f whoami.yml up -d - then 新服务启动
- when 执行
curl -H "curl http://localhost:8100/whoami - then 得到响应结果,证明已被 Traefik 路由成功
- when 浏览器进入 Traefik 面板的 HTTP 页面
- then 看到新服务及其路由规则展示
yml
# whoami.yml
services:
whoami:
image: traefik/whoami
labels:
- "traefik.http.routers.whoami.rule=PathPrefix(`/whoami`)"⏳scenario 请求鉴权
- given 鉴权服务启动(通过响应码来判断鉴权是否成功)
- and 添加 ForwardAuth 中间件到 Traefik 中
⏳scenario 启动 Traefik 为 https 服务
⏳scenario 性能监控