0. Traefik 简介 

    Traefik 是一个开源边缘路由器,它使发布您的服务成为一种有趣而轻松的体验。它接收请求并找出哪些组件负责处理它们。 

   traefik 是一款反向代理、负载均衡服务,支持自动化更新反向代理和负载均衡配置。可以支持多种后端 (Docker, Swarm, Kubernetes, Marathon, Mesos, Consul, Etcd, Zookeeper, BoltDB, Rest API, file…) 来自动化、动态的应用它的配置文件设置。

  0.1 traefik 分为静态配置和动态配置

  • 静态配置:运行期间不会改变的配置,比如监听的端口、日志配置等
  • 动态配置:运行期间会改变的配置,traefik 会定期更新配置,比如路由,限流和熔断等配置

  0.2 traefik 基本概念 

   进入到Traefik的请求会经过以下路径最终到达服务端:

  •   Incoming Requests  
  •   Entrypoints
  •   Routers(Rules,Middlewares)
  •   Services
  •   Server

   EntryPoints:请求进入Traefik的网络入口。Traefik通过EntryPoints定义了一些端口来接收请求,比如HTTP,TCP等。
   Routers:连接进入Traefik的请求和最终处理这些请求的服务。在这个过程中,Router有可能会使用一些middleware去对这些请求作出更新。
   Services:配置如何让Routers将这些请求转发到最终处理这些请求的后端服务上。
 

1. Traefik 路由规则

    traefik router 负责将传入请求连接到可以处理它们的服务。 在这个过程中,路由器可能会使用middleware 来更新请求,或者在将请求转发给 serice 之前采取措施。 

   1.1 taefike router 配置示例

    配置文件为 TOML 文件

## Dynamic configuration
[http.routers]
  [http.routers.my-router]
    rule = "Path(`/foo`)"
    service = "service-foo"

    配置文件为 yaml 文件 

## Dynamic configuration
http:
  routers:
    my-router:
      rule: "Path(`/foo`)"
      service: service-foo

2. Traefik Middlewares 中间件

    Middlewares 处于路由和后端服务的中间件,在外部流量进入 Traefik,且根据路由规则匹配成功后,将流量发送到对应的后端服务前,经过中间件进行一些列处理。Traefik 中有许多不同的可用中间件,有些可以修改请求、标头,有些负责重定向,有些添加身份验证等。

    例如,添加 Header 头信息、鉴权、流量转发、处理访问路径前缀、IP 白名单等等,经过一个或者多个中间件处理完成后,再发送给后端服务。

   2.1 已经实现的 Available Middlewares

MiddlewarePurposeArea
AddPrefixAdd a Path PrefixPath Modifier
BasicAuthBasic auth mechanismSecurity, Authentication
BufferingBuffers the request/responseRequest Lifecycle
ChainCombine multiple pieces of middlewareMiddleware tool
CircuitBreakerStop calling unhealthy servicesRequest Lifecycle
CompressCompress the responseContent Modifier
DigestAuthAdds Digest AuthenticationSecurity, Authentication
ErrorsDefine custom error pagesRequest Lifecycle
ForwardAuthAuthentication delegationSecurity, Authentication
HeadersAdd / Update headersSecurity
IPWhiteListLimit the allowed client IPsSecurity, Request lifecycle
InFlightReqLimit the number of simultaneous connectionsSecurity, Request lifecycle
PassTLSClientCertAdding Client Certificates in a HeaderSecurity
RateLimitLimit the call frequencySecurity, Request lifecycle
RedirectSchemeRedirect easily the client elsewhereRequest lifecycle
RedirectRegexRedirect the client elsewhereRequest lifecycle
ReplacePathChange the path of the requestPath Modifier
ReplacePathRegexChange the path of the requestPath Modifier
RetryAutomatically retry the request in case of errorsRequest lifecycle
StripPrefixChange the path of the requestPath Modifier
StripPrefixRegexChange the path of the request

3. 自定义添加 Middleware

   目前官方没有提供自定义 middleware 加入到 Traefik 的方案,采用的是直接在官方的源代码添加的方式。建议官方提供自定义插件方式,类似与 coreDNS 方式,没有满足自己的情况,可以额外添加插件

   3.0 下载 traefik 源码,选择适合的分支

    git clone https://github.com/traefik/traefik

   3.1 添加自定义 Middleware 结构声明

    文件路径 pkg/config/dynamic/middlewares.go, 在 Middleware 结构体添加自定义的 Middleware 结构,例如 HttpForwardHppts

// Middleware holds the Middleware configuration.
type Middleware struct {
   AddPrefix         *AddPrefix         `json:"addPrefix,omitempty" toml:"addPrefix,omitempty" yaml:"addPrefix,omitempty"`
   StripPrefix       *StripPrefix       `json:"stripPrefix,omitempty" toml:"stripPrefix,omitempty" yaml:"stripPrefix,omitempty"`
  ......
​​​​​​​  HttpForwardHttps  *HttpForwardHttps  `json:"httpForwardHttps,omitempty" toml:"httpForwardHttps,omitempty" yaml:"httpForwardHttps,omitempty"`
}

// Forward http to https configuration.
type HttpForwardHttps struct {
	TLS *ClientTLS `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty"`
}

   3.2 注册

    文件路径 pkg/server/middleware/middlewares.go, buildConstructor 需要注册上述定义的 HttpForwardHttps,添加该信息,以便循环遍历 Middlewares 调用 buildConstructor 注册所有 middleware

// it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists
func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (alice.Constructor, error) {
	config := b.configs[middlewareName]

	// HttpForwardHttps
	if config.HttpForwardHttps != nil {
		middleware = func(next http.Handler) (http.Handler, error) {
			return httpforwardhttps.New(ctx, next, *config.HttpForwardHttps, middlewareName)
		}
	}

  3.3 编译源代码

  3.4 创建配置文件,使用的 FileProvider 方式,dynamic.toml

[http.routers]
      [http.routers.test-router]
        entryPoints = ["web"]
        rule = "Path(`/net/test`)"
        service = "my-service"
        middlewares = ["http-forward-https"]
    [http.middlewares]
        [http.middlewares.http-forward-https.httpForwardHttps]
        [http.middlewares.http-forward-https.httpForwardHttps.tls]
            ca = "/etc/traefik/ca.crt"
            cert = "/etc/traefik/client.crt"
            key = "/etc/traefik/client.pem"
            serverName = "my-service"
        [http.middlewares.rate-limit.rateLimit]
          average = 40000
          burst = 70000
        [http.middlewares.rate-limit-net.rateLimit]
          average = 25000
          burst = 50000
    [http.services]
      [http.services.my-service.loadBalancer]
        [[http.services.my-service.loadBalancer.servers]]
          url = "https://www.baidu.com"
 

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