Traefik Middleware 的使用
Mr.Lee 2025-05-06 19:59:23 favorKubernetesTraefik
书接上回, 上次咱们将 own-open-apis
项目, 并接入kubernetes
的环境中. 并对服务状态检查做出了相应优化. 但是没有对网关配置做优化, 今天我们针对这部分做一些调整吧~
完整的代码在这里呦, 欢迎大家 star
, fork
哈~ 同时欢迎大家提Issues
, PR
哈~
闲言少叙, 开始正文
上一次引入了SpirngBoot Actuator
模块后, 使得/own/open/api/v1/actuator/**
也都开放出来了, 这些本来是不用开放的...今天我们就通过 Traefik
的 Middleware
屏蔽掉这些外部无用的 web接口.
# 1. 修改 Tomcat 的 context-path
server:
servlet:
context-path: /
1
2
3
2
3
这样 Actuator 相关的内容就可以通过
/actuator/**
# 2. 添加网关转发的中间件
{{- if .Values.app.ingress.enabled -}}
# 创建网关转发的中间件
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: {{ include "own-open-apis.name" . }}-gateway-forwarder
namespace: {{ .Release.Namespace }}
spec:
replacePathRegex:
regex: "^/own/open(/.*)"
replacement: "$1"
# stripPrefix:
# prefixes:
# - "/own/open"
# forceSlash: false
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: {{ include "own-open-apis.name" . }}-ingress
namespace: {{ .Release.Namespace }}
labels:
{{ include "own-open-apis.labels" . | indent 4 }}
spec:
entryPoints:
- web
routes:
- match: PathPrefix(`{{ .Values.app.ingress.path }}`)
kind: Rule
middlewares:
- name: {{ include "own-open-apis.name" . }}-gateway-forwarder
services:
- name: {{ include "own-open-apis.name" . }}-service
port: 80 # 这里的80 要配合 service 的port 一起改哈~
{{- end -}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
举例说明:
请求:
/own/open/api/v1/app/down
会被转发到/api/v1/app/down
请求.
结合以上特性, 就可以通过 .Values.app.ingress.path
来控制, Actuator 相关的内容是否开放了.
- 在需要开放时,
.Values.app.ingress.path
的值为/own/open
, 让 traefik 的Rule
可以匹配到/own/open/actuator/health/liveness
- 在不需要开放时,
.Values.app.ingress.path
的值为/own/open/api
, 让 traefik 的Rule
可以匹配不到/own/open/actuator/health/liveness
# 3. 效果展示
# 参考文献:
- https://doc.traefik.io/traefik/middlewares/http/replacepathregex/