[Kong 與 Konga 與 Postgres數據庫] 之 Kuberneres 部署

一、Kong的概述

Kong是一個clould-native、快速的、可擴展的、分佈式的微服務抽象層(也稱爲API網關、API中間件或在某些狀況下稱爲服務網格)框架。Kong做爲開源項目在2015年推出,它的核心價值是高性能和可擴展性。Kong被普遍用於從初創企業到全球5000家公司以及政府組織的生產環境中。html

若是構建Web、移動或IoT(物聯網)應用,可能最終須要使用通用的功能來實現這些應用。Kong充當微服務請求的網關(或側車),經過插件可以提供負載平衡日誌記錄、身份驗證、速率限制、轉換等能力。node

img

二、功能特性

  • 雲本土化(Cloud-Native):Kong能夠在Kubernetes或物理環境上運行;
  • 動態負載平衡(Dynamic Load Balancing):跨多個上游服務的負載平衡業務。
  • 基於哈希的負載平衡(Hash-based Load Balancing):一致的散列/粘性會話的負載平衡。
  • 斷路器(Circuit-Breaker):智能跟蹤不健康的上游服務。
  • 健康檢查(Health Checks):主動和被動監控您的上游服務。
  • 服務發現(Service Discovery):解決如Consul等第三方DNS解析器的SRV記錄。
  • 無服務器(Serverless):從Kong中直接調用和保證AWS或OpenWhisk函數安全。
  • WebSockets:經過WebSockets與上游服務進行通訊。
  • OAuth2.0:輕鬆的向API中添加OAuth2.0認證。
  • 日誌記錄(Logging):經過HTTP、TCP、UDP記錄請求或者相應的日誌,存儲在磁盤中。
  • 安全(Security):ACL,Bot檢測,IPs白名單/黑名單等。
  • 系統日誌(Syslog):記錄信息到系統日誌。
  • SSL:爲基礎服務或API設置特定的SSL證書。
  • 監視(Monitoring):可以實時對關鍵負載和性能指標進行監控。
  • 轉發代理(Forward Proxy):使端口鏈接到中間透明的HTTP代理。
  • 認證(Authentications):支持HMAC,JWT和BASIC方式進行認證等等。
  • 速率限制(Rate-limiting):基於多個變量的阻塞和節流請求。
  • 轉換(Transformations):添加、刪除或操做HTTP請求和響應。
  • 緩存(Caching):在代理層進行緩存和服務響應。
  • 命令行工具(CLI):可以經過命令行控制Kong的集羣。
  • REST API:能夠經過REST API靈活的操做Kong。
  • GEO複製:在不一樣的區域,配置老是最新的。
  • 故障檢測與恢復(Failure Detection & Recovery):若是Cassandra節點失效,Kong並不會受影響。
  • 羣集(Clustering):全部的Kong節點會自動加入羣集,並更新各個節點上的配置。
  • 可擴展性(Scalability):經過添加節點,實現水平縮放。
  • 性能(Performance):經過縮放和使用Nigix,Kong可以輕鬆處理負載。
  • 插件(Plugins):基於插件的可擴展體系結構,可以方便的向Kong和API添加功能。

三、Kong依賴的技術

Kong部署在Nginx和Apache Cassandra或PostgreSQL等可靠技術之上,並提供了易於使用的RESTful API來操做和配置系統。下面是Kong的技術邏輯圖。基於這些技術,Kong提供相關的特性支持:linux

  • Nginx
    • 通過驗證的高性能基礎;
    • HTTP和反向代理服務器;
    • 處理低層級的操做。
  • OpenRestry
    • 支持Lua腳本;
    • 攔截請求/響應生命週期;
    • 基於Nginx進行擴展。
  • Clustering&Datastore
    • 支持Cassandra或PostgreSQL數據庫;
    • 內存級的緩存;
    • 支持水平擴展。
  • Plugins
    • 使用Lua建立插件;
    • 功能強大的定製能力;
    • 與第三方服務實現集成。
  • Restful Administration API
    • 經過Restful API管理Kong;
    • 支持CI/CD&DevOps;
    • 基於插件的可擴展。

img

實踐Kong for Kubernetes

Kong以前都是使用Admin API來進行管理的,Kong主要暴露兩個端口管理端口8001和代理端口8000,管理Kong主要的是爲上游服務配置Service、Routes、Plugins、Consumer等實體資源,Kong按照這些配置規則進行對上游服務的請求進行路由分發和控制。在Kubernetes集羣環境下,Admin API方式不是很適應Kubernetes聲明式管理方式。因此Kong在Kubernetes集羣環境下推出Kong Ingress Controller。Kong Ingress Controller定義了四個CRDs(CustomResourceDefinitions),基本上涵蓋了原Admin API的各個方面。nginx

  • kongconsumers:Kong的用戶,給不一樣的API用戶提供不一樣的消費者身份。
  • kongcredentials:Kong用戶的認證憑證。
  • kongingresses:定義代理行爲規則,是對Ingress的補充配置。
  • kongplugins:插件的配置。
Kong建立的CRDs:

[root@localhost konga]# kubectl get crds
NAME                                          CREATED AT
kongclusterplugins.configuration.konghq.com   2020-08-12T13:16:56Z
kongconsumers.configuration.konghq.com        2020-08-12T13:16:56Z
kongcredentials.configuration.konghq.com      2020-08-12T13:16:56Z
kongingresses.configuration.konghq.com        2020-08-12T13:16:56Z
kongplugins.configuration.konghq.com          2020-08-12T13:16:56Z

先決條件

  • Kubernetes集羣:您可使用MinikubeGKE集羣。Kong與Kubernetes的全部發行版兼容。
  • kubectl訪問權限:您應該已經kubectl安裝並配置爲與Kubernetes集羣通訊。

爲Kubernetes安裝Kong

使用如下安裝方法之一安裝Kong for Kubernetes:git

YAML清單

要經過部署Kong kubectl,請使用:github

kubectl apply -f https://bit.ly/kong-ingress-dbless

