文档首页/ 华为云UCS/ 常见问题/ 服务网格/ 如何使用Istio API配置网关路由规则
更新时间:2024-09-26 GMT+08:00
分享

如何使用Istio API配置网关路由规则

ASM支持使用Istio API(Gateway, VirtualService, DestinationRule)配置网关、路由规则策略。本文介绍如何通过YAML创建资源对象启用该能力。

  1. 使用以下内容,保存为deployment.yaml文件,创建istio-ingressgateway deployment工作负载。

    kind: Deployment
    apiVersion: apps/v1
    metadata:
      name: istio-ingressgateway 
      namespace: default # 命名空间名称,按需替换
    spec:
      replicas: 1 # 工作负载实例数,按需替换
      selector:
        matchLabels:
          app: istio-ingressgateway
          istio: ingressgateway
      template:
        metadata:
          labels:
            app: istio-ingressgateway
            istio: ingressgateway
            istio.io/rev: default
            service.istio.io/canonical-name: istio-ingressgateway
            service.istio.io/canonical-revision: latest
            sidecar.istio.io/inject: 'false'
          annotations:
            sidecar.istio.io/inject: 'false'
        spec:
          volumes:
            - name: workload-socket
              emptyDir: {}
            - name: credential-socket
              emptyDir: {}
            - name: workload-certs
              emptyDir: {}
            - name: istiod-ca-cert
              configMap:
                name: istio-ca-root-cert
                defaultMode: 384
            - name: podinfo
              downwardAPI:
                items:
                  - path: labels
                    fieldRef:
                      apiVersion: v1
                      fieldPath: metadata.labels
                  - path: annotations
                    fieldRef:
                      apiVersion: v1
                      fieldPath: metadata.annotations
                defaultMode: 416
            - name: istio-envoy
              emptyDir: {}
            - name: istio-data
              emptyDir: {}
            - name: istio-token
              secret:
                defaultMode: 420
                optional: false
                secretName: cp-access-default
            - name: config-volume
              configMap:
                name: istio
                defaultMode: 416
                optional: true
            - name: ingressgateway-certs
              secret:
                secretName: istio-ingressgateway-certs
                defaultMode: 384
                optional: true
            - name: ingressgateway-ca-certs
              secret:
                secretName: istio-ingressgateway-ca-certs
                defaultMode: 384
                optional: true
          containers:
            - name: istio-proxy
              image: swr.cn-north-7.myhuaweicloud.com/asm/proxyv2:1.15.5-r1-20230719152011 # proxyv2镜像地址替换
              args:
                - proxy
                - router
                - '--domain'
                - $(POD_NAMESPACE).svc.cluster.local
                - '--proxyLogLevel=warning'
                - '--proxyComponentLogLevel=misc:error'
                - '--log_output_level=default:info'
              ports:
                - containerPort: 15021
                  protocol: TCP
                - containerPort: 8080
                  protocol: TCP
                - containerPort: 8443
                  protocol: TCP
                - name: http-envoy-prom
                  containerPort: 15090
                  protocol: TCP
              env:
                - name: JWT_POLICY
                  value: third-party-jwt
                - name: PILOT_CERT_PROVIDER
                  value: istiod
                - name: CA_ADDR
                  value: asm-mesh.kube-system.svc.cluster.local:15012
                - name: NODE_NAME
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: spec.nodeName
                - name: POD_NAME
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: metadata.name
                - name: POD_NAMESPACE
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: metadata.namespace
                - name: INSTANCE_IP
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: status.podIP
                - name: PROXY_CONFIG
                  value: | 
                    {"discoveryAddress":"asm-mesh.kube-system.svc.cluster.local:15012"}
                - name: HOST_IP
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: status.hostIP
                - name: SERVICE_ACCOUNT
                  valueFrom:
                    fieldRef:
                      apiVersion: v1
                      fieldPath: spec.serviceAccountName
                - name: ISTIO_META_WORKLOAD_NAME
                  value: istio-ingressgateway
                - name: ISTIO_META_OWNER
                  value: kubernetes://apis/apps/v1/namespaces/default/deployments/istio-ingressgateway  # default替换为对应的命名空间名称
                - name: ISTIO_META_MESH_ID
                  value: whtest # 替换为实际的网格名称
                - name: TRUST_DOMAIN
                  value: cluster.local
                - name: ISTIO_META_UNPRIVILEGED_POD
                  value: 'true'
                - name: ISTIO_ADDITIONAL_METADATA_EXCHANGE_KEYS
                  value: ASM_MESH_ID,ASM_CLUSTER_ID
                - name: ISTIO_META_ASM_CLUSTER_ID
                  value: 92311000-df43-11ed-b108-0255ac1001bb # 替换为实际的集群ID
                - name: ISTIO_META_ASM_MESH_ID
                  value: a8653674-3fd2-11ee-9e48-0255ac100695 # 替换为实际的网格ID
                - name: ISTIO_META_CLUSTER_ID
                  value: mesh-test # 替换为实际的集群名称
              resources:
                limits:
                  cpu: '2'
                  memory: 1Gi
                requests:
                  cpu: 100m
                  memory: 128Mi
              volumeMounts:
                - name: workload-socket
                  mountPath: /var/run/secrets/workload-spiffe-uds
                - name: credential-socket
                  mountPath: /var/run/secrets/credential-uds
                - name: workload-certs
                  mountPath: /var/run/secrets/workload-spiffe-credentials
                - name: istio-envoy
                  mountPath: /etc/istio/proxy
                - name: config-volume
                  mountPath: /etc/istio/config
                - name: istiod-ca-cert
                  mountPath: /var/run/secrets/istio
                - name: istio-token
                  readOnly: true
                  mountPath: /var/run/secrets/tokens
                - name: istio-data
                  mountPath: /var/lib/istio/data
                - name: podinfo
                  mountPath: /etc/istio/pod
                - name: ingressgateway-certs
                  readOnly: true
                  mountPath: /etc/istio/ingressgateway-certs
                - name: ingressgateway-ca-certs
                  readOnly: true
                  mountPath: /etc/istio/ingressgateway-ca-certs
              readinessProbe:
                httpGet:
                  path: /healthz/ready
                  port: 15021
                  scheme: HTTP
                initialDelaySeconds: 1
                timeoutSeconds: 1
                periodSeconds: 2
                successThreshold: 1
                failureThreshold: 30
              terminationMessagePath: /dev/termination-log
              terminationMessagePolicy: File
              imagePullPolicy: IfNotPresent
              securityContext:
                capabilities:
                  drop:
                    - ALL
                privileged: false
                readOnlyRootFilesystem: true
                allowPrivilegeEscalation: false
          restartPolicy: Always
          terminationGracePeriodSeconds: 30
          dnsPolicy: ClusterFirst
          securityContext:
            runAsUser: 1337
            runAsGroup: 1337
            runAsNonRoot: true
            fsGroup: 1337
            seccompProfile:
              type: RuntimeDefault
          affinity:
            nodeAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
                - weight: 1
                  preference:
                    matchExpressions:
                      - key: istio
                        operator: In
                        values:
                          - master
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                - labelSelector:
                    matchExpressions:
                      - key: app
                        operator: In
                        values:
                          - istio-ingressgateway
                  topologyKey: kubernetes.io/hostname
          schedulerName: default-scheduler
          tolerations:
            - key: istio
              operator: Exists
              effect: NoExecute
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxUnavailable: 1
          maxSurge: 10%
      revisionHistoryLimit: 10
      progressDeadlineSeconds: 600

    执行以下命令,在当前集群中创建网关工作负载。

    kubectl create -f deployment.yaml

  2. 使用以下内容,保存为svc.yaml文件,创建istio-ingressgateway loadbalancer service。

    apiVersion: v1
    kind: Service
    metadata:
      name: gw-svc1
      namespace: default # 命名空间名称,按需替换
      annotations:
        kubernetes.io/elb.class: union # elb实例类型,union共享型,performance独享型
        kubernetes.io/elb.id: 73febb1c-b191-4fd9-832e-138b2657d3b1 # elb实例ID,可通过在cce服务发现创建负载均衡类型服务页查看可选择的elb实例
    spec:
      ports:
        - name: http-gw-svc1-port1 # 端口名称,注意以服务协议打头
          protocol: TCP
          port: 707 # 对外访问端口
          targetPort: 1026 # 容器端口,必须大于1024,且不能与网格内其他网关服务使用的targetPort端口重复
      selector:
        app: istio-ingressgateway
        istio: ingressgateway
      type: LoadBalancer
      sessionAffinity: None
      externalTrafficPolicy: Cluster
      ipFamilies:
        - IPv4
      ipFamilyPolicy: SingleStack
      allocateLoadBalancerNodePorts: true
      internalTrafficPolicy: Cluster

    执行以下命令,在当前集群中创建网关工作负载对应的loadbalancer service。

    kubectl create -f svc.yaml

    以上步骤1、2使用的kubectl连接的是当前集群。

  3. 使用以下内容,保存为gw.yaml文件,创建Istio Gateway配置。

    apiVersion: networking.istio.io/v1beta1
    kind: Gateway
    metadata:
      name: my-gateway
      namespace: default # 命名空间名称,按需替换
    spec:
      selector:
        istio: ingressgateway
      servers: 
        - hosts:
            - 100.85.115.86 # 使用的elb实例公网IP
          port:
            name: http-48382bd9
            number: 1026 # 同上lb svc的targetPort
            protocol: http

    执行以下命令,在网格控制面中创建网关Gateway资源对象。

    kubectl create -f gw.yaml

  4. 使用以下内容,保存为vs.yaml文件,创建Istio VirtualService配置。

    apiVersion: networking.istio.io/v1beta1
    kind: VirtualService
    metadata:
      name: nginx
      namespace: default # 命名空间名称,按需替换
    spec:
      hosts:
      - 100.95.150.38  # 使用的elb实例公网IP
      gateways:
      - default/my-gateway # 使用步骤3的gw的命名空间、名称
      http:
      - match:
        - headers:
            cookie:
              exact: "user=dev-123"
        route:
        - destination:
            port:
              number: 1234
            host: nginx.default.svc.cluster.local
    

    执行以下命令,在网格控制面中创建VirtualService资源对象。

    kubectl create -f vs.yaml

    以上步骤3、4使用的kubectl连接的是网格控制面,如何配置网格kubectl,请参考使用kubectl连接网格控制面

  5. 结果验证。执行以下命令,访问nginx服务成功。

相关文档