Traefik 详解

为什么80%的码农都做不了架构师?>>>   hot3.png

    traefik是一个使你把微服务暴露出来变的更容易的http反向代理和负载均衡软件。traefik支持K8S、docker swarm、mesos、consul、etcd、zookeeper等基础设施组件,个人认为更适合容器化的微服务,traefik的配置会自动的、动态的配置更新自己。

    假如你在基础架构组件中部署了大量的微服务,你一般通过服务发现或者资源管理框架来管理这些服务,这时候你想访问微服务,你需要一个反向代理。传统的反向代理需要你配置每一个访问到的微服务,在环境中当你增加、删除、升级、横向扩展服务的时候,你都需要调整反向代理配置,而传统的反向代理是不支持动态配置的。为了适应容器化微服务的这种场景,traefik就诞生了,traefik可以监听你的服务发现/基础架构组件的管理API,并且每当你的微服务被添加、移除、杀死或更新都会被感知,并且可以自动生成它们的配置文件。 这样指向到你服务的路由将会被直接创建出来。


    官方针对traefik吹了一大堆,在我看来有用的就一个支持K8S、docker swarm等,和容器结合比较紧密。所以一般情况下大家都是以容器的方式运行traefik。traefik的主程序就是一个二进制文件,你可以在非容器环境下使用。

 

普通青年快速入门

    制作traefik image

git clone https://github.com/containous/traefik.git
docker build -t traefik .

    启动traefik

        配置compose文件

version: '3'

services:
  reverse-proxy:
    image: traefik # The official Traefik docker image
    command: --api --docker # Enables the web UI and tells Træfik to listen to docker
    ports:
      - "80:80"     # The HTTP port
      - "8080:8080" # The Web UI (enabled by --api)
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock # So that Traefik can listen to the Docker events

        启动traefik

docker-compose up -d reverse-proxy

    或者直接以容器启动

docker run -d -p 8080:8080 -p 80:80 -v $PWD/traefik.toml:/etc/traefik/traefik.toml traefik

非普通青年入门

    traefik并非只能在container里面运行,也可以使用二进制文件直接启动

    下载二进制文件

https://github.com/containous/traefik/releases

    简单的配置文件

https://raw.githubusercontent.com/containous/traefik/master/traefik.sample.toml

    ps:默认traefik会寻找/etc/traefik/traefik.toml下的配置文件,当然也可以通过-c参数指定配置文件

启动应用

    创建服务compose文件

version: '3'

services:
  whoami:
    image: emilevauge/whoami
    networks:
      - web
    labels:
      - "traefik.backend=whoami"
      - "traefik.frontend.rule=Host:whoami.docker.localhost"

networks:
  web:
    external:
      name: traefik_webgateway

        ps:其中最关键的是labels的设置

    测试

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

 

下面开始仔细讲解traefik的点点滴滴

 

entrypoints

    进来的请求在entrypoints处结束,entrypoint是traefik的网络入口,entrypoint监听端口,SSL,做流量redirect。在经过entrypoint后,流量会被转发到一个匹配的frontend上,frontend定义了从entrypoint到backends的路由,路由是通过Host、Path、Headers来决定的,可以匹配或者拒绝一个请求。frontend把请求传送到backend,backend是由一个或者多个servers组成的,servers主要是设置负载均衡策略。最后server会把请求转发到私网内真正的微服务上去

entrypoints是traefik的网络入口,可以通过如下方式定义:

  • 一个端口 (80, 443...)
  • SSL (证书, 密钥, 由受信任的CA签名的客户端证书的身份验证...)
  • 重定向到其他的入口点 (重定向 HTTP 到 HTTPS)


显示一个entrypoint定义的例子:

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "tests/traefik.crt"
      keyFile = "tests/traefik.key"
  1.  定义了两个entrypoints,一个是http,一个是https
  2.  http监听在80端口,https监听在443端口
  3.  当启用ssl的时候,需要提供CA证书
  4.  把http entrypoint的请求都重定向到https entrypoint上