重要!這不是生產級部署。根據您的用例調整「參數」:web

  • 副本:確保您正在運行Kong的多個實例,以防止因爲單個節點故障而形成的中斷。
  • 性能優化:調整Kong的內存設置,並根據使用狀況定製部署。
  • 負載均衡器:確保在Kong前面運行基於4層或TCP的均衡器。這使Kong能夠提供TLS證書並與證書管理器集成。

helm部署

Kong有一個官方的Helm Chart。要將Kong部署到帶有Helm的Kubernetes集羣上,請使用:sql

$ helm repo add kong https://charts.konghq.com
$ helm repo update

# Helm 2
$ helm install kong/kong

# Helm 3
$ helm install kong/kong --generate-name --set ingressController.installCRDs=false

Kustomize

可使用Kubernetes的kustomize聲明性地修補Kong的Kubernetes清單。遠程定製構建的一個示例是:docker

kustomize build github.com/kong/kubernetes-ingress-controller/deploy/manifests/base

在Kong的存儲庫中可使用Kustomization 進行不一樣類型的部署。數據庫

使用託管的Kubernetes雲產品

若是您正在使用雲提供商將Kong安裝在託管的Kubernetes產品上,例如Google Kubernetes Engine(GKE),Amazon EKS(EKS),Azure Kubernetes Service(AKS)等,請確保已設置Kubernetes羣集在雲提供程序上,並已kubectl在您的工做站上進行了配置。

一旦您配置了Kubernetes集羣並配置了kubectl,任何雲提供商的安裝都將使用上述方法之一(YAML manifestsHelm ChartKustomize)來安裝Kong。

每一個雲提供商在容許如何配置特定資源(例如負載均衡器,存儲卷等)方面都有一些細微的不一樣。咱們建議您參考其文檔來調整這些設置。

關於Kong的數據庫使用

若是您使用的是數據庫,咱們建議您在Kubernetes內部之內存模式(也稱爲無DB)運行Kong,由於全部配置都存儲在Kubernetes控制面板中。此設置簡化了Kong的操做,所以無需擔憂數據庫的設置,備份,可用性,安全性等。若是您決定使用數據庫,建議您在Kubernetes以外運行數據庫。您能夠從雲提供商使用Amazon RDS之類的服務或相似的託管Postgres服務來自動執行數據庫操做。

咱們不建議在Kubernetes部署中將Kong與Cassandra一塊兒使用,由於Kong的Cassandra使用所涵蓋的功能是經過Kubernetes中的其餘方式處理的。

當前採用yaml清單方式實踐

下載官方yaml 文件

經過瀏覽器打開官方下載地址https://bit.ly/kong-ingress-dbless,下載對應的yaml文件

wget https://raw.githubusercontent.com/Kong/kubernetes-ingress-controller/master/deploy/single/all-in-one-dbless.yaml

修改yaml文件

當前咱們deployment配置的kong 最新版本默認沒有用數據庫,前面[關於kong的數據庫使用]章節,咱們已經說明。

當前kong:2.1,kong-ingress-controller:0.9.1版本,爲適應當前環境,咱們修改了以下的配置,漏掉的位置會在yaml 文件中進行標識

  1. 修改service配置爲NodePort,默認是LoadBalancer
  2. 默認只開通了8444接口,對與接入不方便,修改爲添加8001端口,KONG_ADMIN_LISTEN :value: 0.0.0.0:8001, 0.0.0.0:8444 ssl 參數
  3. 對應的service 裏面也增長的8001端口進行對我映射

總體配置文件以下:

