Traefik docker 权重分流

如果只是简单的 robbin 负载均衡,不需要太多复杂的配置

权重负载均衡需要下面额外的一些配置,所以从头做一遍

traefik 的 docker-compose.yml 文件中需要多映射一个 configs文件夹,用来放配置文件

version: '3.7'

services:
  traefik:
    image: traefik:v2.4
    container_name: traefik
    restart: always
    security_opt:
      - no-new-privileges:true
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./traefik.yml:/traefik.yml:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./configs:/configs
    networks:
      - proxy
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=proxy"
      - "traefik.http.routers.traefik-secure.entrypoints=web"
      - "traefik.http.routers.traefik-secure.rule=Host(`traefik.lizhe.com`)"
      #- "traefik.http.routers.traefik-secure.middlewares=user-auth@file"
      - "traefik.http.routers.traefik-secure.service=api@internal"

networks:
  proxy:
    external: true

在 traefik.yml文件中也要加入对应的configs配置

api:
  dashboard: true

entryPoints:
  web:
    address: :80
  websecure:
    address: :443

pilot:
  dashboard: false

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
  file:
    filename: /configs/config.yml

此时不要急着启动,./configs/config.yml 文件还是要先创建的

http:
  routers:
    app-router:
      service: app
      rule: "Host(`app.lizhe.com`)"
  services:
    app:
      weighted:
        services:
        - name: appv1@docker
          weight: 10
        - name: appv2@docker
          weight: 1

    appv1:
      loadBalancer:
        servers:
        - url: "http://appv1.lizhe.com/"

    appv2:
      loadBalancer:
        servers:
        - url: "http://appv2.lizhe.com/"
        

然后创建 appv1 和 appv2

version: '3.7'

services:
  appv1:
    image: libaibai/version:v1
    container_name: appv1
    restart: always
    networks:
      - proxy
      - default
    restart: always
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=proxy"
      - "traefik.http.routers.appv1.entrypoints=web"
      - "traefik.http.routers.appv1.rule=Host(`appv1.lizhe.com`)"
      - "traefik.http.routers.appv1.service=appv1"
      - "traefik.http.services.appv1.loadbalancer.server.port=80"

networks:
  proxy:
    external: true
version: '3.7'

services:
  appv1:
    image: libaibai/version:v2
    container_name: appv2
    restart: always
    networks:
      - proxy
      - default
    restart: always
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=proxy"
      - "traefik.http.routers.appv2.entrypoints=web"
      - "traefik.http.routers.appv2.rule=Host(`appv2.lizhe.com`)"
      - "traefik.http.routers.appv2.service=appv2"
      - "traefik.http.services.appv2.loadbalancer.server.port=80"

networks:
  proxy:
    external: true

现在可以逐个启动这些服务了

Send a Message