一、概述

Nginx、OpenRestry、Kong这三个项目紧密相连:

  1. Nginx是模块化设计的反向代理软件,C语言开发;

  2. OpenResty是以Nginx为核心的Web开发平台,可以解析执行Lua脚本;

  3. Kong是一个OpenResty应用,一个api gateway。

OpenResty与Lua的关系类似于Jvm与Java,不过OpenResty是基于nginx的,主要用于Web、API类应用。

二、Kong docker方式部署

参考:https://docs.konghq.com/install/docker/?_ga=2.218789593.1933534790.1562222882-743556268.1562222882

1、创建docker 网络

docker network create kong-net

2、运行postgresql 的数据库

docker run -d --name kong-database \
        --network=kong-net \
        -p 5432:5432 \
        -e "POSTGRES_USER=kong" \
        -e "POSTGRES_DB=kong" \
        --restart always \
        postgres:9.6

3、初始化数据库(迁移数据)

docker run --rm \
   --network=kong-net \
   -e "KONG_DATABASE=postgres" \
   -e "KONG_PG_HOST=kong-database" \
   kong:latest kong migrations bootstrap

4、运行kong

docker run -d --name kong \
   --network=kong-net \
   -e "KONG_DATABASE=postgres" \
   -e "KONG_PG_HOST=kong-database" \
   -e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \
   -e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
   -e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
   -e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
   -e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
   -e "KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl" \
   -p 80:8000 \
   -p 443:8443 \
   -p 8001:8001 \
   -p 8444:8444 \
   --restart always \
   kong:latest

概念术语

upstream: 是对上游服务器的抽象;

target: 代表了一个物理服务,是 ip + port 的抽象;

service: 是抽象层面的服务,他可以直接映射到一个物理服务(host 指向 ip + port),也可以指向一个 upstream 来做到负载均衡;

route: 是路由的抽象,他负责将实际的 request 映射到 service。

默认情况下,KONG监听的端口为:8000、8001、8443、8444

8444: 通过此端口,管理者可以对HTTP请求进行监控;

其中 8000/8443 分别是用来监听来自客户端的Http 和 Https请求,等价于 Nginx 默认的 80 端口,而 8001 端口便是默认的管理端口,可以通过 HTTP Restful API 来动态管理 Kong 的配置;

使用方法

# curl http://localhost:8001

5、dashboard

kong dashboard方式

docker run -d --name kong-dashboard -p 8080:8080 pgbi/kong-dashboard start --kong-url http://192.168.20.37:8001 –basic-auth kongUser=kongP@ssw0rd

kong Gateway 使用说明_第1张图片

konga方式

1)、Prepare the database(官网)

$ docker run --rm pantsel/konga:latest -c prepare -a {{adapter}} -u {{connection-uri}} 
-c command
-a adapter (can be postgres or mysql)
-u full database connection url
# docker run --rm pantsel/konga:latest -c prepare -a postgres -u postgresql://kong:@192.168.20.37:5432/konga
debug: Preparing database...
Using postgres DB Adapter.
Database `konga` does not exist. Creating...
Database `konga` created! Continue...
debug: Hook:api_health_checks:process() called
debug: Hook:health_checks:process() called
debug: Hook:start-scheduled-snapshots:process() called
debug: Hook:upstream_health_checks:process() called
debug: Hook:user_events_hook:process() called
debug: Seeding User...
debug: User seed planted
debug: Seeding Kongnode...
debug: Kongnode seed planted
debug: Seeding Emailtransport...
debug: Emailtransport seed planted
debug: Database migrations completed!
#

2)、Start Konga(官网)

Start Konga
$ docker run -p 1337:1337 
          --network {{kong-network}} \ // optional
          -e "TOKEN_SECRET={{somerandomstring}}" \
          -e "DB_ADAPTER=the-name-of-the-adapter" \ // 'mongo','postgres','sqlserver'  or 'mysql'
          -e "DB_HOST=your-db-hostname" \
          -e "DB_PORT=your-db-port" \ // Defaults to the default db port
          -e "DB_USER=your-db-user" \ // Omit if not relevant
          -e "DB_PASSWORD=your-db-password" \ // Omit if not relevant
          -e "DB_DATABASE=your-db-name" \ // Defaults to 'konga_database'
          -e "DB_PG_SCHEMA=my-schema"\ // Optionally define a schema when integrating with prostgres
          -e "NODE_ENV=production" \ // or 'development' | defaults to 'development'
          --name konga \
          pantsel/konga