[root@localhost kong-gateway]# cat kong-all-in-one-dbless.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: kong
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: kongclusterplugins.configuration.konghq.com
spec:
  additionalPrinterColumns:
  - JSONPath: .plugin
    description: Name of the plugin
    name: Plugin-Type
    type: string
  - JSONPath: .metadata.creationTimestamp
    description: Age
    name: Age
    type: date
  - JSONPath: .disabled
    description: Indicates if the plugin is disabled
    name: Disabled
    priority: 1
    type: boolean
  - JSONPath: .config
    description: Configuration of the plugin
    name: Config
    priority: 1
    type: string
  group: configuration.konghq.com
  names:
    kind: KongClusterPlugin
    plural: kongclusterplugins
    shortNames:
    - kcp
  scope: Cluster
  validation:
    openAPIV3Schema:
      properties:
        config:
          type: object
        configFrom:
          properties:
            secretKeyRef:
              properties:
                key:
                  type: string
                name:
                  type: string
                namespace:
                  type: string
              required:
              - name
              - namespace
              - key
              type: object
          type: object
        disabled:
          type: boolean
        plugin:
          type: string
        protocols:
          items:
            enum:
            - http
            - https
            - grpc
            - grpcs
            - tcp
            - tls
            type: string
          type: array
        run_on:
          enum:
          - first
          - second
          - all
          type: string
      required:
      - plugin
  version: v1
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: kongconsumers.configuration.konghq.com
spec:
  additionalPrinterColumns:
  - JSONPath: .username
    description: Username of a Kong Consumer
    name: Username
    type: string
  - JSONPath: .metadata.creationTimestamp
    description: Age
    name: Age
    type: date
  group: configuration.konghq.com
  names:
    kind: KongConsumer
    plural: kongconsumers
    shortNames:
    - kc
  scope: Namespaced
  validation:
    openAPIV3Schema:
      properties:
        credentials:
          items:
            type: string
          type: array
        custom_id:
          type: string
        username:
          type: string
  version: v1
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: kongcredentials.configuration.konghq.com
spec:
  additionalPrinterColumns:
  - JSONPath: .type
    description: Type of credential
    name: Credential-type
    type: string
  - JSONPath: .metadata.creationTimestamp
    description: Age
    name: Age
    type: date
  - JSONPath: .consumerRef
    description: Owner of the credential
    name: Consumer-Ref
    type: string
  group: configuration.konghq.com
  names:
    kind: KongCredential
    plural: kongcredentials
  scope: Namespaced
  validation:
    openAPIV3Schema:
      properties:
        consumerRef:
          type: string
        type:
          type: string
      required:
      - consumerRef
      - type
  version: v1
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: kongingresses.configuration.konghq.com
spec:
  group: configuration.konghq.com
  names:
    kind: KongIngress
    plural: kongingresses
    shortNames:
    - ki
  scope: Namespaced
  validation:
    openAPIV3Schema:
      properties:
        proxy:
          properties:
            connect_timeout:
              minimum: 0
              type: integer
            path:
              pattern: ^/.*$
              type: string
            protocol:
              enum:
              - http
              - https
              - grpc
              - grpcs
              - tcp
              - tls
              type: string
            read_timeout:
              minimum: 0
              type: integer
            retries:
              minimum: 0
              type: integer
            write_timeout:
              minimum: 0
              type: integer
          type: object
        route:
          properties:
            headers:
              additionalProperties:
                items:
                  type: string
                type: array
              type: object
            https_redirect_status_code:
              type: integer
            methods:
              items:
                type: string
              type: array
            path_handling:
              enum:
              - v0
              - v1
              type: string
            preserve_host:
              type: boolean
            protocols:
              items:
                enum:
                - http
                - https
                - grpc
                - grpcs
                - tcp
                - tls
                type: string
              type: array
            regex_priority:
              type: integer
            strip_path:
              type: boolean
        upstream:
          properties:
            algorithm:
              enum:
              - round-robin
              - consistent-hashing
              - least-connections
              type: string
            hash_fallback:
              type: string
            hash_fallback_header:
              type: string
            hash_on:
              type: string
            hash_on_cookie:
              type: string
            hash_on_cookie_path:
              type: string
            hash_on_header:
              type: string
            healthchecks:
              properties:
                active:
                  properties:
                    concurrency:
                      minimum: 1
                      type: integer
                    healthy:
                      properties:
                        http_statuses:
                          items:
                            type: integer
                          type: array
                        interval:
                          minimum: 0
                          type: integer
                        successes:
                          minimum: 0
                          type: integer
                      type: object
                    http_path:
                      pattern: ^/.*$
                      type: string
                    timeout:
                      minimum: 0
                      type: integer
                    unhealthy:
                      properties:
                        http_failures:
                          minimum: 0
                          type: integer
                        http_statuses:
                          items:
                            type: integer
                          type: array
                        interval:
                          minimum: 0
                          type: integer
                        tcp_failures:
                          minimum: 0
                          type: integer
                        timeout:
                          minimum: 0
                          type: integer
                      type: object
                  type: object
                passive:
                  properties:
                    healthy:
                      properties:
                        http_statuses:
                          items:
                            type: integer
                          type: array
                        interval:
                          minimum: 0
                          type: integer
                        successes:
                          minimum: 0
                          type: integer
                      type: object
                    unhealthy:
                      properties:
                        http_failures:
                          minimum: 0
                          type: integer
                        http_statuses:
                          items:
                            type: integer
                          type: array
                        interval:
                          minimum: 0
                          type: integer
                        tcp_failures:
                          minimum: 0
                          type: integer
                        timeout:
                          minimum: 0
                          type: integer
                      type: object
                  type: object
                threshold:
                  type: integer
              type: object
            host_header:
              type: string
            slots:
              minimum: 10
              type: integer
          type: object
  version: v1
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: kongplugins.configuration.konghq.com
spec:
  additionalPrinterColumns:
  - JSONPath: .plugin
    description: Name of the plugin
    name: Plugin-Type
    type: string
  - JSONPath: .metadata.creationTimestamp
    description: Age
    name: Age
    type: date
  - JSONPath: .disabled
    description: Indicates if the plugin is disabled
    name: Disabled
    priority: 1
    type: boolean
  - JSONPath: .config
    description: Configuration of the plugin
    name: Config
    priority: 1
    type: string
  group: configuration.konghq.com
  names:
    kind: KongPlugin
    plural: kongplugins
    shortNames:
    - kp
  scope: Namespaced
  validation:
    openAPIV3Schema:
      properties:
        config:
          type: object
        configFrom:
          properties:
            secretKeyRef:
              properties:
                key:
                  type: string
                name:
                  type: string
              required:
              - name
              - key
              type: object
          type: object
        disabled:
          type: boolean
        plugin:
          type: string
        protocols:
          items:
            enum:
            - http
            - https
            - grpc
            - grpcs
            - tcp
            - tls
            type: string
          type: array
        run_on:
          enum:
          - first
          - second
          - all
          type: string
      required:
      - plugin
  version: v1
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: tcpingresses.configuration.konghq.com
spec:
  additionalPrinterColumns:
  - JSONPath: .status.loadBalancer.ingress[*].ip
    description: Address of the load balancer
    name: Address
    type: string
  - JSONPath: .metadata.creationTimestamp
    description: Age
    name: Age
    type: date
  group: configuration.konghq.com
  names:
    kind: TCPIngress
    plural: tcpingresses
  scope: Namespaced
  subresources:
    status: {}
  validation:
    openAPIV3Schema:
      properties:
        apiVersion:
          type: string
        kind:
          type: string
        metadata:
          type: object
        spec:
          properties:
            rules:
              items:
                properties:
                  backend:
                    properties:
                      serviceName:
                        type: string
                      servicePort:
                        format: int32
                        type: integer
                    type: object
                  host:
                    type: string
                  port:
                    format: int32
                    type: integer
                type: object
              type: array
            tls:
              items:
                properties:
                  hosts:
                    items:
                      type: string
                    type: array
                  secretName:
                    type: string
                type: object
              type: array
          type: object
        status:
          type: object
  version: v1beta1
status:
  acceptedNames:
    kind: ""
    plural: ""
  conditions: []
  storedVersions: []
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kong-serviceaccount
  namespace: kong
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: kong-ingress-clusterrole
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - nodes
  - pods
  - secrets
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - services
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  - extensions
  - networking.internal.knative.dev
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
- apiGroups:
  - networking.k8s.io
  - extensions
  - networking.internal.knative.dev
  resources:
  - ingresses/status
  verbs:
  - update
- apiGroups:
  - configuration.konghq.com
  resources:
  - tcpingresses/status
  verbs:
  - update
- apiGroups:
  - configuration.konghq.com
  resources:
  - kongplugins
  - kongclusterplugins
  - kongcredentials
  - kongconsumers
  - kongingresses
  - tcpingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - configmaps
  verbs:
  - create
  - get
  - update
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: kong-ingress-clusterrole-nisa-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: kong-ingress-clusterrole
subjects:
- kind: ServiceAccount
  name: kong-serviceaccount
  namespace: kong
