# Docker-compose 部署

docker create network traefik
version: "3"
services:
  traefik:
    image: traefik:v3.0.0-beta3
    restart: always
    ports:
       - target: 80
       published: 79
       protocol: tcp
       mode: host
       - target: 8078
       published: 8080
       protocol: tcp
       mode: host
    command:
      - "--api=true"
      - "--api.dashboard=true"
      - "--api.insecure=true"
      - "--ping=true"
      - "--entrypoints.http.address=:80"
      - "--providers.docker=true"
      - "--providers.docker.endpoint=unix:///var/run/docker.sock"
      - "--global.sendanonymoususage=false"
      - "--global.checknewversion=false"
    labels:
      - "traefik.http.routers.traefik-dashboard.entrypoints=http"
      - "traefik.http.routers.traefik-dashboard.rule=Host(`domain.com`)"
      - "traefik.http.routers.traefik-dashboard.service=dashboard@internal"
      - "traefik.http.routers.traefik-dashboard-api.entrypoints=http"
      - "traefik.http.routers.traefik-dashboard-api.rule=Host(`domain.com`) && PathPrefix(`/api`)"
      - "traefik.http.routers.traefik-dashboard-api.service=api@internal"
      - "traefik.http.middlewares.gzip.compress=true"
      - "traefik.http.routers.traefik-dashboard.middlewares=gzip@docker"
      - "traefik.http.routers.traefik-dashboard-api.middlewares=gzip@docker"
      - "traefik.http.routers.traefik-dashboard.tls=true"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    healthcheck:
      test: ["CMD-SHELL", "wget -q --spider --proxy off domain.com:8078/ping || exit 1"]
      interval: 3s
    logging:
      driver: "json-file"
      options:
        max-size: "1m"
networks:
  traefik:
    external: true

访问主机 ip:8078 进入 traefik 面板

# 负载均衡配置

sdocker-compose 部署其他服务时,需指定 labels

下面以微服务举例:

假如有两个微服务, 端口号分别为 1001,1002。

user 服务对应 1001 端口,video 服务对应 1002 端口。

version: "3"
services:
   user-service:
    image: your/user-service-image
    labels:
      - "traefik.http.routers.user-service.entrypoints=http"
      - "traefik.http.routers.user-service.rule=Host(`domain.com`) && PathPrefix(`/user/`)"
      - "traefik.http.services.user-service.loadbalancer.server.port=1001"
  video-service:
    image: your/video-service-image
    labels:
      - "traefik.http.routers.video-service.entrypoints=http"
      - "traefik.http.routers.video-service.rule=Host(`domain.com`) && PathPrefix(`/video/`)"
      - "traefik.http.services.video-service.loadbalancer.server.port=1002"
请求地址转发地址
domain.com/user/ip:1001/user/
domain.com/video/ip:1002/video/