如何使用 Traefik v2.3 在 Docker 上使用 Sticky 会话?

How can I use Sticky sessions on Docker using Traefik v2.3?

如何在 Traefik v2.3 中使用粘性会话?

当我在我的 docker 撰写文件中启用以下行时,我的 docker 服务(例如 http://192.168.0.1:9086)不工作。

- "traefik.http.services.mynginximage2.loadBalancer.sticky.cookie=true"

您知道为什么粘性会话不起作用吗?

是否可以通过服务标签建立会话关联?

以下是我的docker撰写文件:

version: "3.8"

services:
  traefik:
    image: traefik:v2.3
    deploy:
      mode: global
    networks:
      - traefik-net
    command:
      #- "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.mynginximage2_ep.address=:8086"
    ports:
      - 80:80
      - 9086:8086
      - 8080:8080
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
  whoami:
    image: "traefik/whoami"
    deploy:
      replicas: 2
    networks:
      - traefik-net
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.entrypoints=web"
      - "traefik.http.routers.whoami.rule=Host(`192.168.0.1`) || Host(`192.168.0.2`)"
      #- "traefik.http.services.whoami.loadBalancer.sticky.cookie=true"
      - "traefik.http.services.whoami-service.loadbalancer.server.port=80"
  mynginximage2:
    image: mynginximage2
    deploy:
      replicas: 2
    networks:
      - traefik-net
    #ports:
    #  - 9080:8086
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.mynginximage2.entrypoints=mynginximage2_ep"
      - "traefik.http.routers.mynginximage2.rule=Host(`192.168.0.1`) || Host(`192.168.0.2`)"
      #- "traefik.http.services.mynginximage2.loadBalancer.sticky.cookie=true"
      - "traefik.http.services.mynginximage2-service.loadbalancer.server.port=8086"      
networks:
  traefik-net:
    external: true
    name: traefik-net

我发现了为什么我的 Traefik 路由器在启用粘性会话功能时无法工作的问题。 解决方案是每个服务有一个不同的 cookie 名称。所以,我添加了 cookie 名称。例如:

version: "3.8"

services:
  #...
  whoami:
    #...
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.entrypoints=web"
      - "traefik.http.routers.whoami.rule=Host(`192.168.0.1`) || Host(`192.168.0.2`)"
      - "traefik.http.services.whoami-service.loadBalancer.sticky.cookie=true"
      - "traefik.http.services.whoami-service.loadBalancer.sticky.cookie.name=whoami_cookie_name"
      - "traefik.http.services.whoami-service.loadbalancer.server.port=80"
  mynginximage2:
    #...
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.mynginximage2.entrypoints=mynginximage2_ep"
      - "traefik.http.routers.mynginximage2.rule=Host(`192.168.0.1`) || Host(`192.168.0.2`)"
      - "traefik.http.services.mynginximage2-service.loadBalancer.sticky.cookie=true"
      - "traefik.http.services.mynginximage2-service.loadBalancer.sticky.cookie.name=mynginximage2_cookie_name"
      - "traefik.http.services.mynginximage2-service.loadbalancer.server.port=8086"      
#...