1. Kong介绍

官网:https://konghq.com/

1.1 Kong网关的特性

1.2 Kong网关架构

2.Kong环境搭建

2.1 基于centos7搭建

2.1.1 Postgressql

安装命令:

安装地址
选择:
image.png

配置Postgressql

  1. # 创建一个linux 用户 kong
  2. adduser kong
  3. #切换到linux系统用户 'postgres', 因为他是postgressql 数据库的系统管理员
  4. su postgres
  5. # 进入Postgreqsql控制台
  6. psql
  7. #设置用户postgres的密码【仅首次需要】
  8. \password postgres
  9. #创建一个Postgressql用户 ‘kong’, 和上面创建的Linux用户 'kong'对应
  10. create user kong with password '123456'
  11. # 创建一个postgressql的数据库‘kong’
  12. create database kong owner kong;
  13. #将数据库kong授权给postgressql用户 ‘kong’
  14. grant all privileges on database kong to kong;
  15. #退出PostgresSql控制台
  16. \q

PostgresSQL的四种身份认证方式:
trust:

password 和 md5:

ident:

peer:

开启远程访问:
修改 /var/lib/pgsql/10/data/pg_hba.conf文件,注释掉所有默认配置,增加一条配置:
host all all 0.0.0.0/0 trust, 认证方式改成trust
image.png
默认配置在。postgressql只允许本地连接,所以需要修改/var/lib/pgsql/10/data/postgresql.conf
文件,增加listen_addresses = ‘*’,允许远程连接
image.png
telnet测试网络是否连通:
telnet 172.16.219.128 5432
若网络不通,检查服务器防火墙配置,本地开发默认关闭防火墙 systemctl stop firewalld

  1. 即时生效,重启后失效:
  2. 启动: systemctl start firewalld
  3. 查看状态: systemctl status firewalld
  4. 停止:systemctl stop firewalld
  5. 禁用:systemctl disable firewalld

数据库工具(navcat、dbeaver……)链接:

  1. ip:
  2. 172.16.219.128
  3. port:
  4. 5432
  5. user:
  6. kong
  7. pwd:
  8. 123456

2.1.2 安装Kong

centos下安装kong:
下载地址:https://docs.konghq.com/gateway/2.8.x/install-and-run/centos/
image.png
image.png

安装命令:

  1. # 获取安装文件
  2. wget https://download.konghq.com/gateway-2.x-centos-7/Packages/k/kong-2.0.5.el7.amd64.rpm
  3. # 安装
  4. sudo yum install kong-2.0.5.el7.amd64.rpm

配置Kong:

Kong的默认配置文件/etc/kong/kong.conf.default,使用cp /etc/kong/kong.conf.default /etc/kong/kong.conf 命令,拷贝一份新的配置文件
拷贝完成后,修改/etc/kong/kong.conf 配置文件,设置kong使用的数据源:
vim /etc/kong/kong.conf
image.png
执行 kong migrations bootstrap -c /etc/kong/kong.conf 命令,进行kong 的PostgreSQL数据库的表初始化。
表创建完成:
image.png
开启kong远程访问:
vim /etc/kong/kong.conf, 将127.0.0.1改成0.0.0.0
image.png

执行kong start -c /etc/kong/kong.conf 命令,启动kong

  1. # 启动命令
  2. kong start -c /etc/kong/kong.conf
  3. # 停止
  4. kong stop
  5. # 重新加载
  6. kong reload

启动成功后,会看到kong started日志。
image.png
默认情况下,kong绑定4个接口:

  • Proxy 8000: 接受客户端的http请求, 并转发到后段的Upstream
  • Proxy 8443: 接受客户端的https请求, 并转发到后段的Upstream
  • Proxy 8001: 接受客户端的http请求,进行kong的管理
  • Proxy 8444: 接受客户端的https请求, 进行kong的管理 ```shell

    请求 Proxy 端口

    curl http://127.0.0.1:8000 {“message”:”no Route matched with those values”}

    暂时没有配置kong的路由

请求Adming组件

注意: 考虑到安全性, Admin 端口只允许本机访问

curl http://127.0.0.1:8001 {“plugins”:{“enabled_in_cluster”:[],”available_on_server”:{……

  1. <a name="i7hBq"></a>
  2. ### 2.1.3安装Konga
  3. > <a name="jAngK"></a>
  4. #### 我这里使用docker安装Konga,npm安装各种失败,真让人崩溃。
  5. <a name="A7QA7"></a>
  6. #### 拉取konga
  7. > kong目前使用`Cassandra`、`Postgres`来存储数据
  8. ```shell
  9. docker pull pantsel/konga