---
apiVersion: v1
kind: Service
metadata:
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp
    service.beta.kubernetes.io/aws-load-balancer-type: nlb
  name: kong-proxy
  namespace: kong
spec:
  ports:
  - name: proxy
    port: 80
    protocol: TCP
    targetPort: 8000
  - name: proxy-ssl
    port: 443
    protocol: TCP
    targetPort: 8443
  - name: kong-admin
    port: 8001
    protocol: TCP
    targetPort: 8001
  - name: kong-admin-ssl
    port: 8444
    protocol: TCP
    targetPort: 8444
  selector:
    app: ingress-kong
  type: NodePort
---
apiVersion: v1
kind: Service
metadata:
  name: kong-validation-webhook
  namespace: kong
spec:
  ports:
  - name: webhook
    port: 443
    protocol: TCP
    targetPort: 8080
  selector:
    app: ingress-kong
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: ingress-kong
  name: ingress-kong
  namespace: kong
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ingress-kong
  template:
    metadata:
      annotations:
        kuma.io/gateway: enabled
        prometheus.io/port: "8100"
        prometheus.io/scrape: "true"
        traffic.sidecar.istio.io/includeInboundPorts: ""
      labels:
        app: ingress-kong
    spec:
      containers:
      - env:
        - name: KONG_PROXY_LISTEN
          value: 0.0.0.0:8000, 0.0.0.0:8443 ssl http2
        - name: KONG_ADMIN_LISTEN
          value: 0.0.0.0:8001, 0.0.0.0:8444 ssl
        - name: KONG_STATUS_LISTEN
          value: 0.0.0.0:8100
        - name: KONG_DATABASE
          value: "off"
        - name: KONG_NGINX_WORKER_PROCESSES
          value: "1"
        - name: KONG_ADMIN_ACCESS_LOG
          value: /dev/stdout
        - name: KONG_ADMIN_ERROR_LOG
          value: /dev/stderr
        - name: KONG_PROXY_ERROR_LOG
          value: /dev/stderr
        image: kong:2.1
        lifecycle:
          preStop:
            exec:
              command:
              - /bin/sh
              - -c
              - kong quit
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /status
            port: 8100
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: proxy
        ports:
        - containerPort: 8000
          name: proxy
          protocol: TCP
        - containerPort: 8443
          name: proxy-ssl
          protocol: TCP
        - containerPort: 8100
          name: metrics
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /status
            port: 8100
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        securityContext:
          runAsUser: 1000
      - env:
        - name: CONTROLLER_KONG_ADMIN_URL
          value: https://127.0.0.1:8444
        - name: CONTROLLER_KONG_ADMIN_TLS_SKIP_VERIFY
          value: "true"
        - name: CONTROLLER_PUBLISH_SERVICE
          value: kong/kong-proxy
        - name: POD_NAME
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
        image: kong-docker-kubernetes-ingress-controller.bintray.io/kong-ingress-controller:0.9.1
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: ingress-controller
        ports:
        - containerPort: 8080
          name: webhook
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
      serviceAccountName: kong-serviceaccount

執行該yaml 文件

[root@localhost kong-gateway]# kubectl apply -f all-in-one-dbless.yaml 
namespace/kong created
customresourcedefinition.apiextensions.k8s.io/kongclusterplugins.configuration.konghq.com created
customresourcedefinition.apiextensions.k8s.io/kongconsumers.configuration.konghq.com created
customresourcedefinition.apiextensions.k8s.io/kongcredentials.configuration.konghq.com created
customresourcedefinition.apiextensions.k8s.io/kongingresses.configuration.konghq.com created
customresourcedefinition.apiextensions.k8s.io/kongplugins.configuration.konghq.com created
customresourcedefinition.apiextensions.k8s.io/tcpingresses.configuration.konghq.com created
serviceaccount/kong-serviceaccount created
clusterrole.rbac.authorization.k8s.io/kong-ingress-clusterrole created
clusterrolebinding.rbac.authorization.k8s.io/kong-ingress-clusterrole-nisa-binding created
service/kong-proxy created
service/kong-validation-webhook created
deployment.apps/ingress-kong created

查看啓動狀況

[root@localhost kong-gateway]# kubectl get po -n kong -l app=ingress-kong
NAME                            READY   STATUS    RESTARTS   AGE
ingress-kong-5f8b45fbff-4cdtv   2/2     Running   2          20m
ingress-kong-5f8b45fbff-mkkq9   2/2     Running   2          20m
ingress-kong-5f8b45fbff-qt8tw   2/2     Running   1          12h
[root@localhost kong-gateway]# kubectl get svc -n kong
NAME                              TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                                                    AGE
service/kong-proxy                NodePort    10.97.22.195    <none>        80:32284/TCP,443:32083/TCP,8001:32704/TCP,8444:30658/TCP   39h
service/kong-validation-webhook   ClusterIP   10.101.75.177   <none>        443/TCP

開放kong-proxy對外8001接口ingress配置文件

當前配置文件時爲了開放kong-proxy-admin的接口,可讓用戶使用ingress域名進行訪問,限制kong admin管理接口爲8001和8443

[root@localhost kong-gateway]# cat kong-proxy-admin.ingress-demo.yaml 
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  labels:
    ingresscontroller: kong
  annotations:
    kubernetes.io/ingress.class: kong 
  name: kong-proxy
  namespace: kong
spec:
  rules:
  - host: kong-proxy-admin.mydomain.com
    http:
      paths:
      - backend:
          serviceName: kong-proxy
          servicePort: 8001 
        path: /
[root@localhost kong-gateway]# kubectl get ing -n kong 
kong-proxy   <none>   kong-proxy-admin.mydomain.com   172.18.0.2   80      10h

[root@localhost kong-gateway]# kubectl describe  ing -n kong kong-proxy
Name:             kong-proxy
Namespace:        kong
Address:          172.18.0.2
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host                           Path  Backends
  ----                           ----  --------
  kong-proxy-admin.mydomain.com  
                                 /   kong-proxy:8001 (10.244.0.20:8001,10.244.0.21:8001,10.244.0.22:8001)