frontends

    frontends由一组规则组成,这些规则确定传入请求如何从entrypoint转发到backend。规则可以分为两种类型:修饰符和匹配器。

    Modifiers
        Modifier规则只修改请求,它们对正在做出的路由决策没有任何影响,下列是已经存在的modifier规则:

AddPrefix: /products:为请求URL路径添加前缀
ReplacePath: /serverless-path:替换path,并把老的path添加到X-Replaced-Path头
ReplacePathRegex: ^/api/v2/(.*) /api/$1:

    Matchers
        Matcher规则确定一个特定的请求应该被转发到哪个backend,用逗号分隔的规则值之间是'或'的关系,用分号分隔的规则值是必须全部满足的关系。下面是一些已经存在的matcher 规则:

Headers: Content-Type, application/json: 通过 Headers 可以添加一个匹配规则来匹配请求头部包含的值。它接受要匹配的键/值对序列。
HeadersRegexp: Content-Type, application/(text|json): 也可以在 Headers 中使用正则表达式。它接受要匹配的键/值对序列,序列内容解析是通过正则匹配的
Host: traefik.io, www.traefik.io: 匹配请求 Host 必需在给定域名列表内。
HostRegexp: traefik.io, {subdomain:[a-z]+}.traefik.io: 添加匹配请求 Host 的正则表达式。 它接受一个以{}包括起来的为空或更多url变量的模版。变量的值可以以一个可选的正则表达式来匹配。
Method: GET, POST, PUT: Method 可以添加一个HTTP请求方法的匹配。它接受要匹配的一个或多个请求方法序列。
Path: /products/, /articles/{category}/{id:[0-9]+}: Path 可以添加一个URL路径的匹配。它接受一个以{}包括起来的为空或更多url变量的模版。
PathStrip: /products/    和 Path 相同,但从请求的URL路径中去掉的给定的前缀。
PathStripRegex: /articles/{category}/{id:[0-9]+}    Match exact path and strip off the path prior to forwarding the request to the backend. It accepts a sequence of literal and regular expression paths.
PathPrefix: /products/, /articles/{category}/{id:[0-9]+}    PathPrefix 可以添加一个URL路径前缀的匹配。它匹配给定模版中的完整URL路径前缀。
PathPrefixStrip: /products/    和 PathPrefix 相同,但从请求的URL路径中去掉的给定的前缀。
PathPrefixStripRegex: /articles/{category}/{id:[0-9]+}    Match request prefix path and strip off the path prefix prior to forwarding the request to the backend. It accepts a sequence of literal and regular expression prefix paths. Starting with Traefik 1.3, the stripped prefix path will be available in the X-Forwarded-Prefix header.
Query: foo=bar, bar=baz    匹配查询对象,接受k=v的格式

        ps:为了在Host和Path matchers规则中使用正则,你必须使用命名捕获,例如:/posts/{id:[0-9]+},你可以选择启用 passHostHeader 来转发客户端请求Header中的 Host 字段到后端


显示一个frontends定义的例子:

[frontends]
  [frontends.frontend1]
  backend = "backend2"
    [frontends.frontend1.routes.test_1]
    rule = "Host:test.localhost,test2.localhost"
  [frontends.frontend2]
  backend = "backend1"
  passHostHeader = true
  passTLSCert = true
  priority = 10
  entrypoints = ["https"] # overrides defaultEntryPoints
    [frontends.frontend2.routes.test_1]
    rule = "HostRegexp:localhost,{subdomain:[a-z]+}.localhost"
  [frontends.frontend3]
  backend = "backend2"
    [frontends.frontend3.routes.test_1]
    rule = "Host:test3.localhost;Path:/test"
  1.  定义了frontend1, frontend2 和 frontend3三个frontends
  2.  如果匹配Host:test.localhost,test2.localhost规则,则frontend1转发请求到backend2
  3.  如果匹配HostRegexp:localhost,{subdomain:[a-z]+}.localhost规则,则frontend2转发请求到backend1
  4.  如果Host:test3.localhost和Path:/test同时匹配,则frontend3转发请求到backend2