创建一个自定义网络,允许多个容器之间相互发现和通讯。

  1. docker network create kong-net

准备kong的数据库(初始化kona数据库,我这里是用的外部postgres)

  1. docker run --network=kong-net \
  2. --rm pantsel/konga -c prepare -a postgres \
  3. -u postgresql://kong:123456@172.16.219.128:5432/konga

启动konga

  1. docker run -d -p 1337:1337 \
  2. --network=kong-net \
  3. --name konga \
  4. -e "DB_ADAPTER=postgres" \
  5. -e "DB_URI=postgresql://kong:123456@172.16.219.128:5432/konga" \
  6. -e "NODE_ENV=production" \
  7. pantsel/konga

登陆konga

http://172.16.219.128:1337/
首次登陆需要设置用户名(kong)、密码(kong@123)
首次需要配置kong admin连接地址:
image.png
至此konga配置完成:
image.png

2.2 基于docker 安装kong,konga

引用:https://www.yuque.com/steel.li/docker/zqeyyn

搭建环境: docker 20.10.6 centos7

2.2.1 拉取kong、konga、postgres

传送门

kong目前使用Cassandra、Postgres来存储数据

  1. $ docker pull kong
  2. $ docker pull pantsel/konga
  3. $ docker pull postgres:9.6

2.2.2 创建一个自定义网络,允许多个容器之间相互发现和通讯。

  1. $ docker network create kong-net

2.2.3 启动数据库

  1. $ docker run -d --name kong-database \
  2. --restart=always \
  3. --network=kong-net \
  4. -p 5432:5432 \
  5. -e "POSTGRES_USER=kong" \
  6. -e "POSTGRES_DB=kong" \
  7. -e "POSTGRES_PASSWORD=kong" \
  8. postgres:9.6

2.2.4 准备kong的数据库

  1. $ docker run --rm --network=kong-net \
  2. -e "KONG_DATABASE=postgres" \
  3. -e "KONG_PG_HOST=kong-database" \
  4. -e "KONG_PG_PASSWORD=kong" \
  5. -e "KONG_PASSWORD=kong" \
  6. kong:latest kong migrations bootstrap

2.2.5 kong启动网关

  1. $ docker run -d --name kong-oss --network=kong-net \
  2. --restart=always \
  3. -e "KONG_DATABASE=postgres" \
  4. -e "KONG_PG_HOST=kong-database" \
  5. -e "KONG_PG_PASSWORD=kong" \
  6. -e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
  7. -e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
  8. -e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
  9. -e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
  10. -e "KONG_ADMIN_LISTEN=0.0.0.0:8001" \
  11. -p 8000:8000 \
  12. -p 8443:8443 \
  13. -p 8001:8001 \
  14. -p 8444:8444 \
  15. -p 8002:8002 \
  16. -p 8445:8445 \
  17. -p 8003:8003 \
  18. -p 8004:8004 \
  19. kong:latest

2.2.6 安装kong管理UI(konga)

kong官网提供了管理UI,但是开源版本并没有看到,有许多的开源UI,我这里选择的konga

2.2.7 初始化konga数据库

  1. $ docker run --network=kong-net \
  2. --rm pantsel/konga -c prepare -a postgres \
  3. -u postgresql://kong:kong@172.19.3.40:5432/konga

2.2.8 启动konga

  1. $ docker run -d -p 1337:1337 \
  2. --network=kong-net \
  3. --name konga \
  4. -e "DB_ADAPTER=postgres" \
  5. -e "DB_URI=postgresql://kong:kong@172.19.3.40:5432/konga" \
  6. -e "NODE_ENV=production" \
  7. pantsel/konga

2.2.9 查看安装的kongaUI界面

浏览器打开http://172.19.3.40:1337/
注册、登录
API网关Kong实战 - 图12
登录进来后界面

2.2.10添加连接

API网关Kong实战 - 图13
API网关Kong实战 - 图14
点击上方红色框中图标,激活服务
激活后会显示出api gateway
API网关Kong实战 - 图15

