istio从入门到精通(1)

发布于:2025-03-11 ⋅ 阅读:(19) ⋅ 点赞:(0)

1、以单个的nginx举例

部署nginx服务

# nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.19.0
        ports:
        - containerPort: 80
---
# nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
kubectl apply -f nginx.yml

启用istio

kubectl label namespace default istio-injection=enabled

我们需要重新部署nginx服务

kubectl delete -f nginx.yaml
kubectl apply -f nginx.yaml

我们需要部署istio gateway 和vs服务

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: nginx-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "*"
---
# nginx-virtualservice.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: nginx
spec:
  hosts:
  - "*"
  gateways:
  - nginx-gateway
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: nginx
        port:
          number: 80

使用 kubectl 部署 Gateway 和 VirtualService:

kubectl apply -f nginx-gateway.yaml
kubectl apply -f nginx-virtualservice.yaml

访问 Nginx 服务

kubectl get svc istio-ingressgateway -n istio-system

然后,使用该 IP 地址访问 Nginx:

curl http://<INGRESS_GATEWAY_IP>>

重点注意:
由于上面采用了hosts 字段的作用,我们需要了解其含义

当 hosts 设置为 "*" 时,表示该虚拟服务适用于所有通过 Istio Gateway 的请
求,无论请求的主机或域名是什么。意味着无论客户端请求的是 example.com、foo.bar 还是任何其他域名,Istio 都会将该请求路由到该虚拟服务中定义的规则。

注意事项

安全性:在生产环境中,使用 "*" 可能会带来安全风险,因为它会将所有流量路由到该虚
拟服务。建议明确指定适用的域名。
​优先级:如果有多个虚拟服务匹配同一个请求,Istio 会按照最长匹配原则选择最具体的
规则。例如,hosts: ["example.com"] 的优先级高于 hosts: ["*"]。```