合并多条规则的例子:

[frontends.frontend3]
  backend = "backend2"
    [frontends.frontend3.routes.test_1]
    rule = "Host:test3.localhost"
    [frontends.frontend3.routes.test_2]
    rule = "Path:/test"

  可以使用分号把多个规则合并在一起,如下:

  [frontends.frontend3]
  backend = "backend2"
    [frontends.frontend3.routes.test_1]
    rule = "Host:test3.localhost;Path:/test"

你可以使用 , 符号分隔规则,为一个frontend创建一个规则来绑定多个域名或路径:

  [frontends.frontend2]
    [frontends.frontend2.routes.test_1]
    rule = "Host:test1.localhost,test2.localhost"
  [frontends.frontend3]
  backend = "backend2"
    [frontends.frontend3.routes.test_1]
    rule = "Path:/test1,/test2"


    ps:规则的优先级:当结合Modifier和Matcher规则一起使用的时候,要记住,Modifier规则始终在Matcher规则之后起作用。

下面的规则在Matchers和Modifiers都有,所以Matcher先执行,然后才是Modifier:

  1. PathStrip
  2. PathStripRegex
  3. PathPrefixStrip
  4. PathPrefixStripRegex

无论规则的顺序如何写,Modifiers都是按照一定的顺序执行,如下:

  1. PathStrip
  2. PathPrefixStrip
  3. PathStripRegex
  4. PathPrefixStripRegex
  5. AddPrefix
  6. ReplacePath


优先级:默认情况下,路由会以规则长度(为了防止部分重叠情况)被排序(倒序)。

你也可以在frontend上自定义优先级:

  [frontends]
    [frontends.frontend1]
    backend = "backend1"
    priority = 20
    passHostHeader = true
      [frontends.frontend1.routes.test_1]
      rule = "PathPrefix:/to"
    [frontends.frontend2]
    backend = "backend2"
    passHostHeader = true
      [frontends.frontend2.routes.test_1]
      rule = "PathPrefix:/toto"


自定义headers:可以在frontends中配置自定义的headers,可以在requests或者responses中匹配frontends的规则,

[frontends]
  [frontends.frontend1]
  backend = "backend1"
    [frontends.frontend1.headers.customresponseheaders]
    X-Custom-Response-Header = "True"
    [frontends.frontend1.headers.customrequestheaders]
    X-Script-Name = "test"
    [frontends.frontend1.routes.test_1]
    rule = "PathPrefixStrip:/cheese"
  1. 给所有匹配/cheese的请求添加X-Script-Name头,给响应添加X-Custom-Response-Header头


安全headers:是关于HSTS headers, SSL redirection, Browser XSS filter的一些设置,

[frontends]
  [frontends.frontend1]
  backend = "backend1"
    [frontends.frontend1.headers]
    FrameDeny = true
    [frontends.frontend1.routes.test_1]
    rule = "PathPrefixStrip:/cheddar"
  [frontends.frontend2]
  backend = "backend2"
    [frontends.frontend2.headers]
    SSLRedirect = true
    [frontends.frontend2.routes.test_1]
    rule = "PathPrefixStrip:/stilton"

backends

    backends负责将来自一个或者多个frontends的流量负载均衡到一组http servers上。Servers是通过一个url来定义的,也可以给每个server设置weight。

下面是backend和server的定义:

[backends]
  [backends.backend1]
    # ...
    [backends.backend1.servers.server1]
    url = "http://172.17.0.2:80"
    weight = 10
    [backends.backend1.servers.server2]
    url = "http://172.17.0.3:80"
    weight = 1
  [backends.backend2]
    # ...
    [backends.backend2.servers.server1]
    url = "http://172.17.0.4:80"
    weight = 1
    [backends.backend2.servers.server2]
    url = "http://172.17.0.5:80"
    weight = 2
  1.   定义了两个backends:backend1和backend2