Annotations:                     kubernetes.io/ingress.class: kong
Events:                          <none>

安裝Konga 管理UI

Kong 企業版提供了管理UI,開源版本是沒有的。可是有不少的開源的管理 UI ,其中比較好用的是Konga。項目地址:https://github.com/pantsel/konga

img

Konga 特性

Konga 主要是用 AngularJS 寫的,運行於nodejs服務端。具備如下特性:

  • 管理全部Kong Admin API對象。
  • 支持從遠程源(數據庫,文件,API等)導入使用者。
  • 管理多個Kong節點。使用快照備份,還原和遷移Kong節點。
  • 使用運行情況檢查監視節點和API狀態。
  • 支持電子郵件和閒置通知。
  • 支持多用戶。
  • 易於數據庫集成(MySQL,postgresSQL,MongoDB,SQL Server)。

Kubernetes安裝Konga數據庫postgres

  1. 咱們今天經過Kubernetes來安裝Konga。安裝步驟一樣遵循先配置postgres數據庫,初始化數據庫,啓動容器的流程

  2. 第二步配置konga 容器,而後鏈接postgres數據庫,啓動konga

  3. 配置konga鏈接kong admin 8001或者8444端口,配置kong的參數

Kubernetes 部署 Konga數據庫容器postgres

要在Kubernetes上部署PostgreSQL,咱們須要遵循如下步驟:

  • Postgres Docker映像
  • 用於存儲Postgres配置的配置映射
  • 永久存儲量
  • PostgreSQL部署
  • PostgreSQL服務

PostgreSQL Docker映像

咱們正在使用公共註冊表中的PostgreSQL 10.4 Docker映像。該映像將提供提供PostgreSQL自定義配置/環境變量(如用戶名,密碼,數據庫名稱和路徑等)的功能。

PostgreSQL配置的配置映射

咱們將使用配置映射來存儲PostgreSQL相關信息。在這裏,咱們在配置映射中使用數據庫,用戶和密碼,部署模板中的PostgreSQL pod將使用該數據庫,用戶和密碼。

文件:postgres-configmap.yaml

[root@localhost postgres]# cat postgres-configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config
  namespace: kong
  labels:
    app: postgres
data:
  POSTGRES_DB: postgresdb
  POSTGRES_USER: admin
  POSTGRES_PASSWORD: admin

建立Postgres配置資源

$ kubectl create -f postgres-configmap.yaml

永久存儲量StorageClass

衆所周知,容器本質上是短暫的。容器實例終止後,由容器或容器中生成的全部數據都將丟失。

爲了保存數據,咱們將在Kubernetes中使用持久卷和持久卷聲明資源將數據存儲在持久存儲中。

當前咱們配置了StorageClass 動態存儲使用,會在下面進行調用,不過配置Deployment模式不支持直接掛載StorageClass ,須要將控制器修改爲StatefulSet 模式進行掛載。

PostgreSQL部署

用於部署PostgreSQL容器的PostgreSQL清單使用PostgreSQL 10.4映像。它使用的是PostgreSQL配置,例如用戶名,密碼和咱們以前建立的configmap中的數據庫名。它還會掛載從持久卷建立的卷,並聲明使PostgreSQL容器的數據持久化。

[root@localhost postgres]# cat postgres-statefulSet.yaml 
apiVersion: apps/v1
kind: StatefulSet 
metadata:
  name: postgres
  namespace: kong
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels:
      app: postgres 
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:10.4 
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgredb
  volumeClaimTemplates:
  - metadata:
      name: postgredb
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 5Gi
      storageClassName: "standard"

建立Postgres部署

$ kubectl create -f postgres-deployment.yaml

PostgreSQL Service

要訪問部署或容器,咱們須要配置PostgreSQL服務。Kubernetes提供了不一樣類型的服務,例如ClusterIP,NodePort和LoadBalancer。

使用ClusterIP,咱們能夠在Kubernetes中訪問PostgreSQL服務。NodePort能夠在Kubernetes節點上公開服務端點。爲了從外部訪問PostgreSQL,咱們須要使用Load Balancer服務類型,該服務類型能夠在外部公開該服務。

文件:postgres-service.yaml

[root@localhost postgres]# cat postgres-service.yaml 
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: kong
  labels:
    app: postgres
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres

建立Postgres服務

$ kubectl create -f postgres-service.yaml

鏈接到PostgreSQL

爲了鏈接PostgreSQL,咱們須要從服務部署中獲取Node端口。

[root@localhost postgres]# kubectl get svc postgres -n kong 
NAME       TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
postgres   NodePort   10.98.211.186   <none>        5432:30761/TCP   14h

咱們須要使用端口31070從kubernetes集羣中存在的機器/節點鏈接到PostgreSQL,並使用前面configmap中給出的憑據。

$ psql -h localhost -U admin --password -p 30761 postgresdb
# 經過psql 命令進行鏈接

PostgreSQL結論

與僅使用虛擬機時相比,在Kubernetes上運行PostgreSQL有助於以更好的方式利用資源。Kubernetes還使用同一虛擬機或Kubernetes集羣中的PostgreSQL提供其餘應用程序的隔離。

是否可使用StatefulSets嗎?

在Kubernetes中,須要StatefulSets來擴展有狀態的應用程序。可使用StatefulSets經過單個命令輕鬆擴展PostgreSQL。

Kubernetes安裝Konga

  1. 咱們今天經過Kubernetes來安裝Konga。安裝步驟一樣遵循先配置postgres數據庫,初始化數據庫,啓動容器的流程

  2. 第二步配置konga 容器,而後鏈接postgres數據庫,啓動konga

  3. 配置konga鏈接kong admin 8001或者8444端口,配置kong的參數

配置konga Secret加密信息

建立配置konga Secret加密信息鏈接PostgreSQL數據庫。

[root@localhost konga]# cat konga-creds.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: kongcreds
  namespace: kong 
type: Opaque
data:
  username: YWRtaW4= 
  password: YWRtaW4= 
  postgresdbname: cG9zdGdyZXNkYg==
#your secret in base64 echo -n 'admin' | base64 YWRtaW4=
[root@localhost konga]# kubectl get secret -n kong 
NAME                              TYPE                                  DATA   AGE
kongcreds                         Opaque                                3      26h

