跳到主要内容

将请求代理到服务

本教程介绍如何通过 Ingress Controller 将请求代理到集群中的示例服务,并验证路由。

前置条件

  1. 完成设置 Ingress Controller 和网关

以下清单使用 APISIX 本地安装中的值。如果使用 API7 Dashboard,请进行以下替换:

APISIX 示例API7 替换值
aic 命名空间Dashboard 生成的清单中显示的命名空间
apisix Gateway 或 IngressClass生成的 Gateway 或 IngressClass 清单中显示的对应名称

共享的 Kubernetes API 标识符(包括 apisix.apache.orgApisixRoute)应保持不变。

启动示例上游服务

创建以下 Kubernetes manifest,在 aic 命名空间中部署一个 HTTPBIN 服务:

httpbin.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: aic
name: httpbin
spec:
replicas: 1
selector:
matchLabels:
app: httpbin
template:
metadata:
labels:
app: httpbin
spec:
containers:
- name: httpbin
image: kennethreitz/httpbin
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin
spec:
selector:
app: httpbin
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
type: ClusterIP

应用该 manifest:

kubectl apply -f httpbin.yaml

创建路由

创建一个 Kubernetes manifest 文件,用于将请求代理到 HTTPBIN 示例上游服务:

httpbin-route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: getting-started-ip
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /ip
backendRefs:
- name: httpbin
port: 80

将配置应用到集群:

kubectl apply -f httpbin-route.yaml

验证路由

将网关 Service 端口暴露到本地机器:

# 替换为你的网关 Service 名称
kubectl port-forward svc/<gateway-service-name> 9080:80 &

向路由发送请求:

curl "http://127.0.0.1:9080/ip"

你应看到如下响应:

{
"origin": "127.0.0.1"
}

删除路由

如需删除此前创建的路由,运行:

kubectl delete -f httpbin-route.yaml

下一步

现在你已经了解如何通过路由代理请求。接下来可以继续了解插件生态提供的更多能力。