负载均衡:支持两种负载均衡模式,默认是wrr

  • wrr: 加权轮询
  • drr: 动态轮询: 这会为表现比其他服务器好的服务器增加权重。当服务器表现有变化的时,它也会会退到正常权重。


断路器:也可以应用到后端,用于防止故障服务器上的高负载。 初始化状态是Standby。断路器只观察统计信息但并不修改请求。 当断路条件匹配时,断路器进入Tripped状态,它会返回与定义的http状态码或转发到其他前端。 一旦Tripped状态计时器超时,断路器会进入Recovering状态并重置所有统计数据。 当短路条件不匹配并且Recovery状态计时器超时时,断路器进入Standby状态。

断路器可以使用如下配置:

  • 方法: LatencyAtQuantileMS, NetworkErrorRatio, ResponseCodeRatio
  • 操作符: AND, OR, EQ, NEQ, LT, LE, GT, GE

例如:

NetworkErrorRatio() > 0.5: 监控网络故障率大于0.5超过10秒后,为这个前端平滑切换,断路条件匹配
LatencyAtQuantileMS(50.0) > 50: 监控延迟超过50ms时断路条件匹配
ResponseCodeRatio(500, 600, 0, 600) > 0.5: 监控返回 HTTP状态码在[500-600]之间的数量/HTTP状态码在[0-600]之间的数量 的比例大于0.5时,断路条件匹配


下面是包含断路器的backends和servers的定义:

[backends]
  [backends.backend1]
    [backends.backend1.circuitbreaker]
    expression = "NetworkErrorRatio() > 0.5"
    [backends.backend1.servers.server1]
    url = "http://172.17.0.2:80"
    weight = 10
    [backends.backend1.servers.server2]
    url = "http://172.17.0.3:80"
    weight = 1

最大连接数:为了主动防治后端被高负载压垮,可以为每个后端设置最大连接数限制。最大连接数限制可以通过为maxconn.amount配置一个整型值,同时 maxconn.extractorfunc 是用来配置通过什么样的维度来统计最大连接数。

例如:

[backends]
  [backends.backend1]
    [backends.backend1.maxconn]
       amount = 10
       extractorfunc = "request.host"


会话保持:所有的负载平衡器都支持会话保持。当会话保持被开启时,在初始请求上设置cookie,默认cookie名称是sha1的缩写。在随后的请求中,客户端会被直接转发到这个cookie中存储的后端(当然它要是健康可用的),如果这个后端不可用,将会指定一个新的后端。

例如:

[backends]
  [backends.backend1]
    # Enable sticky session
    [backends.backend1.loadbalancer.stickiness]

健康监测:服务器健康检查也是可配置的,Traefik定期执行HTTP GET请求到backend时,backend返回的HTTP状态码不是200 OK,那么这个后端将被从负载均衡轮询列表中移除。

健康检查可以以一个在后端URL后附加路径的路径地址与一个时间间隔 (以 time.ParseDuration 所识别的格式给出) specifying how 配置多久健康检查应该执行一次 (默认30秒). 每个后端必需在5秒内回应健康检查。当一个后端重新返回HTTP状态码200 OK时,将被重新添加回负载均衡轮询列表。
例如:

[backends]
  [backends.backend1]
    [backends.backend1.healthcheck]
    path = "/health"
    interval = "10s"
    port = 8080


配置

Træfik's的配置分为两部分:

  1. Static Træfik configuration:仅在启动时被加载
  2. Dynamic Træfik configuration:被热更新(无需重启进程)

Static Træfik configuration:静态配置是一种全局配置,用来设置entrypoints和backends的连接,traefik可以试验多种配置源,以下是配置生效的优先级,

  1. Key-value store
  2. Arguments
  3. Configuration file
  4. Default

配置文件:traefik会在以下几个地方寻找traefik.toml配置文件

  • /etc/traefik/
  • $HOME/.traefik/