3、kong的使用:

https://segmentfault.com/a/1190000019758461?utm_source=tag-newest

3.1 Add a Service

使用adming API的方式:

  1. curl -i -X POST http://localhost:8001/services \
  2. --data name=example_service \
  3. --data url='http://mockbin.org'
  4. #应答:
  5. HTTP/1.1 201 Created
  6. Date: Tue, 12 Apr 2022 16:24:17 GMT
  7. Content-Type: application/json; charset=utf-8
  8. Connection: keep-alive
  9. Access-Control-Allow-Origin: *
  10. Server: kong/2.0.5
  11. Content-Length: 296
  12. X-Kong-Admin-Latency: 202
  13. {
  14. "host":"mockbin.org",
  15. "created_at":1649780656,
  16. "connect_timeout":60000,
  17. "id":"7ea02d93-2efd-44e8-9fbb-17897c16be9d",
  18. "protocol":"http",
  19. "name":"example_service",
  20. "read_timeout":60000,
  21. "port":80,
  22. "path":null,
  23. "updated_at":1649780656,
  24. "retries":5,
  25. "write_timeout":60000,
  26. "tags":null,
  27. "client_certificate":null
  28. }

验证service:

  1. curl -i http://localhost:8001/services/example_service
  2. # 应答如下:
  3. HTTP/1.1 200 OK
  4. Date: Tue, 12 Apr 2022 16:28:41 GMT
  5. Content-Type: application/json; charset=utf-8
  6. Connection: keep-alive
  7. Access-Control-Allow-Origin: *
  8. Server: kong/2.0.5
  9. Content-Length: 296
  10. X-Kong-Admin-Latency: 5
  11. {
  12. "host":"mockbin.org",
  13. "created_at":1649780656,
  14. "connect_timeout":60000,
  15. "id":"7ea02d93-2efd-44e8-9fbb-17897c16be9d",
  16. "protocol":"http",
  17. "name":"example_service",
  18. "read_timeout":60000,
  19. "port":80,
  20. "path":null,
  21. "updated_at":1649780656,
  22. "retries":5,
  23. "write_timeout":60000,
  24. "tags":null,
  25. "client_certificate":null
  26. }


3.2 Add a Route

  1. curl -i -X POST http://localhost:8001/services/example_service/routes \
  2. --data 'paths[]=/mock' \
  3. --data name=mocking
  4. # 应答如下:
  5. HTTP/1.1 201 Created
  6. Date: Tue, 12 Apr 2022 16:34:01 GMT
  7. Content-Type: application/json; charset=utf-8
  8. Connection: keep-alive
  9. Access-Control-Allow-Origin: *
  10. Server: kong/2.0.5
  11. Content-Length: 429
  12. X-Kong-Admin-Latency: 44
  13. {
  14. "id":"ef2ff070-e864-4828-8169-cca250b51f58",
  15. "path_handling":"v0",
  16. "paths":[
  17. "\/mock"
  18. ],
  19. "destinations":null,
  20. "headers":null,
  21. "protocols":[
  22. "http",
  23. "https"
  24. ],
  25. "methods":null,
  26. "snis":null,
  27. "service":{
  28. "id":"7ea02d93-2efd-44e8-9fbb-17897c16be9d"
  29. },
  30. "name":"mocking",
  31. "strip_path":true,
  32. "preserve_host":false,
  33. "regex_priority":0,
  34. "updated_at":1649781241,
  35. "sources":null,
  36. "hosts":null,
  37. "https_redirect_status_code":426,
  38. "tags":null,
  39. "created_at":1649781241
  40. }