配置konga Deployment Pod

經過Konga Deployment 引用secret 配置文件,同時在配置鏈接地址時,設置成service 內部dns 域名鏈接,具體配置文件以下:

[root@localhost konga]# cat konga-deployment.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: konga
  namespace: kong
spec:
  replicas: 1
  selector:
    matchLabels:
      app: konga
  template:
    metadata:
      labels:
        name: konga
        app: konga
    spec:
      containers:
      - name: konga
        image: pantsel/konga:latest 
        env:
        - name: DB_ADAPTER
          value: postgres
        - name: DB_HOST
          value: postgres.kong.svc.cluster.local.
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: kongcreds
              key: username
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: kongcreds
              key: password
        - name: DB_DATABASE
          value: postgresdb
        - name: TOKEN_SECRET
          value: somesecretstring
        ports:
        - containerPort: 1337
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: konga
  name: konga-svc
  namespace: kong
spec:
  ports:
    - protocol: TCP
      port: 443
      targetPort: 1337
  selector:
    app: konga

配置konga Ingress 域名對外

[root@localhost konga]# cat konga-admin-ingress-demo.yaml 
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  labels:
    ingresscontroller: kong
  annotations:
    kubernetes.io/ingress.class: kong 
  name: kong-admin
  namespace: kong
spec:
  rules:
  - host: konga-admin.mydomain.com
    http:
      paths:
      - backend:
          serviceName: konga-svc
          servicePort: 443
        path: /

測試訪問konga 頁面

經過Ingress 域名 konga-admin.mydomain.com訪問,首先會進行管理員帳號和密碼建立,而後進入Connections 界面 鏈接對應kong節點。

注意當前我沒有使用Ingress 域名,是直接使用端口映射進去的,生產狀況下建議使用Ingress 域名。

  1. 登入Konga 界面

  1. 建立一個新的Kong 節點鏈接

  1. 建立成功以後點擊鏈接

  1. 鏈接成功以後,能夠看到總體的kong節點的配置和概況

  1. 由於我以前建立了兩個Ingress 映射域名,因此在konga service選項和Routes選項會展現出來

  1. 配置好konga管理後臺以後,咱們能夠經過konga 後臺直接對kong進行管理,圖形化界面建立Service和Routes 或者其餘功能和參數的修改,均可以在konga web 界面進行操做。本章到這裏也就告一段落了,後面我會介紹下關於kong節點的配置文件。

Kong API Gateway 配置文件詳解

配置文件這塊轉載該博客,https://linuxops.org/blog/kong/config.html

下面介紹的配置文件,能夠直接在自定義鏡像修改對應的配置,也能夠在konga web界面進行修改。

兩個主要組件

  • Kong Server,基於 nginx 的服務器,用來接收 API 請求。下面主要是對配置文件進行詳解。後面也能夠經過Kong API Gateway 管理API詳解,對kong進行操做。Kong 功能強大注意仍是由於它支持強大的插件功能。
  • Apache Cassandra,用來存儲操做數據。

1、前言

Kong配置文件是Kong服務的核心文件,它配置了Kong以怎麼的方式運行,而且依賴於這個配置生成Nginx的配置文件,本文經過解讀Kong配置文件,以瞭解Kong的運行和配置。

在成功安裝Kong之後,會有一個名爲kong.conf.default默認的配置文件示例,若是是經過包管理器安裝的,一般位於/etc/kong/kong.conf.default,咱們要將其複製爲kong.conf以便於咱們修改使用他。

在Kong的配置文件中,約定了如下的幾條規則:

  • 配置文件中以#開頭的行均爲註釋行,程序不會讀取這些內容。
  • 在官方提供的默認配置文件中,以#開頭的有值的配置項目均爲默認配置。
  • 全部的配置項,都可以在系統環境變量中配置,可是必需要加上KONG_爲前綴。
  • 值爲布爾型的配置,可使用on/off或者true/false
  • 值爲列表的,必須使用半角逗號分割。

Kong的配置,大概分爲幾種,分別是:

  • 常規配置:配置服務運行目錄,插件加載,日誌等等
  • NGINX配置:配置Nginx注入,例如監聽IP和端口配置等等,用於Kong在啓動的時候生成Nginx配置文件
  • 數據庫存儲配置:配數據庫類型,地址、用戶名密碼等等信息
  • 數據庫緩存配置:配置數據的緩存規則,Kong會緩存諸如API信息、用戶、憑證等信息,以減小訪問數據庫次數提升性能
  • DNS解析器配置:默認狀況會使用系統設置,如hostsresolv.conf的配置,你也能夠經過DNS的解析器配置來修改
  • 其餘雜項配置:繼承自lua-nginx模塊的其餘設置容許更多的靈活性和高級用法。

下面咱們一個模塊一個模塊解釋一下各項的配置。

2、常規配置

在常規配置中,主要是控制Kong一些運行時的一些配置,主要有以下配置:

配置項 默認值 說明
prefix /usr/local/kong/ 配置Kong的工做目錄,至關於Nginx的工做目錄,這個目錄存放運行時的臨時文件和日誌,包括Kong啓動的時候自動生成的Nginx的配置文件。 每個Kong常常必須有一個單獨的工做目錄
log_level notice Nginx的日誌級別。日誌存放/logs/error.log
proxy_access_log logs/access.log 代理端口請求的日誌文件,能夠設置爲off來關閉日誌的記錄,也能夠經過設置絕對路徑也能夠設置相對路徑。 若是設置了相對路徑,則日誌文件會保存在的目錄下
proxy_error_log logs/error.log 代理端口請求的錯誤日誌文件,能夠設置爲off來關閉日誌的記錄,也能夠經過設置絕對路徑也能夠設置相對路徑。 若是設置了相對路徑,則日誌文件會保存在的目錄下
admin_access_log logs/admin_access.log Kong管理的API端口請求的日誌文件,能夠設置爲off來關閉日誌的記錄,也能夠經過設置絕對路徑也能夠設置相對路徑。 若是設置了相對路徑,則日誌文件會保存在的目錄下
admin_error_log logs/error.log Kong管理的API端口請求的錯誤日誌文件,能夠設置爲off來關閉日誌的記錄,也能夠經過設置絕對路徑也能夠設置相對路徑。 若是設置了相對路徑,則日誌文件會保存在的目錄下
plugins bundled Kong啓動的時候加載的插件,若是多個必需要使用半角逗號分割。默認狀況下,只有捆綁官方發行版本的插件經過 bundled 這個值來加載。 加載插件只是Kong在啓動的時候載入插件的代碼,可是並不會使用它,若是要使用他,還必需要經過管理API來配置 固然,若是你不想加載任何插件,可使用off來關閉它,值得強調的一點bundled值能夠和其餘插件名稱一塊兒使用,bundled並非一個插件名稱,它表明了隨官方發行的全部插件。
anonymous_reports on 若是Kong進程發生了錯誤,會以匿名的方式將錯誤提交給Kong官方, 以幫助改善Kong。