不过也可以在命令行改变配置文件路径:traefik --configFile=foo/bar/myconfigfile.toml


前面说过traefik的配置可以是kv对的形式,这些kv对可以存储在以下后端存储中:

  • Consul
  • etcd
  • ZooKeeper
  • boltdb


Dynamic Træfik configuration:动态配置关注的是frontends、backends、servers、https ca等。


Global Configuration

    Main Section:

# graceTimeOut = "10s"
# debug = true
# checkNewVersion = false
# providersThrottleDuration = "2s"
# maxIdleConnsPerHost = 200
# insecureSkipVerify = true
# rootCAs = [ "/mycert.cert" ]
# defaultEntryPoints = ["http", "https"]
# AllowMinWeightZero = true


    Constraints:

        在一个以中央服务发现的微服务架构中,配置文件会将Træfɪk的发现范围约束到一小部分路由上。Træfɪk 根据你在配置后端时为服务设置的属性/标签来过滤服务。traefik支持通过tag来过滤 


    支持的后端类型:

Docker
Consul K/V
BoltDB
Zookeeper
Etcd
Consul Catalog
Rancher
Marathon
Kubernetes


    tag配置样例:

# 简单约束匹配的条件
# constraints = ["tag==api"]
#
# 简单约束不匹配的条件
# constraints = ["tag!=api"]
#
# 约束全局匹配条件
# constraints = ["tag==us-*"]
#
# 多个约束条件
# constraints = ["tag!=us-*", "tag!=asia-*"]

    Custom Error pages:

        可以在frontend上自定义错误状态码的返回页面

    例如:

[frontends]
  [frontends.website]
  backend = "website"
  [frontends.website.errors]
    [frontends.website.errors.network]
    status = ["500-599"]
    backend = "error"
    query = "/{status}.html"
  [frontends.website.routes.website]
  rule = "Host: website.mydomain.com"

[backends]
  [backends.website]
    [backends.website.servers.website]
    url = "https://1.2.3.4"
  [backends.error]
    [backends.error.servers.error]
    url = "http://2.3.4.5"

    Rate limiting:

        可以在每个frontend上配置限速

    例如:

[frontends]
    [frontends.frontend1]
      # ...
      [frontends.frontend1.ratelimit]
        extractorfunc = "client.ip"
          [frontends.frontend1.ratelimit.rateset.rateset1]
            period = "10s"
            average = 100
            burst = 200
          [frontends.frontend1.ratelimit.rateset.rateset2]
            period = "3s"
            average = 5
            burst = 10


    Buffering:

        可以在每个backend上开启请求的buffer

    例如:

[backends]
  [backends.backend1]
    [backends.backend1.buffering]
      maxRequestBodyBytes = 10485760  
      memRequestBodyBytes = 2097152  
      maxResponseBodyBytes = 10485760
      memResponseBodyBytes = 2097152
      retryExpression = "IsNetworkError() && Attempts() <= 2"

    Retry Configuration:

        当网络有异常时的请求重试次数

    例如:

[retry]
# Number of attempts
# Optional
# Default: (number servers in backend) -1
#
# attempts = 3


    Health Check Configuration:

        可以自定义监控检测时间

    例如:

[healthcheck]

# Set the default health check interval.
#
# Optional
# Default: "30s"
#
# interval = "30s"


    Life Cycle:

        在Traefik停机的时间内,控制Traefik的行为

    例如:

[lifeCycle]

# Optional
# Default: 0
#
# requestAcceptGraceTimeout = "10s"

#
# Optional
# Default: "10s"
#
# graceTimeOut = "10s"


    Timeouts:

        各种超时时间的设置   

    例如

[respondingTimeouts]

# readTimeout is the maximum duration for reading the entire request, including the body.
#
# Optional
# Default: "0s"
#
# readTimeout = "5s"

# writeTimeout is the maximum duration before timing out writes of the response.
#
# Optional
# Default: "0s"
#
# writeTimeout = "5s"

