使用 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 协议。
定义 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
验证上游 Scheme
如果你使用 API7 企业版,可以在 API7 控制台中看到该服务的上游协议 已设置为 https。
如果你使用 APISIX,可以通过 Admin API 查看上游协议。先将 Admin API 的 Service 端口转发到本地:
kubectl port-forward service/apisix-admin 9180:9180 &
假设 APISIX 以 独立模式启动,向 /apisix/admin/configs 发送请求以查看同步到网关的全部配置:
curl "http://127.0.0.1:9180/apisix/admin/configs" -H "X-API-KEY: ${ADMIN_API_KEY}" | jq
你应看到该服务的上游协议 已设置为 https:
{
"services_conf_version": 1767088219134,
"consumers_conf_version": 0,
"X-Last-Modified": 1767088880,
"X-Digest": "6cfa92e8e40d2554c621a72fb62311edc16c741d",
"services": [
{
"name": "aic_httpbin-route_0",
"upstream_id": "ee55f349",
...
}
],
"secrets_conf_version": 0,
"plugins_conf_version": 0,
"routes": [
{
...
}
],
"upstreams_conf_version": 1767088880723,
"global_rules_conf_version": 0,
"protos_conf_version": 0,
"routes_conf_version": 1767088219134,
"stream_routes_conf_version": 0,
"upstreams": [
{
"scheme": "https",
"labels": {
"managed-by": "apisix-ingress-controller"
},
"name": "aic_httpbin-route_0",
"id": "ee55f349"
...
}
],
"plugin_configs_conf_version": 0,
"consumer_groups_conf_version": 0,
"ssls_conf_version": 0,
"plugin_metadata_conf_version": 0
}