3.3. 使用 Kubernetes 网关 API 通过网关直接出口流量
使用 Kubernetes 网关 API 通过出口网关直接出站 HTTP 流量。
先决条件
- 已安装 Istio control plane。
-
已配置了
Istio和IstioCNI资源。
流程
可选:启用 {k8} Gateway API 自定义资源定义(CRD)。
注意从 Kubernetes 1.28 和 OpenShift Container Platform 4.18 或更早版本 Red Hat OpenShift Service Mesh 开始,Kubernetes 网关 API CRD 默认不可用,且您必须在使用 CRD 前启用 CRD。OpenShift Container Platform 4.19 及更新的版本默认启用 CRD。
创建名为
gateway-cr.yaml的 YAML 文件,该文件启用 Kubernetes 网关 API CRD。Kubernetes 网关自定义资源(CR)文件示例
apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: info-gateway spec: gatewayClassName: istio listeners: - name: http port: 80 protocol: HTTP allowedRoutes: namespaces: from: Same --- apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: info spec: parentRefs: - name: info-gateway rules: - matches: - path: type: Exact value: /productpage - path: type: PathPrefix value: /static - path: type: Exact value: /login - path: type: Exact value: /logout - path: type: PathPrefix value: /api/v1/products backendRefs: - name: productpage port: 9080运行以下命令来应用 YAML 文件:
$ oc apply -f gateway-cr.yaml
运行以下命令,创建一个名为
egress-gateway的命名空间:$ oc create namespace egress-gateway运行以下命令,将
istio-injection标签应用到命名空间:$ oc label namespace egress-gateway istio-injection=enabled创建名为
egress-gateway-cr.yaml的 YAML 文件,用于定义出口网关。出口网关 CR 文件示例
# ServiceEntry to allow traffic to httpbin.org apiVersion: networking.istio.io/v1 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 80 name: http protocol: HTTP location: MESH_EXTERNAL resolution: DNS --- # Gateway API Gateway for egress apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: httpbin-egress-gateway annotations: networking.istio.io/service-type: ClusterIP spec: gatewayClassName: istio listeners: - name: http hostname: httpbin.org port: 80 protocol: HTTP allowedRoutes: namespaces: from: Same --- # HTTPRoute to direct traffic from sidecars to the egress gateway apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: direct-httpbin-to-egress-gateway spec: parentRefs: - kind: ServiceEntry group: networking.istio.io name: httpbin-ext rules: - backendRefs: - name: httpbin-egress-gateway-istio port: 80 --- # HTTPRoute to forward traffic from the egress gateway to httpbin.org apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: forward-httpbin-from-egress-gateway spec: parentRefs: - name: httpbin-egress-gateway hostnames: - httpbin.org rules: - backendRefs: - kind: Hostname group: networking.istio.io name: httpbin.org port: 80运行以下命令来应用 YAML 文件:
$ oc apply -f egress-gateway-cr.yaml
验证
运行以下命令,验证网关配置的状态:
$ oc describe gateway -n egress-gateway所需输出由
Programmed在Status列中显示。运行以下命令,在
egress-gateway命名空间中创建curlpod:$ oc run test-pod --image=curlimages/curl:latest -n egress-gateway --rm -it --restart=Never -- sh通过使用
curl客户端,输入以下命令验证您可以通过出口网关访问httpbin.org:$ curl -v http://httpbin.org/get所需输出显示
httpbin.org的响应,它表示通过配置的网关路由出口流量。