Traefik中间件middleware初体验
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.Traefik中间件概述
1.中间件在Traefik的位置
如上图所示,连接到路由器的中间件是在将请求发送到您的服务之前(或在将服务的答案发送到客户端之前)调整请求的一种手段。
Traefik中有几个可用的中间件,有些可以修改请求、标头,有些负责重定向,有些添加身份验证等等。
使用相同协议的中间件可以组合成链,以适应每种情况。官方支持HTTP和TCP两种中间件。
参考链接:
https://doc.traefik.io/traefik/middlewares/overview/
2.HTTP中间件
Middleware(中间件) | Purpose(作用) | Area(用途) |
---|---|---|
AddPrefix | Adds a Path Prefix | Path Modifier |
BasicAuth | Adds Basic Authentication | Security, Authentication |
Buffering | Buffers the request/response | Request Lifecycle |
Chain | Combines multiple pieces of middleware | Misc |
CircuitBreaker | Prevents calling unhealthy services | Request Lifecycle |
Compress | Compresses the response | Content Modifier |
ContentType | Handles Content-Type auto-detection | Misc |
DigestAuth | Adds Digest Authentication | Security, Authentication |
Errors | Defines custom error pages | Request Lifecycle |
ForwardAuth | Delegates Authentication | Security, Authentication |
Headers | Adds / Updates headers | Security |
IPAllowList | Limits the allowed client IPs | Security, Request lifecycle |
InFlightReq | Limits the number of simultaneous connections | Security, Request lifecycle |
PassTLSClientCert | Adds Client Certificates in a Header | Security |
RateLimit | Limits the call frequency | Security, Request lifecycle |
RedirectScheme | Redirects based on scheme | Request lifecycle |
RedirectRegex | Redirects based on regex | Request lifecycle |
ReplacePath | Changes the path of the request | Path Modifier |
ReplacePathRegex | Changes the path of the request | Path Modifier |
Retry | Automatically retries in case of error | Request lifecycle |
StripPrefix | Changes the path of the request | Path Modifier |
StripPrefixRegex | Changes the path of the request | Path Modifier |
如上表所示,官方针对HTTPP协议的中间件有很多。
参考链接:
https://doc.traefik.io/traefik/middlewares/http/overview/
3.TCP中间件
Middleware(中间件) | Purpose(作用) | Area(用途) |
---|---|---|
InFlightConn | Limits the number of simultaneous connections. | Security, Request lifecycle |
IPAllowList | Limit the allowed client IPs. | Security, Request lifecycle |
如上表所示,针对TCP协议的中间件相对较少。
参考链接:
https://doc.traefik.io/traefik/middlewares/tcp/overview/
二.traefik中间件实战案例
1. 部署测试服务
1.1 编写资源清单
[root@master241 ingressroutes]# cat 12-deploy-xiuxian.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy-xiuxian
spec:
replicas: 1
selector:
matchLabels:
apps: xiuxian
template:
metadata:
labels:
apps: xiuxian
spec:
containers:
- image: registry.cn-hangzhou.aliyuncs.com/yinzhengjie-k8s/apps:v1
name: c1
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: svc-xiuxian
spec:
ports:
- port: 80
selector:
apps: xiuxian
[root@master241 ingressroutes]#
1.2 创建资源
[root@master241 ingressroutes]# kubectl apply -f 12-deploy-xiuxian.yaml
deployment.apps/deploy-xiuxian created
service/svc-xiuxian created
[root@master241 ingressroutes]#
[root@master241 ingressroutes]# kubectl get deploy,svc,po -o wide
NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR
deployment.apps/deploy-xiuxian 1/1 1 1 8s c1 registry.cn-hangzhou.aliyuncs.com/yinzhengjie-k8s/apps:v1 apps=xiuxian
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
service/kubernetes ClusterIP 10.192.0.1 <none> 443/TCP 13s <none>
service/svc-xiuxian ClusterIP 10.194.9.32 <none> 80/TCP 8s apps=xiuxian
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod/deploy-xiuxian-55f8cbccd9-xdsgs 1/1 Running 0 8s 10.100.207.44 worker243 <none> <none>
[root@master241 ingressroutes]#
1.3 访问测试
[root@master241 ingressroutes]# curl 10.194.9.32
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>yinzhengjie apps v1</title>
<style>
div img {
width: 900px;
height: 600px;
margin: 0;
}
</style>
</head>
<body>
<h1 style="color: green">凡人修仙传 v1 </h1>
<div>
<img src="1.jpg">
<div>
</body>
</html>
[root@master241 ingressroutes]#
2.ipWhiteList|ipallowlist应用案例
2.1 ipWhiteList|ipallowlist中间件概述
在实际工作中,有一些URL并不希望对外暴露,比如prometheus、grafana等,我们就可以通过白名单IP来过到要求,可以使用Traefix中的ipWhiteList中间件来完成。
ipWhiteList组件可以限制客户端的IP地址是否可以进行访问,如果在白名单则允许访问,目前官方支持http和tcp两种配置方式。
值得注意的是,ipwhitelist官方已经弃用,推荐使用ipallowlist来替代。
参考链接:
https://doc.traefik.io/traefik/middlewares/http/ipwhitelist/ # 已经弃用,推荐使用ipallowlist
https://doc.traefik.io/traefik/middlewares/http/ipallowlist/
https://doc.traefik.io/traefik/middlewares/tcp/ipwhitelist/ # 已经弃用,推荐使用ipallowlist
https://doc.traefik.io/traefik/middlewares/tcp/ipallowlist/
2.2 编写资源清单
[root@master241 ingressroutes]# cat 13-ipAllowList-IngressRoute.yaml
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: xiuxian-ipallowlist
namespace: default
spec:
ipAllowList:
sourceRange:
- 127.0.0.1
- 10.0.0.0/24
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: ingressroute-xiuxian
spec:
entryPoints:
- web
routes:
- match: Host(`middleware.yinzhengjie.com`) && PathPrefix(`/`)
kind: Rule
services:
- name: svc-xiuxian
port: 80
middlewares:
- name: xiuxian-ipallowlist
namespace: default
[root@master241 ingressroutes]#
2.3 创建资源
[root@master241 ingressroutes]# kubectl apply -f 13-ipAllowList-IngressRoute.yaml
middleware.traefik.io/xiuxian-ipallowlist created
ingressroute.traefik.io/ingressroute-xiuxian created
[root@master241 ingressroutes]#
[root@master241 ingressroutes]# kubectl describe -f 13-ipAllowList-IngressRoute.yaml
Name: xiuxian-ipallowlist
Namespace: default
Labels: <none>
Annotations: <none>
API Version: traefik.io/v1alpha1
Kind: Middleware
Metadata:
Creation Timestamp: 2025-06-06T07:13:48Z
Generation: 1
Resource Version: 2185783
UID: 2a79b049-4a41-4fa8-8c17-c54fb823ca76
Spec:
Ip Allow List:
Source Range:
127.0.0.1
10.0.0.0/24
Events: <none>
Name: ingressroute-xiuxian
Namespace: default
Labels: <none>
Annotations: <none>
API Version: traefik.io/v1alpha1
Kind: IngressRoute
Metadata:
Creation Timestamp: 2025-06-06T07:13:48Z
Generation: 1
Resource Version: 2185784
UID: 84859639-4dd2-4806-9336-f70c2b7502c1
Spec:
Entry Points:
web
Routes:
Kind: Rule
Match: Host(`middleware.yinzhengjie.com`) && PathPrefix(`/`)
Middlewares:
Name: xiuxian-ipallowlist
Namespace: default
Services:
Name: svc-xiuxian
Port: 80
Events: <none>
[root@master241 ingressroutes]#
2.4 访问测试
1.访问测试
[root@worker242 ~]# echo 10.0.0.150 middleware.yinzhengjie.com >> /etc/hosts
[root@worker242 ~]# tail -1 /etc/hosts
10.0.0.150 middleware.yinzhengjie.com
[root@worker242 ~]#
2.可以成功访问
[root@worker242 ~]# curl middleware.yinzhengjie.com
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>yinzhengjie apps v1</title>
<style>
div img {
width: 900px;
height: 600px;
margin: 0;
}
</style>
</head>
<body>
<h1 style="color: green">凡人修仙传 v1 </h1>
<div>
<img src="1.jpg">
<div>
</body>
</html>
[root@worker242 ~]#
2.5 将白名单的地址删除测试
1.修改资源清单
[root@master241 ingressroutes]# cat 13-ipAllowList-IngressRoute.yaml
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: xiuxian-ipallowlist
namespace: default
spec:
ipAllowList:
sourceRange:
- 127.0.0.1
# - 10.0.0.0/24 # 将该行注释,目的是为了不让该网段的地址访问
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: ingressroute-xiuxian
spec:
entryPoints:
- web
routes:
- match: Host(`middleware.yinzhengjie.com`) && PathPrefix(`/`)
kind: Rule
services:
- name: svc-xiuxian
port: 80
middlewares:
- name: xiuxian-ipallowlist
namespace: default
[root@master241 ingressroutes]#
2.查看资源是否生效
[root@master241 ingressroutes]# kubectl apply -f 13-ipAllowList-IngressRoute.yaml
middleware.traefik.io/xiuxian-ipallowlist configured
ingressroute.traefik.io/ingressroute-xiuxian unchanged
[root@master241 ingressroutes]#
[root@master241 ingressroutes]# kubectl describe middleware xiuxian-ipallowlist
Name: xiuxian-ipallowlist
Namespace: default
Labels: <none>
Annotations: <none>
API Version: traefik.io/v1alpha1
Kind: Middleware
Metadata:
Creation Timestamp: 2025-06-06T07:13:48Z
Generation: 2
Resource Version: 2186500
UID: 2a79b049-4a41-4fa8-8c17-c54fb823ca76
Spec:
Ip Allow List:
Source Range:
127.0.0.1
Events: <none>
[root@master241 ingressroutes]#
2.6 再次访问测试
[root@worker242 ~]# curl middleware.yinzhengjie.com ;echo # Duang~不难发现,访问被拒绝啦!!!
Forbidden
[root@worker242 ~]#
3.Traefik中间件BasicAuth应用案例
3.1 basicAuth中间件概述
basicAuth中间件可以做基础的认证。
参考链接:
https://doc.traefik.io/traefik/middlewares/http/basicauth/
3.2.编写资源清单
[root@master241 ingressroutes]# cat 14-basicAuth-secrets-IngressRoute.yaml
apiVersion: v1
kind: Secret
metadata:
name: login-info
namespace: default
type: kubernetes.io/basic-auth
stringData:
username: JasonYin
password: yinzhengjie
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: login-auth
spec:
basicAuth:
secret: login-info
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: ingressroute-xiuxian
spec:
entryPoints:
- web
routes:
- match: Host(`middleware.yinzhengjie.com`) && PathPrefix(`/`)
kind: Rule
services:
- name: svc-xiuxian
port: 80
middlewares:
- name: login-auth
namespace: default
[root@master241 ingressroutes]#
3.3 创建并查看资源的状态
[root@master241 ingressroutes]# kubectl describe -f 14-basicAuth-secrets-IngressRoute.yaml
Name: login-info
Namespace: default
Labels: <none>
Annotations: <none>
Type: kubernetes.io/basic-auth
Data
====
password: 11 bytes
username: 8 bytes
Name: login-auth
Namespace: default
Labels: <none>
Annotations: <none>
API Version: traefik.io/v1alpha1
Kind: Middleware
Metadata:
Creation Timestamp: 2025-06-06T07:27:54Z
Generation: 1
Resource Version: 2187518
UID: bfb38efe-b967-4680-b6ba-fdc6f6154a74
Spec:
Basic Auth:
Secret: login-info
Events: <none>
Name: ingressroute-xiuxian
Namespace: default
Labels: <none>
Annotations: <none>
API Version: traefik.io/v1alpha1
Kind: IngressRoute
Metadata:
Creation Timestamp: 2025-06-06T07:27:54Z
Generation: 1
Resource Version: 2187519
UID: 29c5fe51-9074-469b-af53-36ecdd53a245
Spec:
Entry Points:
web
Routes:
Kind: Rule
Match: Host(`middleware.yinzhengjie.com`) && PathPrefix(`/`)
Middlewares:
Name: login-auth
Namespace: default
Services:
Name: svc-xiuxian
Port: 80
Events: <none>
[root@master241 ingressroutes]#
3.4 测试验证
1.不输入认证信息或者输入错误都会认证失败,报错401哟~
[root@worker242 ~]# curl middleware.yinzhengjie.com
401 Unauthorized
[root@worker242 ~]#
[root@worker242 ~]# curl -u admin:123 middleware.yinzhengjie.com
401 Unauthorized
[root@worker242 ~]#
2.使用认证信息就可以正确使用
[root@worker242 ~]# curl -u JasonYin:yinzhengjie middleware.yinzhengjie.com
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>yinzhengjie apps v1</title>
<style>
div img {
width: 900px;
height: 600px;
margin: 0;
}
</style>
</head>
<body>
<h1 style="color: green">凡人修仙传 v1 </h1>
<div>
<img src="1.jpg">
<div>
</body>
</html>
[root@worker242 ~]#
3.5 查看Traefik的WebUI
如上图所示,我们可以在Route配置中看到中间件的名称哟。
后记:
更多中间间玩法大家可以自行解锁,前提是你对负载均衡器的深度有一定的了解,不然学习Traefik可能有点不太好理解。
后续会陆续更新更多Traefik及Istio相关的课程笔记哟~欢迎各位道友一起探讨哈!
本文来自博客园,作者:尹正杰,转载请注明原文链接:https://www.cnblogs.com/yinzhengjie/p/18917210,个人微信: "JasonYin2020"(添加时请备注来源及意图备注,有偿付费)
当你的才华还撑不起你的野心的时候,你就应该静下心来学习。当你的能力还驾驭不了你的目标的时候,你就应该沉下心来历练。问问自己,想要怎样的人生。