Traefik是一个为了让部署微服务更加便捷而诞生的现代HTTP反向代理、负载均衡工具。 它可以支持多种后端 (Docker, Swarm, Kubernetes, Marathon, Mesos, Consul, Etcd, Zookeeper, BoltDB, Rest API, file…) 来自动化、动态的应用它的配置文件设置。
让我们通过Traefik的架构图,来了解下Traefik中的几个核心的组件。
从上述架构图中,我们可以看到进入到Traefik的请求会经过以下路径到达最终的服务端:
Requests -》Entrypoints -》Routers(Rules,Middlewares)-》Services -》Server
EntryPoints:是请求进入Traefik的网络入口。Traefik通过EntryPoints定义了一些端口来接收请求,比如HTTP,TCP等。
Routers:职责是连接进入Traefik的请求和最终处理这些请求的服务。在这个过程中,Router有可能会使用一些middleware去对这些请求作出更新。
Services:职责在于配置如何让Routers将这些请求转发到最终处理这些请求的后端服务上。
为了测试方便,本文使用helm进行traefik的安装,在执行以下命令前,请确保你已经有一个可以正常工作的Kubernetes集群,并已经安装了helm v3版本。
通过以下三条命令就可以将traefik安装到你的K8S集群上:
$ helm repo add traefik https://containous.github.io/traefik-helm-chart
$ helm repo update
$ helm install traefik traefik/traefik
Traefik v2版本通过Kubernetes提供的CRD定义了以下核心的资源对象:
其中IngressRoute和IngressRouteTCP是Traefik最重要的CRD资源,它将Traefik中所有核心的概念关联到一起,最终实现了请求的中间处理,并最终转发到具体的服务。
以下为在K8S上定义一个IngressRoute的yaml配置文件,仅供参考。
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: ingressroutefoo
spec:
entryPoints:
- web
routes:
# Match is the rule corresponding to an underlying router.
# Later on, match could be the simple form of a path prefix, e.g. just "/bar",
# but for now we only support a traefik style matching rule.
- match: Host(`foo.com`) && PathPrefix(`/bar`)
# kind could eventually be one of "Rule", "Path", "Host", "Method", "Header",
# "Parameter", etc, to support simpler forms of rule matching, but for now we
# only support "Rule".
kind: Rule
# (optional) Priority disambiguates rules of the same length, for route matching.
priority: 12
services:
- name: whoami
port: 80
# (default 1) A weight used by the weighted round-robin strategy (WRR).
weight: 1
# (default true) PassHostHeader controls whether to leave the request's Host
# Header as it was before it reached the proxy, or whether to let the proxy set it
# to the destination (backend) host.
passHostHeader: true
responseForwarding:
# (default 100ms) Interval between flushes of the buffered response body to the client.
flushInterval: 100ms
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRouteTCP
metadata:
name: ingressroutetcpfoo.crd
spec:
entryPoints:
- footcp
routes:
# Match is the rule corresponding to an underlying router.
- match: HostSNI(`*`)
services:
- name: whoamitcp
port: 8080
除此之外,Traefik v2也提供了丰富的MiddleWares,通过CRD在K8S上定义和使用MiddleWares的方式如下所示:
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: stripprefix
spec:
stripPrefix:
prefixes:
- /stripit
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: ingressroute
spec:
# more fields...
routes:
# more fields...
middlewares:
- name: stripprefix
以上仅为本人对前期调研和使用Traefik的一点粗浅的理解,如有不当之处,请不吝赐教。