验证Kong是否正确地通过Route将请求转发给Service。请注意,默认情况下,Kong在端口8000上处理代理请求:

  1. curl -i -X GET http://localhost:8000/mock/request
  2. # 应答如下
  3. HTTP/1.1 200 OK
  4. Content-Type: application/json; charset=utf-8
  5. Content-Length: 1002
  6. Connection: keep-alive
  7. Date: Sun, 24 Apr 2022 16:17:48 GMT
  8. Access-Control-Allow-Origin: *
  9. Access-Control-Allow-Methods: GET
  10. Access-Control-Allow-Headers: host,connection,accept-encoding,x-forwarded-for,cf-ray,x-forwarded-proto,cf-visitor,x-forwarded-host,x-forwarded-port,user-agent,accept,cf-connecting-ip,cdn-loop,x-request-id,via,connect-time,x-request-start,total-route-time
  11. Access-Control-Allow-Credentials: true
  12. X-Powered-By: mockbin
  13. Vary: Accept, Accept-Encoding
  14. Etag: W/"3ea-w1aFHW79jWrxyjLH+mtaBGsSbCQ"
  15. Via: kong/2.0.5
  16. CF-Cache-Status: DYNAMIC
  17. Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=DHOIH3T1QFJfOjML7w3neA0X4mlQW4LCixp042lVo3Qtz60xh8%2FEQNXdV3EVYEAA2d%2F%2FE%2F5qxIPj3t54x3IhI0wW8UBTW7BwXAu3PRwUeS%2BRfR0%2BonzmqNuPwicfjg%3D%3D"}],"group":"cf-nel","max_age":604800}
  18. NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
  19. Server: cloudflare
  20. CF-RAY: 701026b59dc58b4d-HKG
  21. alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
  22. X-Kong-Upstream-Latency: 701
  23. X-Kong-Proxy-Latency: 225
  24. {
  25. "startedDateTime": "2022-04-24T16:17:48.869Z",
  26. "clientIPAddress": "127.0.0.1",
  27. "method": "GET",
  28. "url": "http://localhost/request",
  29. "httpVersion": "HTTP/1.1",
  30. "cookies": {},
  31. "headers": {
  32. "host": "mockbin.org",
  33. "connection": "close",
  34. "accept-encoding": "gzip",
  35. "x-forwarded-for": "127.0.0.1,180.167.221.114, 172.68.253.55",
  36. "cf-ray": "701026b59dc58b4d-HKG",
  37. "x-forwarded-proto": "http",
  38. "cf-visitor": "{\"scheme\":\"http\"}",
  39. "x-forwarded-host": "localhost",
  40. "x-forwarded-port": "80",
  41. "user-agent": "curl/7.29.0",
  42. "accept": "*/*",
  43. "cf-connecting-ip": "180.167.221.114",
  44. "cdn-loop": "cloudflare",
  45. "x-request-id": "ca5e4735-13c0-4288-ab0e-90df8adc1cbd",
  46. "via": "1.1 vegur",
  47. "connect-time": "0",
  48. "x-request-start": "1650817068858",
  49. "total-route-time": "0"
  50. },
  51. "queryString": {},
  52. "postData": {
  53. "mimeType": "application/octet-stream",
  54. "text": "",
  55. "params": []
  56. },
  57. "headersSize": 531,
  58. "bodySize": 0
  59. }

为了验证路由结果的正确性,我们对比直接访问https://mockbin.org/request的结果:

  1. curl https://mockbin.org/request
  2. # 应答如下:
  3. {
  4. "startedDateTime": "2022-04-24T16:23:53.152Z",
  5. "clientIPAddress": "180.167.221.114",
  6. "method": "GET",
  7. "url": "https://mockbin.org/request",
  8. "httpVersion": "HTTP/1.1",
  9. "cookies": {},
  10. "headers": {
  11. "host": "mockbin.org",
  12. "connection": "close",
  13. "accept-encoding": "gzip",
  14. "x-forwarded-for": "180.167.221.114, 162.158.179.104",
  15. "cf-ray": "70102f9a8e033d42-HKG",
  16. "x-forwarded-proto": "http",
  17. "cf-visitor": "{\"scheme\":\"https\"}",
  18. "user-agent": "curl/7.29.0",
  19. "accept": "*/*",
  20. "cf-connecting-ip": "180.167.221.114",
  21. "cdn-loop": "cloudflare",
  22. "x-request-id": "994bf765-8aa9-4ff9-bc8e-adf359277088",
  23. "x-forwarded-port": "80",
  24. "via": "1.1 vegur",
  25. "connect-time": "0",
  26. "x-request-start": "1650817433155",
  27. "total-route-time": "0"
  28. },
  29. "queryString": {},
  30. "postData": {
  31. "mimeType": "application/octet-stream",
  32. "text": "",
  33. "params": []
  34. },
  35. "headersSize": 495,
  36. "bodySize": 0
  37. }