在常規的配置中,主要配置了Kong運行的目錄日誌等信息。

不管如何,配置的文件或者目錄Kong必需要用權限訪問,不然會報錯。

3、Nginx注入配置

Kong基於Nginx,固然須要配置Nginx來知足Kong的運行要求,Kong提供了Nginx的注入配置,使得咱們更輕鬆控制。

在Nginx注入配置中,有以下配置:

配置項 默認值 說明
proxy_listen 0.0.0.0:8000, 0.0.0.0:8443 ssl 配置Kong代理監聽的地址和端口,這個是Kong的入口,API調用都將經過這個端口請求。這個配置和Ngxin中的配置一致,經過SSL能夠指定接受https的請求 支持IPv4和IPv6
admin_listen 127.0.0.1:8001, 127.0.0.1:8444 ssl 配置Kong的管理API監聽的端口,和proxy_listen配置同樣,可是這個配置不建議監聽在公網IP上。
nginx_user nobody nobody 配置Nginx的用戶名和用戶組,和Nginx的配置規則同樣
nginx_worker_processes auto 設置Nginx的進程書,一般等於CPU核心數
nginx_daemon on 是否以daemon的方式運行Ngxin
mem_cache_size 128m 內存的緩存大小,可使用km爲單位
ssl_cipher_suite modern 定義Nginx提供的TLS密碼,能夠配置的值有:modern,intermediate, old, custom.
ssl_ciphers 定義Nginx提供的TLS密碼的列表,參考Nginx的配置
ssl_cert 配置SSL證書的crt路徑,必須是要絕對路徑
ssl_cert_key 設置SSL證書的key文件,必須是絕對路徑
client_ssl off .....
client_ssl_cert .....
client_ssl_cert_key .....
admin_ssl_cert .....
admin_ssl_cert_key .....
headers server_tokens, latency_tokens 設置再相應客戶端時候應該注入的頭部,能夠設置的值以下: - server_tokens: 注入'Via'和'Server'頭部. - latency_tokens: 注入'X-Kong-Proxy-Latency'和'X-Kong-Upstream-Latency' 頭部. - X-Kong-<header-name>: 只有在適當的時候注入特定的頭部 這個配置能夠被設置爲off。固然,即使設置了off之後,插件依然能夠注入頭部
trusted_ips 定義可信的IP地址段,一般不建議在此處限制請求,應該再插件中過濾
real_ip_header X-Real-IP 獲取客戶端真實的IP,將值經過同步的形式傳遞給後端
real_ip_recursive off 這個值在Nginx配置中設置了同名的ngx_http_realip_module指令
client_max_body_size 0 配置Nginx接受客戶端最大的body長度,若是超過此配置 將返回413。 設置爲0則不檢查長度
client_body_buffer_size 8k 設置讀取緩衝區大小,若是超過內存緩衝區大小,那麼NGINX會緩存在磁盤中,下降性能。
error_default_type text/plain 當請求' Accept '頭丟失,Nginx返回請求錯誤時使用的默認MIME類型。能夠配置的值爲: text/plain,text/html, application/json, application/xml.

在Nginx注入配置中,配置了Nginx的基本的參數,這些參數大部分和NGINX的配置值是同樣的,能夠經過Nginx的配置文檔瞭解一下。

4、 數據庫存儲配置

數據庫配置的模塊配置數據庫相關的鏈接信息等等。主要有以下配置:

配置項 默認值 說明
database postgres 設置數據庫類型,Kong支持兩種數據庫,一種是postgres,一種是cassandra
PostgreSQL配置 若是database設置爲postgres如下配置生效
pg_host 127.0.0.1 設置PostgreSQL的鏈接地址
pg_port 5432 設置PostgreSQL的端口
pg_user kong 設置PostgreSQL的用戶名
pg_password 設置PostgreSQL的密碼
pg_database kong 設置數據庫名稱
pg_ssl off 是否開啓ssl鏈接
pg_ssl_verify off 若是啓用了' pg_ssl ',則切換服務器證書驗證。
cassandra配置 若是database設置爲cassandra如下配置生效
cassandra_contact_points 127.0.0.1 .....
cassandra_port 9042 .....
cassandra_keyspace kong .....
cassandra_timeout 5000 .....
cassandra_ssl off .....
cassandra_ssl_verify off .....
cassandra_username kong .....
cassandra_password .....
cassandra_consistency ONE .....
cassandra_lb_policy RoundRobin .....
cassandra_local_datacenter .....
cassandra_repl_strategy SimpleStrategy .....
cassandra_repl_factor 1 .....
cassandra_data_centers dc1:2,dc2:3 .....
cassandra_schema_consensus_timeout 10000 .....

推薦使用PostgreSQL數據庫做爲生產環境的存儲,PostgreSQL具備良好的性能和穩定性,是一個很是優秀的開源數據庫。

5、 數據庫緩存配置

在上一節中,配置了Kong持久化存儲,顯然若是每次的請求都須要去查詢數據庫中的相關信息那無疑是很是消耗資源,性能和穩定性也會大大下降,做爲一個API網關確定是不能忍的,解決這個問題的辦法就是緩存,Kong將數據緩存在內存中,這樣會大大提升性能,本節介紹Kong的緩存配置。