# idleTimeout is the maximum duration an idle (keep-alive) connection will remain idle before closing itself.
#
# Optional
# Default: "180s"
#
# idleTimeout = "360s"

[forwardingTimeouts]

# dialTimeout is the amount of time to wait until a connection to a backend server can be established.
#
# Optional
# Default: "30s"
#
# dialTimeout = "30s"

# responseHeaderTimeout is the amount of time to wait for a server's response headers after fully writing the request (including its body, if any).
#
# Optional
# Default: "0s"
#
# responseHeaderTimeout = "0s"

# idleTimeout
#
# DEPRECATED - see [respondingTimeouts] section.
#
# Optional
# Default: "180s"
#
idleTimeout = "360s"

    provider_name:

        就是后端存储的类型

    例如

[provider_name]

# Override default provider configuration template. For advanced users :)
#
# Optional
# Default: ""
#
filename = "custom_config_template.tpml"

# Enable debug logging of generated configuration template.
#
# Optional
# Default: false
#
debugLogGeneratedTemplate = true


Logs Definition

    TOML

logLevel = "INFO"

[traefikLog]
  filePath = "/path/to/traefik.log"
  format   = "json"

[accessLog]
  filePath = "/path/to/access.log"
  format = "json"

  [accessLog.filters]
    statusCodes = ["200", "300-302"]
    retryAttempts = true
    minDuration = "10ms"

  [accessLog.fields]
    defaultMode = "keep"
    [accessLog.fields.names]
      "ClientUsername" = "drop"
      # ...

    [accessLog.fields.headers]
      defaultMode = "keep"
      [accessLog.fields.headers.names]
        "User-Agent" = "redact"
        "Authorization" = "drop"
        "Content-Type" = "keep"

    CLI

--logLevel="DEBUG"
--traefikLog.filePath="/path/to/traefik.log"
--traefikLog.format="json"
--accessLog.filePath="/path/to/access.log"
--accessLog.format="json"
--accessLog.filters.statusCodes="200,300-302"
--accessLog.filters.retryAttempts="true"
--accessLog.filters.minDuration="10ms"
--accessLog.fields.defaultMode="keep"
--accessLog.fields.names="Username=drop Hostname=drop"
--accessLog.fields.headers.defaultMode="keep"
--accessLog.fields.headers.names="User-Agent=redact Authorization=drop Content-Type=keep"


Entry Points Definition

    TOML

defaultEntryPoints = ["http", "https"]


[entryPoints]
  [entryPoints.http]
    address = ":80"
    compress = true

    [entryPoints.http.whitelist]
      sourceRange = ["10.42.0.0/16", "152.89.1.33/32", "afed:be44::/16"]
      useXForwardedFor = true

    [entryPoints.http.tls]
      minVersion = "VersionTLS12"
      cipherSuites = [
        "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
        "TLS_RSA_WITH_AES_256_GCM_SHA384"
       ]
      [[entryPoints.http.tls.certificates]]
        certFile = "path/to/my.cert"
        keyFile = "path/to/my.key"
      [[entryPoints.http.tls.certificates]]
        certFile = "path/to/other.cert"
        keyFile = "path/to/other.key"
      # ...
      [entryPoints.http.tls.clientCA]
        files = ["path/to/ca1.crt", "path/to/ca2.crt"]
        optional = false

    [entryPoints.http.redirect]
      entryPoint = "https"
      regex = "^http://localhost/(.*)"
      replacement = "http://mydomain/$1"
      permanent = true

    [entryPoints.http.auth]
      headerField = "X-WebAuth-User"
      [entryPoints.http.auth.basic]
        removeHeader = true
        users = [
          "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/",
          "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0",
        ]
        usersFile = "/path/to/.htpasswd"
      [entryPoints.http.auth.digest]
        removeHeader = true
        users = [
          "test:traefik:a2688e031edb4be6a3797f3882655c05",
          "test2:traefik:518845800f9e2bfb1f1f740ec24f074e",
        ]
        usersFile = "/path/to/.htdigest"
      [entryPoints.http.auth.forward]
        address = "https://authserver.com/auth"
        trustForwardHeader = true
        authResponseHeaders = ["X-Auth-User"]
        [entryPoints.http.auth.forward.tls]
          ca = "path/to/local.crt"
          caOptional = true
          cert = "path/to/foo.cert"
          key = "path/to/foo.key"
          insecureSkipVerify = true

    [entryPoints.http.proxyProtocol]
      insecure = true
      trustedIPs = ["10.10.10.1", "10.10.10.2"]

    [entryPoints.http.forwardedHeaders]
      trustedIPs = ["10.10.10.1", "10.10.10.2"]

  [entryPoints.https]
    # ...

    CLI

