­

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

1、Kong的概述

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

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

img

2、功能特性

  • 雲本土化(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添加功能。

3、Kong依賴的技術

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

  • 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的各個方面。

  • 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:

YAML清單

要通過部署Kong kubectl,請使用:

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

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

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

helm部署

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

$ helm repo add kong //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清單。遠程定製構建的一個示例是:

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 文件

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

wget //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: //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。項目地址://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 配置文件詳解

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

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

兩個主要組件

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

一、前言

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模塊的其他設置允許更多的靈活性和高級用法。

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

二、常規配置

在常規配置中,主要是控制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必須要用權限訪問,否則會報錯。

三、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的配置文檔了解一下。

四、 數據庫存儲配置

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

配置項 默認值 說明
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具有良好的性能和穩定性,是一個非常優秀的開源數據庫。

五、 數據庫緩存配置

在上一節中,配置了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過期時,將嘗試刷新陳舊的實體。

六、 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,否則都不會生效的。

七、 其他雜項配置

雜項配置基本上關於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 實例:

在這裡插入圖片描述

配置完成之後,我們就可以訪問我們的服務了。

# //192.168.0.231:31617/config 或 //192.168.0.231:32740/config Host: config.kong
> curl -ik -H "Host":"config.kong" //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生成 & 校驗://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

非學無以廣才

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

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