Kong是一個clould-native、快速的、可擴展的、分佈式的微服務抽象層(也稱爲API網關、API中間件或在某些狀況下稱爲服務網格)框架。Kong做爲開源項目在2015年推出,它的核心價值是高性能和可擴展性。Kong被普遍用於從初創企業到全球5000家公司以及政府組織的生產環境中。html
若是構建Web、移動或IoT(物聯網)應用,可能最終須要使用通用的功能來實現這些應用。Kong充當微服務請求的網關(或側車),經過插件可以提供負載平衡、日誌記錄、身份驗證、速率限制、轉換等能力。node
Kong部署在Nginx和Apache Cassandra或PostgreSQL等可靠技術之上,並提供了易於使用的RESTful API來操做和配置系統。下面是Kong的技術邏輯圖。基於這些技術,Kong提供相關的特性支持:linux
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
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
kubectl
安裝並配置爲與Kubernetes集羣通訊。使用如下安裝方法之一安裝Kong for Kubernetes:git
要經過部署Kong kubectl
,請使用:github
kubectl apply -f https://bit.ly/kong-ingress-dbless
重要!這不是生產級部署。根據您的用例調整「參數」:web
- 副本:確保您正在運行Kong的多個實例,以防止因爲單個節點故障而形成的中斷。
- 性能優化:調整Kong的內存設置,並根據使用狀況定製部署。
- 負載均衡器:確保在Kong前面運行基於4層或TCP的均衡器。這使Kong能夠提供TLS證書並與證書管理器集成。
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
可使用Kubernetes的kustomize聲明性地修補Kong的Kubernetes清單。遠程定製構建的一個示例是:docker
kustomize build github.com/kong/kubernetes-ingress-controller/deploy/manifests/base
在Kong的存儲庫中可使用Kustomization 進行不一樣類型的部署。數據庫
若是您正在使用雲提供商將Kong安裝在託管的Kubernetes產品上,例如Google Kubernetes Engine(GKE),Amazon EKS(EKS),Azure Kubernetes Service(AKS)等,請確保已設置Kubernetes羣集在雲提供程序上,並已kubectl
在您的工做站上進行了配置。
一旦您配置了Kubernetes集羣並配置了kubectl,任何雲提供商的安裝都將使用上述方法之一(YAML manifests,Helm Chart或Kustomize)來安裝Kong。
每一個雲提供商在容許如何配置特定資源(例如負載均衡器,存儲卷等)方面都有一些細微的不一樣。咱們建議您參考其文檔來調整這些設置。
若是您使用的是數據庫,咱們建議您在Kubernetes內部之內存模式(也稱爲無DB)運行Kong,由於全部配置都存儲在Kubernetes控制面板中。此設置簡化了Kong的操做,所以無需擔憂數據庫的設置,備份,可用性,安全性等。若是您決定使用數據庫,建議您在Kubernetes以外運行數據庫。您能夠從雲提供商使用Amazon RDS之類的服務或相似的託管Postgres服務來自動執行數據庫操做。
咱們不建議在Kubernetes部署中將Kong與Cassandra一塊兒使用,由於Kong的Cassandra使用所涵蓋的功能是經過Kubernetes中的其餘方式處理的。
經過瀏覽器打開官方下載地址https://bit.ly/kong-ingress-dbless,下載對應的yaml文件
wget https://raw.githubusercontent.com/Kong/kubernetes-ingress-controller/master/deploy/single/all-in-one-dbless.yaml
當前咱們deployment配置的kong 最新版本默認沒有用數據庫,前面[關於kong的數據庫使用]章節,咱們已經說明。
當前kong:2.1,kong-ingress-controller:0.9.1版本,爲適應當前環境,咱們修改了以下的配置,漏掉的位置會在yaml 文件中進行標識
總體配置文件以下:
[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
[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-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>
Kong 企業版提供了管理UI,開源版本是沒有的。可是有不少的開源的管理 UI ,其中比較好用的是Konga。項目地址:https://github.com/pantsel/konga
Konga 主要是用 AngularJS 寫的,運行於nodejs服務端。具備如下特性:
咱們今天經過Kubernetes來安裝Konga。安裝步驟一樣遵循先配置postgres數據庫,初始化數據庫,啓動容器的流程
第二步配置konga 容器,而後鏈接postgres數據庫,啓動konga
配置konga鏈接kong admin 8001或者8444端口,配置kong的參數
要在Kubernetes上部署PostgreSQL,咱們須要遵循如下步驟:
咱們正在使用公共註冊表中的PostgreSQL 10.4 Docker映像。該映像將提供提供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
衆所周知,容器本質上是短暫的。容器實例終止後,由容器或容器中生成的全部數據都將丟失。
爲了保存數據,咱們將在Kubernetes中使用持久卷和持久卷聲明資源將數據存儲在持久存儲中。
當前咱們配置了StorageClass 動態存儲使用,會在下面進行調用,不過配置Deployment模式不支持直接掛載StorageClass ,須要將控制器修改爲StatefulSet 模式進行掛載。
用於部署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服務。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,咱們須要從服務部署中獲取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 命令進行鏈接
與僅使用虛擬機時相比,在Kubernetes上運行PostgreSQL有助於以更好的方式利用資源。Kubernetes還使用同一虛擬機或Kubernetes集羣中的PostgreSQL提供其餘應用程序的隔離。
在Kubernetes中,須要StatefulSets來擴展有狀態的應用程序。可使用StatefulSets經過單個命令輕鬆擴展PostgreSQL。
咱們今天經過Kubernetes來安裝Konga。安裝步驟一樣遵循先配置postgres數據庫,初始化數據庫,啓動容器的流程
第二步配置konga 容器,而後鏈接postgres數據庫,啓動konga
配置konga鏈接kong admin 8001或者8444端口,配置kong的參數
建立配置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 引用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
[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: /
經過Ingress 域名 konga-admin.mydomain.com訪問,首先會進行管理員帳號和密碼建立,而後進入Connections 界面 鏈接對應kong節點。
注意當前我沒有使用Ingress 域名,是直接使用端口映射進去的,生產狀況下建議使用Ingress 域名。
配置文件這塊轉載該博客,https://linuxops.org/blog/kong/config.html
下面介紹的配置文件,能夠直接在自定義鏡像修改對應的配置,也能夠在konga web界面進行修改。
Kong配置文件是Kong服務的核心文件,它配置了Kong以怎麼的方式運行,而且依賴於這個配置生成Nginx的配置文件,本文經過解讀Kong配置文件,以瞭解Kong的運行和配置。
在成功安裝Kong之後,會有一個名爲kong.conf.default
默認的配置文件示例,若是是經過包管理器安裝的,一般位於/etc/kong/kong.conf.default
,咱們要將其複製爲kong.conf
以便於咱們修改使用他。
在Kong的配置文件中,約定了如下的幾條規則:
#
開頭的行均爲註釋行,程序不會讀取這些內容。#
開頭的有值的配置項目均爲默認配置。KONG_
爲前綴。on
/off
或者true
/false
。Kong的配置,大概分爲幾種,分別是:
hosts
和resolv.conf
的配置,你也能夠經過DNS的解析器配置來修改下面咱們一個模塊一個模塊解釋一下各項的配置。
在常規配置中,主要是控制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必需要用權限訪問,不然會報錯。
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 | 內存的緩存大小,可使用k 和m 爲單位 |
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解析器將使用標準配置文件/etc/hosts
和/etc/resolv.conf
。若是設置了環境變量LOCALDOMAIN
和RES_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 | .... |
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 請求阻斷/終止
日誌
監控
請求轉發
自定義