--entryPoints='Name:http Address::80'
--entryPoints='Name:https Address::443 TLS'

Basic:

# Entrypoints definition
#
# Default:
# [entryPoints]
#   [entryPoints.http]
#   address = ":80"
#
[entryPoints]
  [entryPoints.http]
  address = ":80"

Redirect HTTP to HTTPS:

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "integration/fixtures/https/snitest.com.cert"
      keyFile = "integration/fixtures/https/snitest.com.key"
      [[entryPoints.https.tls.certificates]]
      certFile = "integration/fixtures/https/snitest.org.cert"
      keyFile = "integration/fixtures/https/snitest.org.key"


Rewriting URL:

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    regex = "^http://localhost/(.*)"
    replacement = "http://mydomain/$1"

TLS:

[entryPoints]
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "integration/fixtures/https/snitest.com.cert"
      keyFile = "integration/fixtures/https/snitest.com.key"


Authentication

Basic Authentication

[entryPoints]
  [entryPoints.http]
  address = ":80"
  [entryPoints.http.auth.basic]
  users = ["test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/", "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0"]
  usersFile = "/path/to/.htpasswd"

Digest Authentication

[entryPoints]
  [entryPoints.http]
  address = ":80"
  [entryPoints.http.auth.digest]
  users = ["test:traefik:a2688e031edb4be6a3797f3882655c05", "test2:traefik:518845800f9e2bfb1f1f740ec24f074e"]
  usersFile = "/path/to/.htdigest"


Forward Authentication

[entryPoints]
  [entryPoints.http]
    # ...
    # To enable forward auth on an entrypoint
    [entryPoints.http.auth.forward]
    address = "https://authserver.com/auth"

    # Trust existing X-Forwarded-* headers.
    # Useful with another reverse proxy in front of Traefik.
    #
    # Optional
    # Default: false
    #
    trustForwardHeader = true

    # Copy headers from the authentication server to the request.
    #
    # Optional
    #
    authResponseHeaders = ["X-Auth-User", "X-Secret"]

      # Enable forward auth TLS connection.
      #
      # Optional
      #
      [entryPoints.http.auth.forward.tls]
      ca = "path/to/local.crt"
      caOptional = true
      cert = "path/to/foo.cert"
      key = "path/to/foo.key"


Specify Minimum TLS Version:

[entryPoints]
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
    minVersion = "VersionTLS12"
    cipherSuites = [
      "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
      "TLS_RSA_WITH_AES_256_GCM_SHA384"
    ]
      [[entryPoints.https.tls.certificates]]
      certFile = "integration/fixtures/https/snitest.com.cert"
      keyFile = "integration/fixtures/https/snitest.com.key"
      [[entryPoints.https.tls.certificates]]
      certFile = "integration/fixtures/https/snitest.org.cert"
      keyFile = "integration/fixtures/https/snitest.org.key"

Compression:

[entryPoints]
  [entryPoints.http]
  address = ":80"
  compress = true

White Listing:

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

    [entryPoints.http.whiteList]
      sourceRange = ["127.0.0.1/32", "192.168.1.7"]
      # useXForwardedFor = true


Forwarded Header:

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

    # Enable Forwarded Headers
    [entryPoints.http.forwardedHeaders]
      # List of trusted IPs
      #
      # Required
      # Default: []
      #
      trustedIPs = ["127.0.0.1/32", "192.168.1.7"]