# docker run -d -p 1337:1337 \
          --network kong-net \ 
          -e "TOKEN_SECRET=P@ssw0rd" \
          -e "DB_ADAPTER=postgres" \
          -e "DB_URI=postgresql://kong:@kong-database:5432/konga" \
          -e "NODE_ENV=production" \ 
          --name konga \
          pantsel/konga

http://192.168.20.37:1337

kong Gateway 使用说明_第2张图片

6、辅助pgadmin

# docker run -d -p 8090:80 \
    --name=pgadmin \
    --network=kong-net \
    --link kong-database:kong-database \
    -e "[email protected]" \
    -e "PGADMIN_DEFAULT_PASSWORD=P@ssw0rd" \
    --restart always \
    -d dpage/pgadmin4

kong Gateway 使用说明_第3张图片

三、Kong的使用

一个典型的 Nginx 配置

upstream helloUpstream {
    server localhost:3000 weight=100;
}

server {
    listen 80;
    location /hello {
    proxy_pass http://helloUpstream;
  }
}

如上简单的 Nginx 配置,可以转换为如下的 Http 请求。

对应的 Kong 配置

1) 配置 upstream

# curl -X POST http://localhost:8001/upstreams --data "name=helloUpstream"

2) 配置 target

# curl -X POST http://localhost:8001/upstreams/helloUpstream/targets --data "target=localhost:3000" --data "weight=100"

3) 配置 service

# curl -X POST http://localhost:8001/services --data "name=hello" --data "host=helloUpstream"

4) 配置 route

# curl -X POST http://localhost:8001/routes --data "paths[]=/hello" --data "service.id=8695cc65-16c1-43b1-95a1-5d30d0a50409"

这一切都是动态的,无需手动 reload nginx.conf

为 Kong 新增路由信息时涉及到了 upstream,target,service,route 等概念,便是 Kong 最核心的四个对象。

为 hello 服务添加50次/秒的限流:

# curl -X POST http://localhost:8001/services/hello/plugins \
    --data "name=rate-limiting" \
    --data "config.second=50"

为 hello 服务添加 jwt 插件:

# curl -X POST http://localhost:8001/services/login/plugins \
    --data "name=jwt"

同理,插件也可以安装在 route 之上

#   curl -X POST http://localhost:8001/routes/{routeId}/plugins \
    --data "name=rate-limiting" \
    --data "config.second=50"

# curl -X POST http://localhost:8001/routes/{routeId}/plugins \
    --data "name=jwt"

四、Konga的使用

1、创建upstream

kong Gateway 使用说明_第4张图片

2、指定Targets

kong Gateway 使用说明_第5张图片

3、创建service

kong Gateway 使用说明_第6张图片
kong Gateway 使用说明_第7张图片

4、为service添加Route

kong Gateway 使用说明_第8张图片
kong Gateway 使用说明_第9张图片
kong Gateway 使用说明_第10张图片

5、Consumer

kong Gateway 使用说明_第11张图片
kong Gateway 使用说明_第12张图片
kong Gateway 使用说明_第13张图片
kong Gateway 使用说明_第14张图片

6、plugins

kong Gateway 使用说明_第15张图片
kong Gateway 使用说明_第16张图片

五、kubernetes kongIngress

kong Gateway 使用说明_第17张图片
说明: 下例代码是我在生产环境的清单,镜像仓库我已经隐藏,且在本人环境中连接镜像仓库是需要secret的,所以在清单中出现了“ imagePullSecrets: [ name: harbor-secret ] ” 的内容,各位朋友在使用时可根据自己的需要修改或删除。
cat 01-kong-namespace.yaml

---
apiVersion: v1
kind: Namespace
metadata:
  name: kong
---
kind: Secret
apiVersion: v1
metadata:
  name: harbor-secret
  namespace: kong
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: eyJhdXRocyI6eyJoYXJ.....................

cat 02-CustomResourceDefinition.yaml

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

cat 03-rbac.yaml

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

cat 04-configmap.yaml

---
kind: ConfigMap
apiVersion: v1
metadata:
  name: kong-server-blocks
  namespace: kong
