使用 appProtocol 检测上游协议
appProtocol 是 Service 端口上的可选字段,用于说明后端期望接收的流量类型。Ingress Controller 可以使用该值自动判断上游协议。
本文介绍 Ingress Controller 如何读取 Kubernetes Service 中的 appProtocol 字段,并将其转换为网关中的上游配置。
支持的 appProtocol 值
Ingress Controller 支持在 Service 端口中使用以下 appProtocol 值:
| 值 | 说明 |
|---|---|
http | 将上游协议设置为 http。 |
https | 将上游协议设置为 https。 |
kubernetes.io/ws | 将上游协议设置为 http,并在路由上将 enable_websocket 设置为 true。 |
kubernetes.io/wss | 将上游协议设置为 https,并在路由上将 enable_websocket 设置为 true。 |
如果未指定 appProtocol,默认使用 http 协议。
引用 ExternalName Service 的 HTTPRoute 与 Ingress 使用相同的 appProtocol 检测逻辑。请定义被引用的 Service 端口及其 appProtocol;控制器会解析外部 DNS 名称,并应用所选上游协议。
定义 Kubernetes Service
假设你要暴露上游服务 httpbin。可以在 Service 中使用 appProtocol 指明每个端口期望的协议:
httpbin-service.yaml
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin
spec:
selector:
app: httpbin
ports:
- name: http
port: 80
targetPort: 80
appProtocol: http
- name: https
port: 443
targetPort: 443
appProtocol: https
创建路由
创建引用指定 Service 端口的路由。Ingress Controller 会读取被引用端口关联的 appProtocol 值,并据此自动配置上游协议。
在本示例中,路由会指向 Service 的 443 端口,该端口配置了 appProtocol: https。因此无需额外配置,上游协议会自动设置为 https。
- Gateway API
- Ingress
- APISIX CRD
httpbin-https.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: httpbin-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /anything
backendRefs:
- name: httpbin
port: 443
httpbin-https.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
namespace: aic
name: httpbin-route
spec:
ingressClassName: apisix
rules:
- http:
paths:
- path: /anything
pathType: Exact
backend:
service:
name: httpbin
port:
number: 443
httpbin-https.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: httpbin-route
spec:
ingressClassName: apisix
http:
- name: httpbin-route
match:
paths:
- /anything
backends:
- serviceName: httpbin
servicePort: 443
将配置应用到集群:
kubectl apply -f httpbin-https.yaml