配置項 默認值 說明
db_update_frequency 5 節點更新數據庫的時間,以秒爲單位。 這個配置設置了節點查詢數據庫的時間,假若有3臺Kong服務器節點ABC,若是再A節點增長了一個API網關,那麼B和C節點最多須要等待db_update_frequency時間才能被更新到。
db_update_propagation 0 數據庫節點的更新時間。 若是使用了Cassandra數據庫集羣,那麼若是數據庫有更新,最多須要db_update_propagation時間來同步全部的數據庫副本。 若是使用PostgreSQL或者單數據庫,這個值能夠被設置爲0
db_cache_ttl 0 緩存生效時間,單位秒。若是設置爲0表示永不過時 Kong從數據庫中讀取數據而且緩存,在ttl過時後會刪除這個緩存而後再一次讀取數據庫並緩存
db_resurrect_ttl 30 緩存刷新時間,單位秒。當數據存儲中的陳舊實體沒法刷新時(例如,數據存儲不可訪問),應該對其進行恢復。當這個TTL過時時,將嘗試刷新陳舊的實體。

6、 DNS解析器配置

默認狀況下,DNS解析器將使用標準配置文件/etc/hosts/etc/resolv.conf。若是設置了環境變量LOCALDOMAINRES_OPTIONS,那麼後一個文件中的設置將被覆蓋。

配置項 默認值 說明
dns_resolver 配置DNS服務器列表,用半角逗號分割,每一個條目使用ip[:port]的格式,這個配置僅提供給Kong使用,不會覆蓋節點系統的配置,若是沒有配置則使用系統的設置。接受IPv4和IPv6的地址。
dns_hostsfile /etc/hosts 配置Kong的hosts文件,這個配置一樣僅提供給Kong使用,不會覆蓋節點系統的配置。 須要說明的是這個文件僅讀取一次,讀取的內容會緩存再內存中,若是修改了此文件,必需要重啓Kong才能生效。
dns_order LAST,SRV,A,CNAME 解析不一樣記錄類型的順序。「LAST」類型表示最後一次成功查找的類型(用於指定的名稱)
dns_stale_ttl 4 配置DNS記錄緩存過時時間
dns_not_found_ttl 30 這個配置值不知道該如何理解??
dns_error_ttl 1 .....
dns_no_sync off 若是啓用了該項,那麼在DNS緩存過時以後,每一次請求都會發起DNS查詢。在禁用此項時,那麼相同的域名屢次請求會同步到一個查詢中共享返回值。

在DNS配置中,咱們基本上不須要更改,官網的配置給出了最優的配置。若是咱們須要在host文件中定義後端綁定的域名,必定要在編輯hosts文件後重載Kong的配置,或者重啓Kong,不管hosts的文件是不是/etc/hosts,不然都不會生效的。

7、 其餘雜項配置

雜項配置基本上關於LUA的配置,若是不熟悉請不要修改,按照官方默認便可。

配置項 默認值 說明
lua_ssl_trusted_certificate ....
lua_ssl_verify_depth 1 ....
lua_package_path ./?.lua;./?/init.lua; ....
lua_package_cpath ....
lua_socket_pool_size 30 ....

Kong基本功能說明

基礎功能(konga爲例)

在這裏插入圖片描述

應用級菜單

  1. Connections Kong鏈接,用於配置Kong的AdminAPI地址,配置成功以後,將會開啓Kong級菜單。
  2. Snapshots 快照,用於存儲Kong節點快照,可快速恢復節點配置。

API網關菜單

  1. Consumers API網關消費者,用於各種認證以及限流控制等;
  2. Services 服務,用於配置上游服務的信息,主要包括服務名稱、上游的Host以及Port等;
  3. Routes 路由,用於配置下游的路由信息,定義服務的出口路徑,主要包括路由名稱、Host、Path、Methods以及Http/Https等;
  4. Plugins 插件,可配置於Service或Route,主要包括認證、安全、限流、監控、日誌以及自定義幾大模塊,官方提供了較爲全面的基礎插件功能;
  5. Upstreams 類nginx中的Upstream,用於配置上游的服務信息;
  6. Certificates 證書管理。

服務配置

1.添加服務: Services -> Create Services 實例:

在這裏插入圖片描述

說明:因爲這裏的Kong部署在K8S環境中,因此能夠直接使用K8S中的服務名+端口號來定義服務的Host和Port。

2.添加路由: Services -> Service Detail -> Routes -> Add Route 實例:

在這裏插入圖片描述

配置完成以後,咱們就能夠訪問咱們的服務了。

# https://192.168.0.231:31617/config 或 http://192.168.0.231:32740/config Host: config.kong
> curl -ik -H "Host":"config.kong" https://192.168.0.231:31617/config/basic/dev
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Date: Thu, 17 Oct 2019 02:05:16 GMT
Server: Kestrel
X-Kong-Upstream-Latency: 3
X-Kong-Proxy-Latency: 10007
Via: kong/1.3.0

{"logLevel":"Debug",...}
複製代碼

插件配置

插件添加有兩個入口: 1.服務插件 Servcies -> Service Detail -> Plugins -> Add Plugin 2.路由插件 Routes -> Route Detail -> Plugins -> Add Plugin

認證

1.Basic 認證
 Header: Authorization Basic base64(username:password)

 2.Jwt認證
 支持三種認證參數傳遞:uri param,cookie and header,可自定義鍵名
 key claim通常爲iss
 jwt生成 & 校驗:https://jwt.io/

 3.OAuth2認證
 認證地址:oauth2/authorize
 獲取token地址: oauth2/token
 刷新token地址: oauth2/token

安全

1. Acl 訪問控制列表
 2. Cors  跨域資源共享
 3. Ip Restriction IP限制
 4. Bot Detection 機器人檢測

限流

1. Rate Limiting 速率限制
 2. Response Ratelimiting 響應速率限制
 3. Request Size Limiting  請求大小限制
 4. Request Termination 請求阻斷/終止

日誌

監控

請求轉發

自定義

Kong Admin API

AdminAPI

感謝參考

AdminAPI

shoy160

kirito-moe

非學無以廣才

https://linuxops.org/blog/kong/admin.html

https://blog.csdn.net/twingao/article/details/104073289

相關文章
相關標籤/搜索