Kubernetes

[ Kans 3 Study - 7w ] 2. Bookinfo 실습 & Istio 기능

su''@ 2024. 10. 19. 15:10

CloudNetaStudy - Kubernets Networtk 3기 실습 스터디 게시글입니다.

 

5. Bookinfo 실습 & Istio 기능

 

[5.1 Bookinfo]

  • Bookinfo 애플리케이션 소개 : 4개의 마이크로서비스로 구성 : Productpage, reviews, ratings, details - 링크
      • ProductPage 페이지에서 요청을 받으면, 도서 리뷰를 보여주는 Reviews 서비스와 도서 상세 정보를 보여주는 Details 서비스에 접속하고,
      • ProductPage 는 ReviewsDetails 결과를 사용자에게 응답한다.
      • Reviews 서비스는 v1, v2, v3 세 개의 버전이 있고 v2, v3 버전의 경우 Ratings 서비스에 접소갛여 도서에 대한 5단계 평가를 가져옴.
      • Reviews 서비스의 차이는, v1은 Rating 이 없고, v2는 검은색 별로 Ratings 가 표시되며, v3는 색깔이 있는 별로 Ratings 가 표시됨.
      • (도서 참고 정보) [실수연발](http://www.webegt.com./cgi-bin/egt/read.cgi?board=Shakespeare&y_number=7&nnew=2) (셰익스피어) Wikipedia
      • Bookinfo 애플리케이션 배포 - 링크
        출처 : https://kschoi728.tistory.com/271
        # 모니터링
        watch -d 'kubectl get pod -owide;echo;kubectl get svc'
        
        # Bookinfo 애플리케이션 배포
        echo $ISTIOV
        cat ~/istio-$ISTIOV/samples/bookinfo/platform/kube/bookinfo.yaml
        kubectl apply -f ~/istio-$ISTIOV/samples/bookinfo/platform/kube/bookinfo.yaml
        
        # 확인
        kubectl get all,sa
        
        # product 웹 접속 확인
        kubectl exec "$(kubectl get pod -l app=ratings -o jsonpath='{.items[0].metadata.name}')" -c ratings -- curl -sS productpage:9080/productpage | grep -o "<title>.*</title>"
        
        # 로그
        kubetail -l app=productpage -f

 

 

[ 5. 2 Istio 를 통한 인입 기본 설정 ]

  • Istio Gateway/VirtualService 설정
    • bookinfo-gateway.yaml
      apiVersion: networking.istio.io/v1alpha3
      kind: Gateway
      metadata:
        name: bookinfo-gateway
      spec:
        # The selector matches the ingress gateway pod labels.
        # If you installed Istio using Helm following the standard documentation, this would be "istio=ingress"
        selector:
          istio: ingressgateway # use istio default controller
        servers:
        - port:
            number: 8080
            name: http
            protocol: HTTP
          hosts:
          - "*"
      ---
      apiVersion: networking.istio.io/v1alpha3
      kind: VirtualService
      metadata:
        name: bookinfo
      spec:
        hosts:
        - "*"
        gateways:
        - bookinfo-gateway
        http:
        - match:
          - uri:
              exact: /productpage
          - uri:
              prefix: /static
          - uri:
              exact: /login
          - uri:
              exact: /logout
          - uri:
              prefix: /api/v1/products
          route:
          - destination:
              host: productpage
              port:
                number: 9080

      # Istio Gateway/VirtualService 설정
      cat ~/istio-$ISTIOV/samples/bookinfo/networking/bookinfo-gateway.yaml
      kubectl apply -f ~/istio-$ISTIOV/samples/bookinfo/networking/bookinfo-gateway.yaml
      
      # 확인
      kubectl get gw,vs
      istioctl proxy-status
      NAME                                                   CLUSTER        CDS                LDS                EDS                RDS                ECDS        ISTIOD                      VERSION
      details-v1-65cfcf56f9-4drsk.default                    Kubernetes     SYNCED (7m4s)      SYNCED (7m4s)      SYNCED (6m57s)     SYNCED (7m4s)      IGNORED     istiod-7f8b586864-mv944     1.23.2
      istio-ingressgateway-5f9f654d46-c4g7s.istio-system     Kubernetes     SYNCED (3m7s)      SYNCED (3m7s)      SYNCED (6m57s)     SYNCED (3m7s)      IGNORED     istiod-7f8b586864-mv944     1.23.2
      productpage-v1-d5789fdfb-5cr6m.default                 Kubernetes     SYNCED (6m59s)     SYNCED (6m59s)     SYNCED (6m57s)     SYNCED (6m59s)     IGNORED     istiod-7f8b586864-mv944     1.23.2
      ratings-v1-7c9bd4b87f-9q4nv.default                    Kubernetes     SYNCED (7m3s)      SYNCED (7m3s)      SYNCED (6m57s)     SYNCED (7m3s)      IGNORED     istiod-7f8b586864-mv944     1.23.2
      reviews-v1-6584ddcf65-rqgp7.default                    Kubernetes     SYNCED (7m2s)      SYNCED (7m2s)      SYNCED (6m57s)     SYNCED (7m2s)      IGNORED     istiod-7f8b586864-mv944     1.23.2
      reviews-v2-6f85cb9b7c-h6m7p.default                    Kubernetes     SYNCED (7m2s)      SYNCED (7m2s)      SYNCED (6m57s)     SYNCED (7m2s)      IGNORED     istiod-7f8b586864-mv944     1.23.2
      reviews-v3-6f5b775685-rprpb.default                    Kubernetes     SYNCED (6m58s)     SYNCED (6m58s)     SYNCED (6m57s)     SYNCED (6m58s)     IGNORED     istiod-7f8b586864-mv944     1.23.2
      
      # productpage 파드의 istio-proxy 로그 확인 Access log 가 출력 - Default access log format : 링크
      kubetail -l app=productpage -c istio-proxy -f
  • Istio 를 통한 productpage 접속(반복) 테스트 & 웹 브라우저 접속 테스트*
    출처 : https://kschoi728.tistory.com/271
    • k3s-s NodePort 접속 확인
      #
      export IGWHTTP=$(kubectl get service -n istio-system istio-ingressgateway -o jsonpath='{.spec.ports[1].nodePort}')
      echo $IGWHTTP
      32759
      
      # 접속 확인
      kubectl get svc -n istio-system istio-ingressgateway
      curl -s http://localhost:$IGWHTTP/productpage
      curl -s http://192.168.10.101:$IGWHTTP/productpage
      curl -s http://192.168.10.102:$IGWHTTP/productpage
      
      # 정보 확인
      echo $MYDOMAIN
      cat /etc/hosts
      
      #
      curl -s http://$MYDOMAIN:$IGWHTTP/productpage

    • 자신의 PC에서 접속 확인
      #
      echo $MYDOMAIN $IGWHTTP
      cat /etc/hosts
      
      #
      curl -v -s $MYDOMAIN:$IGWHTTP/productpage
      echo -e "http://$MYDOMAIN:$IGWHTTP/productpage"
      
      #
      aws ec2 describe-instances --query "Reservations[*].Instances[*].{PublicIPAdd:PublicIpAddress,InstanceName:Tags[?Key=='Name']|[0].Value,Status:State.Name}" --filters Name=instance-state-name,Values=running --output text
      - 자신의 PC 에서 도메인으로 접속이 되지 않을 경우, 노드의 http://IP:port 로 변경해서 접속 할 것.


    • testpc 에서 접속 실행*
      # istio ingress gw 를 통한 접속 테스트
      curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>"
      while true; do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; echo "--------------" ; sleep 1; done
      for i in {1..100};  do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; done

      • 자신의 PC 에서 웹 브라우저를 통해서 http://NodeIP:NodePort/productpage 로 접속 후 새로고침 해보자 → ReviewsRatings 변경 확인!

[ 5.3 모니터링 - Blog ]

    • Kiali (키알리) 소개 : 주 데이터 소스(Prometheus, Jaeger)- 링크 링크2 링크3
    • Kiali is an observability console for Istio with service mesh configuration and validation capabilities. Kiali provides detailed metrics and a basic Grafana integration, which can be used for advanced queries. Distributed tracing is provided by integration with Jaeger.
      • Jaeger 와 연동을 통해서 분산 트레이싱을 제공할 수 있다
    • Monitoring port of the IstioD pod : Kiali connects directly to the IstioD pod (not the Service) to check for its health. By default, the connection is done to port 15014 which is the default monitoring port of the IstioD pod. 
      • 파드의 헬스체크Kiali 가 직접 IstioD 파드에 TCP Port 15014 를 통해서 체크한다
    • Prometheus, Jaeger and Grafana - 링크
      Prometheus
      and Jaeger are primary data sources for Kiali. This page describes how to configure Kiali to communicate with these dependencies. A minimalistic Grafana integration is also available.
      • 주 데이터 소스는 Prometheus and Jaeger 이며, 최소 수준의 Grafana 와 연동할 수 있다
    • Addon 설치 : Kiali (키알리) 대시보드 along with Prometheus, Grafana, and Jaeger - 링크
      • Istio integrates with several different telemetry applications. These can help you gain an understanding of the structure of your service mesh, display the topology of the mesh, and analyze the health of your mesh.
      • Use the following instructions to deploy the Kiali dashboard, along with PrometheusGrafana, and Jaeger.
        # Install Kiali and the other addons and wait for them to be deployed. : Kiali dashboard, along with Prometheus, Grafana, and Jaeger.
        tree ~/istio-$ISTIOV/samples/addons/
        kubectl apply -f ~/istio-$ISTIOV/samples/addons # 디렉터리에 있는 모든 yaml 자원을 생성
        kubectl rollout status deployment/kiali -n istio-system
        
        # 확인
        kubectl get all,sa,cm -n istio-system
        kubectl get svc,ep -n istio-system
        
        # kiali 서비스 변경
        kubectl patch svc -n istio-system kiali -p '{"spec":{"type":"NodePort"}}'
        
        # kiali 웹 접속 주소 확인
        KIALINodePort=$(kubectl get svc -n istio-system kiali -o jsonpath={.spec.ports[0].nodePort})
        echo -e "KIALI UI URL = http://$(curl -s ipinfo.io/ip):$KIALINodePort"
        
        # Grafana 서비스 변경
        kubectl patch svc -n istio-system grafana -p '{"spec":{"type":"NodePort"}}'
        
        # Grafana 웹 접속 주소 확인 : 7개의 대시보드
        GRAFANANodePort=$(kubectl get svc -n istio-system grafana -o jsonpath={.spec.ports[0].nodePort})
        echo -e "Grafana URL = http://$(curl -s ipinfo.io/ip):$GRAFANANodePort"
        
        # Prometheus 서비스 변경
        kubectl patch svc -n istio-system prometheus -p '{"spec":{"type":"NodePort"}}'
        
        # Prometheus 웹 접속 주소 확인
        PROMENodePort=$(kubectl get svc -n istio-system prometheus -o jsonpath={.spec.ports[0].nodePort})
        echo -e "Prometheus URL = http://$(curl -s ipinfo.io/ip):$PROMENodePort"

        • 프로메테우스 : Targets - 파드 별로 tcp 15020 에 /stats/prometheus
    • Kiali (키알리) 대시보드 둘러보기 - 링크
      • Namespacedefault 로 선택 후 Graph (Traffic, Versioned app graph) 에서 Display 옵션 중 ‘Traffic Distribution’ 과 ‘Traffic Animation’ 활성화! , Security 체크 해보자 (Last 1m, Evety 10s) Last 5m
      • k8s-rtr 에서 트래픽 요청 간격을 조절해보자 (1초, 0.5초, 0.3초, 0.1초)
        testpc 에서 아래 실행
        # 반복 접속 테스트
        while true; do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; echo "--------------" ; sleep 1; done
        while true; do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; echo "--------------" ; sleep 0.1; done
        while true; do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; echo "--------------" ; sleep 0.5; done
        for i in {1..100};  do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; done
        for i in {1..1000}; do curl -s $MYDOMAIN:$IGWHTTP/productpage | grep -o "<title>.*</title>" ; done

      • ApplicationsServices 측면에서의 정보를 확인해보자
      • Workloads 에서 Logs(istio-proxy, app) 를 확인할 수 있고, Envoy 관련 설정 정보(Clusters, Listeners, Routes, Config 등)를 편리하게 볼 수 있다
      • Istio Config 에서 Istio 관련 설정을 볼 수 있고, Action 으로 Istio 관련 오브젝트를 설정/삭제 할 수 있다

 

[ 5.4 Traffic Management ]

  • Traffic Managenet : 트래픽 컨트롤은 VirtualServiceDestinationRule 설정을 통해서 동작한다 - Concepts 링크
    출처 : https://faun.pub/on-premise-to-cloud-migration-mock-drills-using-istio-ea89aee5ea38
  • 동작 소개 : 클라이언트 PC → Istio ingressgateway 파드 → (Gateway, VirtualService + DestinationRule) → Cluster(Endpoint - 파드)
    • Gateway : 지정한 인그레스 게이트웨이로부터 트래픽이 인입, 프로토콜 및 포트, HOSTS, Proxy 등 설정 가능
    • VirtualService : 인입 처리할 hosts 설정, L7 PATH 별 라우팅, 목적지에 대한 정책 설정 가능 (envoy route config) - 링크
      • 사용 예시 : 헤더 매칭에 따라서, 각기 다른 destination 으로 라우팅
        • VirtualService 는 DestinationRule 에서 설정된 **서브셋(subset)**을 사용하여 트래픽 컨트롤을 할 수 있다
        • hosts 필드 : 목적지 주소 - IP address, a DNS name (FQDN), 혹은 k8s svc 이름 , wildcard (”*”) prefixes
        • Routing rules : HTTP 경우 - Match 필드(예, 헤더) , Destination(istio/envoy 에 등록된 대상, subnet 에 DestinationRule 활용)
          • HTTPRoute : redirect , rewrite , fault(장애 주입) , mirror(복제, 기본 100%) , corsPolicy(CORS 삽입) , headers(헤더 조작) 등 - 링크
        • Routing rule precedence : Routing rules are evaluated in sequential order from top to bottom - 위에서 순차적 적용
    • DestinationRule : 실제 도착지(서비스와 1:1 연결)의 정교한 정책(부하분산, 연결 옵션, 서킷 브레이크, TLS 등)을 설정 - 링크
      • 사용 예시 : 3개의 subsets for the my-svc destination service 에 3개의 subsets 이 있고, 이중 v1/v3 은 RAMDOM 이고 v2 는 ROUND_ROBIN
        apiVersion: networking.istio.io/v1alpha3
        kind: DestinationRule
        metadata:
          name: my-destination-rule
        spec:
          host: my-svc
          trafficPolicy:
            loadBalancer:
              simple: RANDOM
          subsets:
          - name: v1
            labels:
              version: v1
          - name: v2
            labels:
              version: v2
            trafficPolicy:
              loadBalancer:
                simple: ROUND_ROBIN
          - name: v3
            labels:
              version: v3
        • Load balancing options : Round robin(기본값) , Random , Weighted , Least requests - 링크
          • Destination Rule : TrafficPolicy , Subset , ConnectionPoolSettings 등 - 링크
          • 서브셋(subsets)을 정의할 수 있어 마이크로서비스 버전별로 라우팅할 때 사용한다
  • Request Routing - 링크