data:
  servers.conf: |
    # Prometheus metrics server
    server {
        server_name kong_prometheus_exporter;
        listen 0.0.0.0:9542; # can be any other port as well
        access_log off;

        location /metrics {
            default_type text/plain;
            content_by_lua_block {
                 local prometheus = require "kong.plugins.prometheus.exporter"
                 prometheus:collect()
            }
        }

        location /nginx_status {
            internal;
            stub_status;
        }
    }
    # Health check server
    server {
        server_name kong_health_check;
        listen 0.0.0.0:9001; # can be any other port as well

        access_log off;
        location /health {
          return 200;
        }
    }

cat 05-postgres-pv.yaml

---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: postgrespv01
  labels:
    name: postgrespv01
    function: postgres
spec:
  nfs:
    path: /data/volumes/postgresql7901
    server: 192.168.20.46
  accessModes: ["ReadWriteMany","ReadWriteOnce"]
  capacity:
    storage: 10Gi

cat 06-postgres-sts.yaml

---
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: kong
spec:
  ports:
  - name: pgql
    port: 5432
    protocol: TCP
    targetPort: 5432
  selector:
    app: postgres
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: kong
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  serviceName: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      imagePullSecrets:
        - name: harbor-secret
      containers:
      - env:
        - name: POSTGRES_USER
          value: kong
        - name: POSTGRES_PASSWORD
          value: kong
        - name: POSTGRES_DB
          value: kong
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        image: **************/postgres:9.6
        name: postgres
        ports:
        - containerPort: 5432
        volumeMounts:
        - mountPath: /var/lib/postgresql/data
          name: postgres-pvc
          subPath: pgdata
      terminationGracePeriodSeconds: 60
  volumeClaimTemplates:
  - metadata:
      name: postgres-pvc
    spec:
      selector:
        matchLabels:
          function: postgres
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi

cat 07-magrations.yaml

---
apiVersion: batch/v1
kind: Job
metadata:
  name: kong-migrations
  namespace: kong
spec:
  template:
    metadata:
      name: kong-migrations
    spec:
      imagePullSecrets:
        - name: harbor-secret
      containers:
      - command:
        - /bin/sh
        - -c
        - kong migrations bootstrap
        env:
        - name: KONG_PG_PASSWORD
          value: kong
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PORT
          value: "5432"
        image: *************/kong:2.0.2
        name: kong-migrations
      initContainers:
      - command:
        - /bin/sh
        - -c
        - until nc -zv $KONG_PG_HOST $KONG_PG_PORT -w1; do echo 'waiting for db';
          sleep 1; done
        env:
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PORT
          value: "5432"
        image: busybox
        name: wait-for-postgres
      restartPolicy: OnFailure

---
apiVersion: batch/v1
kind: Job
metadata:
  name: konga-migrations
  namespace: kong
spec:
  template:
    metadata:
      name: konga-migrations
    spec:
      imagePullSecrets:
        - name: harbor-secret
      containers:
      - command:
        - /bin/sh
        - -c
        - /app/start.sh -c prepare -a postgres -u postgresql://kong:kong@postgres:5432/konga
        env:
        - name: KONG_PG_PASSWORD
          value: kong
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PORT
          value: "5432"
        image: ******************/konga:latest
        name: kong-migrations
      initContainers:
      - command:
        - /bin/sh
        - -c
        - until nc -zv $KONG_PG_HOST $KONG_PG_PORT -w1; do echo 'waiting for db';
          sleep 1; done
        env:
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PORT
          value: "5432"
        image: busybox
        name: wait-for-postgres
      restartPolicy: OnFailure

cat 08-ingress-kong.yaml

apiVersion: v1
kind: Service
metadata:
  name: kong-proxy
  namespace: kong
spec:
  type: NodePort
  ports:
  - name: kong-proxy
    port: 80
    targetPort: 8000
    nodePort: 80
    protocol: TCP
  - name: kong-proxy-ssl
    port: 443
    targetPort: 8443
    nodePort: 443
    protocol: TCP
  externalTrafficPolicy: Local
  selector:
    app: ingress-kong
---
apiVersion: v1
kind: Service
metadata:
  name: kong-proxy-admin
  namespace: kong
spec:
  ports:
  - name: kong-proxy-admin
    port: 8001
    targetPort: 8001
    protocol: TCP
  - name: kong-proxy-admin-ssl
    port: 8444
    targetPort: 8444
    protocol: TCP
  selector:
    app: ingress-kong