API Definition

    Configuration:

# API definition
# Warning: Enabling API will expose Træfik's configuration.
# It is not recommended in production,
# unless secured by authentication and authorizations
[api]
  # Name of the related entry point
  #
  # Optional
  # Default: "traefik"
  #
  entryPoint = "traefik"

  # Enable Dashboard
  #
  # Optional
  # Default: true
  #
  dashboard = true

  # Enable debug mode.
  # This will install HTTP handlers to expose Go expvars under /debug/vars and
  # pprof profiling data under /debug/pprof/.
  # Additionally, the log level will be set to DEBUG.
  #
  # Optional
  # Default: false
  #
  debug = true


    Security:

API:

defaultEntryPoints = ["http"]

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

  [entryPoints.foo]
  address = ":8082"

  [entryPoints.bar]
  address = ":8083"

[ping]
entryPoint = "foo"

[api]
entryPoint = "bar"

Custom Path
defaultEntryPoints = ["http"]

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

  [entryPoints.foo]
  address = ":8080"

  [entryPoints.bar]
  address = ":8081"

# Activate API and Dashboard
[api]
entryPoint = "bar"
dashboard = true

[file]
  [backends]
    [backends.backend1]
      [backends.backend1.servers.server1]
      url = "http://127.0.0.1:8081"

  [frontends]
    [frontends.frontend1]
    entryPoints = ["foo"]
    backend = "backend1"
      [frontends.frontend1.routes.test_1]
      rule = "PathPrefixStrip:/yourprefix;PathPrefix:/yourprefix"

Authentication
defaultEntryPoints = ["http"]

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

 [entryPoints.foo]
   address=":8080"
   [entryPoints.foo.auth]
     [entryPoints.foo.auth.basic]
       users = [
         "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/",
         "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0",
       ]

[api]
entrypoint="foo"

Metrics:

[api]
  # ...

  # Enable more detailed statistics.
  [api.statistics]

    # Number of recent errors logged.
    #
    # Default: 10
    #
    recentErrors = 10

  # ...

Docker Provider


    Docker Swarm Mode:

################################################################
# Docker Swarm Mode Provider
################################################################

# Enable Docker Provider.
[docker]

# Docker server endpoint.
# Can be a tcp or a unix socket endpoint.
#
# Required
# Default: "unix:///var/run/docker.sock"
#
endpoint = "tcp://127.0.0.1:2375"

# Default base domain used for the frontend rules.
# Can be overridden by setting the "traefik.domain" label on a services.
#
# Optional
# Default: ""
#
domain = "docker.localhost"

# Enable watch docker changes.
#
# Optional
# Default: true
#
watch = true

# Use Docker Swarm Mode as data provider.
#
# Optional
# Default: false
#
swarmMode = true

# Define a default docker network to use for connections to all containers.
# Can be overridden by the traefik.docker.network label.
#
# Optional
#
network = "web"

# Override default configuration template.
# For advanced users :)
#
# Optional
#
# filename = "docker.tmpl"

# Override template version
# For advanced users :)
#
# Optional
# - "1": previous template version (must be used only with older custom templates, see "filename")
# - "2": current template version (must be used to force template version when "filename" is used)
#
# templateVersion = 2

# Expose services by default in Traefik.
#
# Optional
# Default: true
#
exposedByDefault = false

# Enable docker TLS connection.
#
# Optional
#
#  [docker.tls]
#  ca = "/etc/ssl/ca.crt"
#  cert = "/etc/ssl/docker.crt"
#  key = "/etc/ssl/docker.key"
#  insecureSkipVerify = true


    Labels:

        overriding default behavior:

    Using Docker with Swarm Mode:

version: "3"
services:
  whoami:
    deploy:
      labels:
        traefik.docker.network: traefik

 

 

转载于:https://my.oschina.net/guol/blog/2209678

你可能感兴趣的:(运维)