使用Traefik为应用服务集群提供反向代理及负载均衡能力

官方资源

官方网站:https://www.traefik.io
官方文档:https://docs.traefik.io

快速尝试

创建docker-compose.yml

version: '3'
services:
  traefik:
    image: traefik #官方镜像
    command: --api --docker # 启用webui及docker监听
    ports:
      - "80:80"     #http端口
      - "8080:8080" #webui端口,使用--api启用生效
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock #docker监听地址

启动traefik服务

1
docker-compose up -d traefik

新建测试服务

使用label:traefik.frontend.rule标注

version: '3'
services:
    whoami:
        image: containous/whoami
        labels:
          - "traefik.frontend.rule=Host:whoami.docker.localhost"
1
docker-compose up -d whoami

测试访问

1
curl -H Host:whoami.docker.localhost http://127.0.0.1

可能结果

Hostname: 858ds8v4dc7
IP: 10.19.0.5
#...

数据持久化

主要包含主配置文件traefik.toml和Let’s Encrypt数据文件acme.json,在主机创建一个目录/data/traefik来存放这些数据

1
mkdir -p /data/traefik

现在变更服务定义

version: '3'
services:
  traefik:
    image: traefik #官方镜像
    command: --api --docker # 启用webui及docker监听
    ports:
      - "80:80"     #http端口
      - "8080:8080" #webui端口,使用--api启用生效
    volumes:
      - /data/traefik/traefik.toml:/traefik.toml
      - /data/traefik/acme.json:/acme.json
      - /var/run/docker.sock:/var/run/docker.sock #docker监听地址

常用配置

访问点定义

defaultEntryPoints = ["https","http"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
  [entryPoints.https]
  address = ":443"

Let’s Encrypt自动证书配置

[acme]
email = "your@domain.com" #更改为你的账户邮箱
storage = "acme.json" #存放证书数据
entryPoint = "https"
onHostRule = true #启用基于host rule的生成规则(traefik.frontend.rule定义host)

[acme.httpChallenge]
entryPoint = "http"

监听docker改变

watch = true

traefik.toml完整内容

debug = false

logLevel = "ERROR"
defaultEntryPoints = ["https","http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
  [entryPoints.https]
  address = ":443"

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "yourdomain.com"
watch = true

[acme]
email = "your@domain.com"
storage = "acme.json"
entryPoint = "https"
onHostRule = true

[acme.httpChallenge]
entryPoint = "http"

#...
#...

为服务配置label以便于traefik识别及提供访问

traefik.backend=appname #服务名称
traefik.frontend.entryPoints=http,https #访问方式
traefik.frontend.rule=Host: yourdomain.com #基于host规则的域名定义
traefik.port=80 #容器内部访问端口
traefik.protocol=http #容器内部访问协议

例如:

version: '3'
services:
    whoami:
        image: containous/whoami
        labels:
          - traefik.backend=appname
          - traefik.frontend.entryPoints=http,https
          - traefik.frontend.rule=Host: yourdomain.com
          - traefik.port=80
          - traefik.protocol=http

则应用可使用域名yourdomain.com通过http,https访问

如何设置http重定向https

增加下列label

traefik.frontend.redirect.entryPoint=https

结束