上一篇安装好Istio后,本篇开始使用 Istio 的 Ingress Gateway
官方教程地址
以下是学习过程的整理
安装 httpbin 提供http服务
# 进入Istio目录
cd istio-1.9.2/
# default命名空间启用sidecar自动注入
kubectl label namespace default istio-injection=enabled
# 部署 httpbin 服务
kubectl apply -f samples/httpbin/httpbin.yaml
由于是在本地环境,没有云环境的负载均衡器,必须使用服务的 node port 访问网关
# 临时设置 ingress 端口
export INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].nodePort}')
export SECURE_INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="https")].nodePort}')
# 临时设置 ingress host
export INGRESS_HOST=127.0.0.1
使用 Istio Gateway 配置 ingress
新建 istio-gateway.yaml 填入如下内容
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: httpbin-gateway
spec:
selector:
istio: ingressgateway # use Istio default gateway implementation
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "httpbin.example.com"
新建 gateway.yaml 填入如下内容
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: httpbin
spec:
hosts:
- "httpbin.example.com"
gateways:
- httpbin-gateway
http:
- match:
- uri:
prefix: /status
- uri:
prefix: /delay
route:
- destination:
port:
number: 8000
host: httpbin
以 http://httpbin.example.com/status 和 http://httpbin.example.com/delay 开头的请求将转发给 httpbin ,其他请求的返回结果是404
部署 gateway与虚拟服务
kubectl apply -f istio-gateway.yaml
kubectl apply -f gateway.yaml
使用 curl 访问 httpbin 服务,使用 -H 标识将 HTTP 头部参数 Host 设置为 “httpbin.example.com”
curl -I -HHost:httpbin.example.com http://$INGRESS_HOST:$INGRESS_PORT/status/200
删除部署
kubectl delete -f istio-gateway.yaml
kubectl delete -f gateway.yaml
集群外部访问httpbin服务
由于是本地环境,没有域名,集群外部无法访问 httpbin 服务,可在 Gateway 和 VirtualService 配置中使用通配符 *
新建 ingress-all-host.yaml ,将所有域名以 /headers 开头的请求都转给httpbin服务
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: httpbin-gateway
spec:
selector:
istio: ingressgateway # use Istio default gateway implementation
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: httpbin
spec:
hosts:
- "*"
gateways:
- httpbin-gateway
http:
- match:
- uri:
prefix: /headers
route:
- destination:
port:
number: 8000
host: httpbin
部署 ingress-all-host.yaml
kubectl apply -f ingress-all-host.yaml
使用curl访问服务,host是127.0.0.1
curl http://127.0.0.1:$INGRESS_PORT/headers
查看 $INGRESS_PORT
echo $INGRESS_PORT
宿主机浏览器可使用 http://集群主节点IP:INGRESS_PORT的值/headers 访问httpbin服务