---
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: 2
  selector:
    matchLabels:
      app: ingress-kong
  template:
    metadata:
      annotations:
        kuma.io/gateway: enabled
        prometheus.io/port: "9542"
        prometheus.io/scrape: "true"
        traffic.sidecar.istio.io/includeInboundPorts: ""
      labels:
        app: ingress-kong
    spec:
      imagePullSecrets:
        - name: harbor-secret
      nodeSelector:
        ingress: proxy
      containers:
      - env:
        - name: KONG_DATABASE
          value: postgres
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PASSWORD
          value: kong
        - name: KONG_NGINX_WORKER_PROCESSES
          value: "1"
        - name: KONG_NGINX_HTTP_INCLUDE
          value: /kong/servers.conf
        - name: KONG_ADMIN_ACCESS_LOG
          value: /dev/stdout
        - name: KONG_ADMIN_ERROR_LOG
          value: /dev/stderr
        - name: KONG_ADMIN_LISTEN
          value: 0.0.0.0:8001, 0.0.0.0:8444 ssl
        - name: KONG_PROXY_LISTEN
          value: 0.0.0.0:8000, 0.0.0.0:8443 ssl http2
        image: ***********/kong:2.0.2
        lifecycle:
          preStop:
            exec:
              command:
              - /bin/sh
              - -c
              - kong quit
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /health
            port: 9001
            scheme: HTTP
          initialDelaySeconds: 30
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: proxy
        ports:
        - containerPort: 8000
          name: proxy
          protocol: TCP
        - containerPort: 8443
          name: proxy-ssl
          protocol: TCP
        - containerPort: 9542
          name: metrics
          protocol: TCP
        - containerPort: 8444
          name: proxy-admin
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /health
            port: 9001
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        securityContext:
          runAsUser: 1000
        volumeMounts:
        - mountPath: /kong
          name: kong-server-blocks
      - args:
        - /kong-ingress-controller
        - --kong-url=https://localhost:8444
        - --admin-tls-skip-verify
        - --publish-service=kong/kong-proxy
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
        image: ************/kong-ingress-controller:0.8.0
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          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: 10
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
      initContainers:
      - command:
        - /bin/sh
        - -c
        - while true; do kong migrations list; if [[ 0 -eq $? ]]; then exit 0; fi;
          sleep 2;  done;
        env:
        - name: KONG_PG_HOST
          value: postgres
        - name: KONG_PG_PASSWORD
          value: kong
        image: ***************/kong:2.0.2
        name: wait-for-migrations
      serviceAccountName: kong-serviceaccount
      volumes:
      - configMap:
          name: kong-server-blocks
        name: kong-server-blocks
      tolerations:
      - key: "node-role.kubernetes.io/master"
        operator: "Equal"
        value: ""
        effect: "NoSchedule"

cat 09-dashboard-konga.yaml

---
apiVersion: v1
kind: Service
metadata:
  name: konga-proxy
  namespace: kong
spec:
  ports:
  - name: konga-proxy
    port: 1337
    targetPort: 1337
    nodePort: 1337
    protocol: TCP
  selector:
    app: dashboard-konga
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: dashboard-konga
  name: konga
  namespace: kong
spec:
  replicas: 1
  selector:
    matchLabels:
      app: dashboard-konga
  template:
    metadata:
      annotations:
        prometheus.io/port: "1337"
        prometheus.io/scrape: "true"
        traffic.sidecar.istio.io/includeInboundPorts: ""
      labels:
        app: dashboard-konga
    spec:
      imagePullSecrets:
        - name: harbor-secret
      nodeSelector:
        ingress: proxy
      containers:
      - env:
        - name: NODE_ENV
          value: production
        - name: DB_ADAPTER
          value: postgres
        - name: DB_URI
          value: postgresql://kong:kong@postgres:5432/konga
        image: ***********************/konga:latest
        name: konga
        ports:
        - containerPort: 1337
          name: konga-port
          protocol: TCP
      tolerations:
      - key: "node-role.kubernetes.io/master"
        operator: "Equal"
        value: ""
        effect: "NoSchedule"

六、排错

(有同学反馈在创建kong的数据库时不指定密码,后期在操作时会出现错误提示,所以在此补充 使用指定用户名、密码的方式安装kong)