4. 插件开发

4.1 安装luarocks

  1. wget https://luarocks.org/releases/luarocks-2.4.1.tar.gz
  2. tar zxpf luarocks-2.4.1.tar.gz
  3. cd luarocks-2.4.1
  4. ./configure --with-lua-include=/usr/local/openresty/luajit/include/luajit-2.1/
  5. sudo make bootstrap
  1. mkdir -p "/usr/local/share/lua/5.1//luarocks"
  2. cp src/luarocks/site_config.lua "/usr/local/share/lua/5.1//luarocks"
  3. mkdir -p "/usr/local"
  4. 查看
  5. which luarocks
  6. /usr/local/bin/luarocks

4.2 给Service设置自定义插件[pre-processor]

先看效果:我们给请求头新增了【”x-root-mch-id”: “8988979087897879879879879”】

  1. curl -X POST http://localhost:8001/services/example_service/plugins \
  2. -d "name=pre-processor"
  3. # 应答如下:
  4. {
  5. "created_at":1649798158,
  6. "config":{
  7. },
  8. "id":"e1d8ecda-e94c-4b1a-8c35-13d842e6698b",
  9. "service":{
  10. "id":"7ea02d93-2efd-44e8-9fbb-17897c16be9d"
  11. },
  12. "enabled":true,
  13. "protocols":[
  14. "grpc",
  15. "grpcs",
  16. "http",
  17. "https"
  18. ],
  19. "name":"pre-processor",
  20. "consumer":null,
  21. "route":null,
  22. "tags":null
  23. }

再次访问:http://localhost:8000/mock/request

  1. curl http://localhost:8000/mock/request
  2. 应答如下:
  3. {
  4. "startedDateTime": "2022-04-24T21:30:19.671Z",
  5. "clientIPAddress": "127.0.0.1",
  6. "method": "GET",
  7. "url": "http://localhost/request",
  8. "httpVersion": "HTTP/1.1",
  9. "cookies": {},
  10. "headers": {
  11. "host": "mockbin.org",
  12. "connection": "close",
  13. "accept-encoding": "gzip",
  14. "x-forwarded-for": "127.0.0.1,101.93.124.5, 172.70.214.133",
  15. "cf-ray": "7011f0804c477d82-LAX",
  16. "x-forwarded-proto": "http",
  17. "cf-visitor": "{\"scheme\":\"http\"}",
  18. "x-forwarded-host": "localhost",
  19. "x-forwarded-port": "80",
  20. "user-agent": "curl/7.29.0",
  21. "accept": "*/*",
  22. "x-root-mch-id": "8988979087897879879879879",
  23. "cf-connecting-ip": "101.93.124.5",
  24. "cdn-loop": "cloudflare",
  25. "x-request-id": "612f5ead-cc1a-49e7-a5bf-a07cdf56b61c",
  26. "via": "1.1 vegur",
  27. "connect-time": "0",
  28. "x-request-start": "1650835819671",
  29. "total-route-time": "0"
  30. },
  31. "queryString": {},
  32. "postData": {
  33. "mimeType": "application/octet-stream",
  34. "text": "",
  35. "params": []
  36. },
  37. "headersSize": 568,
  38. "bodySize": 0
  39. }
  40. # 可以看到我们设置的 x-root-mch-id 生效了

实现代码如下:

  1. local plugin = {
  2. PRIORITY = 1000, -- set the plugin priority, which determines plugin execution order
  3. VERSION = "0.1.0", -- version in X.Y.Z format. Check hybrid-mode compatibility requirements.
  4. }
  5. -- runs in the 'access_by_lua_block'
  6. function plugin:access(plugin_conf)
  7. kong.service.request.set_header("X-Root-Mch-Id", "8988979087897879879879879")
  8. end --]]
  9. -- return our plugin object
  10. return plugin

源码位置:

插件部署:

  1. cd /etc/kong/kong-plugin/pre-processor/
  2. # 卸载
  3. luarocks remove kong-plugin-pre-processor-0.1.0-1.rockspec
  4. # 编译
  5. luarocks make kong-plugin-pre-processor-0.1.0-1.rockspec
  6. # 重新加载kong
  7. kong reload
  8. vim /etc/kong/kong-plugin/pre-processor/kong/plugins/pre-processor/handler.lua