将请求代理到服务
本教程介绍如何通过 Ingress Controller 配置路由,并验证请求能否经网关转发到集群中的示例服务。
前置条件
开始前,请完成以下准备:
- 完成设置 Ingress Controller 和网关。
- 如果使用 API7 Dashboard,请将示例命名空间
aic替换为生成的清单中显示的命名空间。 - 如果使用 API7 Dashboard,请将示例 Gateway 或 IngressClass 名称
apisix替换为生成的清单中对应的名称。 - 共享的 Kubernetes API 标识符(包括
apisix.apache.org和ApisixRoute)应保持不变。
部署示例上游服务
创建以下 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
创建路由
创建一个路由 manifest,将请求代理到 HTTPBIN 示例服务:
- Gateway API
- Ingress
- APISIX CRD
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
httpbin-route.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
namespace: aic
name: getting-started-ip
spec:
ingressClassName: apisix
rules:
- http:
paths:
- backend:
service:
name: httpbin
port:
number: 80
path: /ip
pathType: Exact
httpbin-route.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: getting-started-ip
spec:
ingressClassName: apisix
http:
- name: getting-started-ip
match:
paths:
- /ip
backends:
- serviceName: httpbin
servicePort: 80
应用路由 manifest:
kubectl apply -f httpbin-route.yaml
验证路由
将网关 Service 端口暴露到本地机器。APISIX 本地安装使用 aic;API7 Dashboard 安装则使用在 Dashboard 中选择的命名空间:
# 替换为你的网关 Service 名称
kubectl port-forward svc/<gateway-service-name> -n <namespace> 18080:80 &
示例使用本地端口 18080,因此可以与占用 9080 端口的快速入门网关同时运行。如果 18080 已被占用,请选择其他可用的本地端口,并在下面的请求中使用该端口。
向路由发送请求:
curl "http://127.0.0.1:18080/ip"
你应收到类似以下内容的 HTTPBIN 响应。origin 的值取决于 HTTPBIN 看到的客户端地址:
{
"origin": "127.0.0.1"
}
删除路由
删除路由:
kubectl delete -f httpbin-route.yaml
下一步
继续阅读常见用例,了解用于流量控制、身份认证、转换和可观测性的插件。