如果创建数据库时指定了用户名、密码,如下所示:

# docker run -d --name kong-database \
>                --network=kong-net \
>                -p 5432:5432 \
>                -e "POSTGRES_USER=kong" \
>                -e "POSTGRES_DB=kong" \
>                -e "POSTGRES_PASSWORD=kong" \
>                postgres:9.6
>                Unable to find image 'postgres:9.6' locally
>                9.6: Pulling from library/postgres
>                6d28e14ab8c8: Pull complete
Digest: sha256:92042d6c1c79d2a48856803b750bad4bc153676a797109f6836e55ddc96b404f
Status: Downloaded newer image for postgres:9.6
3fac04d9c4c9faa3af70324619f24c38921c33efd38dc177b2edb6d50e0ce5b6

(大家根据自己的环境配置ENV,没有必要配置两种数据库的Endpoint,本次仅配置了postgres的Endpoint)

创建库时指定了用户名与密码,初始化数据库时需要也指定用户名、密码,如下所示:

# docker run --rm \
>      --network=kong-net \
>      -e "KONG_DATABASE=postgres" \
>      -e "KONG_PG_HOST=kong-database" \
>      -e "KONG_PG_PASSWORD=kong" \
>      kong:latest kong migrations bootstrap
Unable to find image 'kong:latest' locally
latest: Pulling from library/kong
4167d3e14976: Pull complete
3f12465f7519: Pull complete
0844b942a3e9: Pull complete
Digest: sha256:39b9d3226a26daa2eba233c8d6096b59f8f26c1bbc0595a44dabea00a6c01a7e
Status: Downloaded newer image for kong:latest
Bootstrapping database...
migrating core on database 'kong'...
core migrated up to: 000_base (executed)
core migrated up to: 003_100_to_110 (executed)
response-ratelimiting migrated up to: 000_base_response_rate_limiting (executed)
migrating session on database 'kong'...
session migrated up to: 000_base_session (executed)
24 migrations processed
24 executed
Database is up-to-date

运行kong时一般不会出现错误;提示:尽量不要把8001、8444绑在127.0.0.1端口上。

在初始化 konga的数据库 时,需要指定network及 postgresql的主机名,如下所示:

# docker run --network=kong-net --rm pantsel/konga:latest -c prepare -a postgres -u postgresql://kong:kong@kong-database:5432/konga
debug: Preparing database...
Using postgres DB Adapter.
Database `konga` does not exist. Creating...
Database `konga` created! Continue...
debug: Hook:api_health_checks:process() called
debug: Hook:health_checks:process() called
debug: Hook:start-scheduled-snapshots:process() called
debug: Hook:upstream_health_checks:process() called
debug: Hook:user_events_hook:process() called
debug: Seeding User...
debug: User seed planted
debug: Seeding Kongnode...
debug: Kongnode seed planted
debug: Seeding Emailtransport...
debug: Emailtransport seed planted
debug: Database migrations completed!
#

最终运行 konga 如下所示:

# docker run -d -p 1337:1337 --network kong-net -e "TOKEN_SECRET=P@ssw0rd" -e "DB_ADAPTER=postgres" -e "DB_URI=postgresql://kong:kong@kong-database:5432/konga"  -e "NODE_ENV=production" --name konga  pantsel/konga
8fc6afaa5bc59adf40260c7333e1cd64555876a9792a6719cdb5f5436e3ee440
#

效果如下:

# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                                NAMES
ba15365f681c        dpage/pgadmin4      "/entrypoint.sh"         13 minutes ago      Up 13 minutes       443/tcp, 0.0.0.0:8090->80/tcp                                        pgadmin
8fc6afaa5bc5        pantsel/konga       "/app/start.sh"          22 minutes ago      Up 22 minutes       0.0.0.0:1337->1337/tcp                                               konga
14cb5bb8d25e        kong:latest         "/docker-entrypoint.…"   43 minutes ago      Up 43 minutes       0.0.0.0:8000-8001->8000-8001/tcp, 0.0.0.0:8443-8444->8443-8444/tcp   kong
3fac04d9c4c9        postgres:9.6        "docker-entrypoint.s…"   48 minutes ago      Up 48 minutes       0.0.0.0:5432->5432/tcp                                               kong-database
#