将请求代理到服务
本教程介绍如何使用 Ingress Controller 创建一条基础路由,将请求代理到集群中运行的示例服务,并验证路由是否正常工作。
前置条件
启动示例上游服务
创建以下 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 示例上游服务:
- 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
将配置应用到集群:
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
下一步
现在你已经了解如何通过路由代理请求。接下来可以继续了解插件生态提供的更多能力。