Kong基础

介绍

技术特性适用场景说明
Kong– 基于OpenResty编写
– 高可用
– 易扩展
– 支持Cassandra存储
– 支持PostgreSQL存储
– restfull 方式 管理admin api
– 插件化支持
– 集群中的节点通过gossip协议自动发现其它节点
网关– 官网
– Kong Community Edition (CE)
– Github
– Docs
– Install Kong Community Edition
– Quickstart
– 入门
– FAQS
– Kong插件
konga– 多用户管理
– 管理多个Kong节点
– 电子邮件异常信息通知
– 管理所有Kong Admin API
– 使用快照备份,还原和迁移Kong节点
– 使用运行状况检查监控节点和API状态
– 轻松的数据库集成(MySQL、postgresSQL、MongoDB)
Kong GUI– 官网
– Github
– Doc
Kong dashboard– 基于node.jsKong GUI官方推荐UI管理工具
– Github
kongdash– 支持windows、MacOS、Ubuntu、Fedoradesktop client for Kong Admin API– 官网
– Github
– 下载

基本概念

名称说明
serviceupstream services的抽象。
Service的主要属性是它的URL。
服务与路由相关联(服务可以有许多与之关联的路由)
Route路由是进入Kong的入口点,并为要匹配的请求定义规则,并路由到给定的Service。
Route定义匹配客户端请求的规则。每个Route与一个服务相关联,一个服务可能有多个与之关联的路由。匹配给定路由的每个请求都将代理到其关联的服务。
upstream service这是指位于Kong后面的您自己的API /服务,转发客户端请求。
target
consumerAPI可能没有用户概念,会出现随意调用的情况。为此Kong提供了一种consumer对象(全局共用),如某API启用了key-auth,没有身份的访问者将无法调用该API。
api用于表示上游服务的旧实体。不推荐使用。

安装Kong

先决条件

安装PostgreSQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ yum -y install https://download.postgresql.org/pub/repos/yum/11/redhat/rhel-7-x86_64/pgdg-centos11-11-2.noarch.rpm
$ yum -y install postgresql11
$ yum -y install postgresql11-server
$ /usr/pgsql-11/bin/postgresql-11-setup initdb
$ systemctl enable postgresql-11
$ systemctl start postgresql-11
$ su – postgres
$ psql
$ CREATE USER kong;
$ CREATE DATABASE kong OWNER kong;
$ alter user kong with encrypted password ‘123456’;
\q
$ find / -name “postgresql.conf”
$ vi /var/lib/pgsql/11/data/postgresql.conf
# 修改 listen_addresses项值设定为“*”
$ find / -name “pg_hba.conf”
$ vi /var/lib/pgsql/11/data/pg_hba.conf
# 添加以下内容
host all all 0.0.0.0/0 md5
$ systemctl restart postgresql-11

CentOS7中RPM方式安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 下载
$ cd /usr/local
$ wget https://bintray.com/kong/kong-rpm/download_file?file_path=centos/7/kong-1.3.0.el7.amd64.rpm

# 安装
$ yum localinstall kong-1.3.0.el7.amd64.rpm

# 配置kong的配置文件
$ whereis kong
$ cd /etc/kong/
$ cp kong.conf.default kong.conf
##### 内容开始 #####
database = postgres
pg_host = 10.10.1.179
pg_port = 5432
pg_user = kong
pg_password = 123456
pg_database = kong
##### 内容结束 #####

# 初始化kong的数据库
$ kong migrations up -c /etc/kong/kong.conf

# 启动kong
$ kong start -c /etc/kong/kong.conf

# 测试是否安装成功
$ curl -i http://localhost:8001/

kong的默认值

说明
kong默认的代理地址proxy_listen = 0.0.0.0:8000, 0.0.0.0:8443
默认的管理地址admin_listen = 127.0.0.1:8001, 127.0.0.1:8444 ssl

安装kong-dashboard

npm安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 安装npm
$ yum -y install npm

# 安装kong-dashboard
$ npm install -g kong-dashboard

##### 启动kong-dashboard #####
# 查看启动选项的完整列表
$ kong-dashboard start –help
# 启动Kong Dashboard
$ kong-dashboard start –kong-url http://127.0.0.1:8001
# 在自定义端口上启动Kong Dashboard
kong-dashboard start \
–kong-url http://kong:8001 \
–port [port]
# 使用基本身份验证启动Kong Dashboard
kong-dashboard start \
–kong-url http://kong:8001 \
–basic-auth user1=password1 user2=password2
##### 启动kong-dashboard #####

# 访问kong-dashboard
$ curl http://127.0.0.1:8080

Docker安装

1
2
3
4
5
6
7
8
9
10
11
12
13
# 查看启动选项的完整列表
docker run –rm -p 8080:8080 pgbi / kong-dashboard start –help

# 启动Kong Dashboard
$ docker run –rm -p 8080:8080 pgbi / kong-dashboard start –kong-url http:// kong:8001

# 在自定义端口上启动Kong Dashboard
$ docker run –rm -p [port]:8080 pgbi / kong-dashboard start –kong-url http:// kong:8001

# 使用基本身份验证启动Kong Dashboard
$ docker run –rm -p 8080:8080 pgbi / kong-dashboard start \
–kong-url http:// kong:8001
–basic-auth user1 = password1 user2 = password2

安装konga

先决条件

  • 安装node.js 8.0+
  • 安装npm

CentOS7安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
##### 安装node.js 8+ ######
$ cd /usr/local
$ wget https://nodejs.org/dist/v10.14.2/node-v10.14.2-linux-x64.tar.xz
$ tar -xJvf node-v10.14.2-linux-x64.tar.xz
$ mv node-v10.14.2-linux-x64 node
$ vi /etc/profile
##### 在末尾处添加如下
export NODEJS_HOME=/usr/local/node
export PATH=$NODEJS_HOME:$PATH
##### 使环境变量生效
$ source /etc/profile
$ node –version
##### 安装bower ######
$ npm install bower -g
$ bower -v
##### 安装gulp ######
$ npm install gulp -g
$ gulp -v
##### 安装grunt ######
$
##### 安装konga ######
$ git clone https://github.com/pantsel/konga.git
$ cd konga
$ npm i

# 启动
$ npm start
$ curl http://localhost:1337

Admin API

节点信息

查询节点信息

1
$ curl http://localhost:8001
字段说明
node_id正在运行的kong节点的uuid,当kong启动时随机生成,每次kong重启时这个uuid都会变
availabel_on_serverkong节点上安装的plugins的名称
enabled_in_clusterkong节点中启用的插件,即在数据库中生成了对应存储表

查询节点状态

1
$ curl http://localhost:8001/status
字段说明
total_requests客户端请求总数
connections_active包括等待连接的活动客户端连接的当前数量
connections_accepted接受的客户端连接的总数
connections_handled处理连接的总数。一般来说,除非达到一定的资源限制,否则参数值与接受值相同
connections_reading当前Kong正在读取请求头的连接数
connections_writingNGINX将响应写入客户端的连接的当前数量
connections_waiting等待请求的空闲客户端连接的当前数量
reachable反映数据库连接状态的布尔值。注意,此标志不反映数据库本身的健康状况。

Service

添加Service

1
2
$ curl -i -X POST http://localhost:8001/services -d “name=test.service” -d “url=http://后端服务域名/api”
$ curl -i -X POST http://localhost:8001/services -d “name=test.service” -d “protocol=http” -d “host=hxonline.hxsd.cn” -d “path=/api”
字段说明
name服务名称
protocol协议:http or https 默认是 http
host后端服务域名
port后端服务端口
path后端服务子路径;没有就填 ‘/‘
retries重试次数:默认 5次
connect_timeout请求后端服务的超时时间:默认60000 ms
write_timeout写超时时间:默认60000 ms
read_timeout读超时时间:默认60000 ms
url后端服务url地址

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ curl -i -X POST \
–url http://localhost:8001/services/ \
–data ‘name=example-service’ \
–data ‘url=http://mockbin.org’
HTTP/1.1 201 Created
Date: Thu, 13 Dec 2018 07:36:57 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.14.1
Content-Length: 259

{“host”:”mockbin.org”,”created_at”:1544704617,”connect_timeout”:60000,”id”:”c7be1fbd-c8dc-42a5-9397-a494514db290″,”protocol”:”http”,”name”:”example-service”,”read_timeout”:60000,”port”:80,”path”:null,”updated_at”:1544704617,”retries”:5,”write_timeout”:60000}

查询所有Service

1
$ curl -i -X GET http://localhost:8001/services

示例:

1
2
3
4
5
6
7
8
9
10
$ curl -i -X GET http://localhost:8001/services/
HTTP/1.1 200 OK
Date: Thu, 13 Dec 2018 07:42:02 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.14.1
Content-Length: 282

{“next”:null,”data”:[{“host”:”mockbin.org”,”created_at”:1544704617,”connect_timeout”:60000,”id”:”c7be1fbd-c8dc-42a5-9397-a494514db290″,”protocol”:”http”,”name”:”example-service”,”read_timeout”:60000,”port”:80,”path”:null,”updated_at”:1544704617,”retries”:5,”write_timeout”:60000}]}

查询某个Service

1
$ curl -i -X GET http://localhost:8001/services/{服务名称 or 服务id}

示例:

1
2
3
4
5
6
7
8
9
10
$ curl -i -X GET http://localhost:8001/services/example-service
HTTP/1.1 200 OK
Date: Thu, 13 Dec 2018 08:02:24 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.14.1
Content-Length: 247

{“host”:”mockbin.org”,”created_at”:1544704617,”connect_timeout”:60000,”id”:”c7be1fbd-c8dc-42a5-9397-a494514db290″,”protocol”:”http”,”name”:”example-service”,”read_timeout”:60000,”port”:80,”updated_at”:1544704617,”retries”:5,”write_timeout”:60000}

获取某个路由下的Service

1
2
$ curl -i -X GET http://localhost:8001/routes/{路由ID}/service
$ curl -i -X GET http://localhost:8001/routes/xxxx-xxx-xxx-xx/service

更新Service

1
$ curl -i -X PUT http://localhost:8001/services/{服务名称或ID} -d “name=test.service” -d “protocol=http” -d “host=hxonline.hxsd.cn” -d “path=/api”

删除Service

1
2
$ curl -i -X DELETE http://localhost:8001/services/{服务名称或ID}
$ curl -i -X DELETE http://localhost:8001/services/test.service

Route

添加Route

1
2
3
4
$ curl -i -X POST –url http://localhost:8001/routes/ \
-d ‘protocols[]=http&protocols[]=https’ \
-d ‘paths=/test’ \
-d ‘service.id=xxx-xxxx-xxxx-xx’

示例:

1
2
3
4
5
6
7
8
9
10
11
12
$ curl -i -X POST \
–url http://localhost:8001/services/example-service/routes \
–data ‘hosts[]=example.com’
HTTP/1.1 201 Created
Date: Thu, 13 Dec 2018 08:06:10 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.14.1
Content-Length: 290

{“created_at”:1544688370,”strip_path”:true,”hosts”:[“example.com”],”preserve_host”:false,”regex_priority”:0,”updated_at”:1544688370,”paths”:null,”service”:{“id”:”c7be1fbd-c8dc-42a5-9397-a494514db290″},”methods”:null,”protocols”:[“http”,”https”],”id”:”076d68f8-47fd-47aa-af48-40e71677aa9c”}

访问接口:

1
2
3
$ curl -i -X GET \
–url http://localhost:8000/ \
–header ‘Host: example.com’

可以在/etc/hostsname中将example.com地址配置为kong所在的机器的地址:

1
10.10.192.35 example.com

然后就可以通过example.com:8000打开http://mockbin.org。

字段是否必填说明
protocols必填协议列表,http、https。设置:protocols[]=http&protocols[]=https
methods半选填
默认是二者都行
接受请求的方法:GET 或 POST ,二者都行。设置 methods[]=GET&methods[]=POST
hosts半选填与此路由匹配的域名列表。例如:example.com。用作form-encode, 设置:hosts[]= Foo.com和hosts[]= BAR.com
paths必填与此路由匹配的路径列表。
例如:/test
strip_path选填
preserve_host选填
service必填与此路由绑定的服务。
设置:service.id=

获取全部Route

1
$ curl -i -X GET http://localhost:8001/routes/

获取某个Route

1
2
# xxx-xxx-xxx 路由ID
$ curl -i -X GET http://localhost:8001/routes/xxx-xxx-xxx

获取某Service下的Route

1
$ curl -i -X GET http://localhost:8001/services/{服务名或服务ID}/routes

更新Route

可以用 PATCH 和 PUT,PATCH可以修改已存在的路由,PUT 如果路由不存在则新建一个。

1
2
3
4
# xxx-xxx-xxx 路由ID
$ curl -i -X PUT http://localhost:8001/routes/xxx-xxx-xxx \
-d ‘protocols[]=http&protocols[]=https’ \
-d ‘paths=test’ \

删除Route

1
2
# xxx-xxx-xxx 路由ID
$ curl -i -X DELETE http://localhost:8001/routes/xxx-xxx-xxx

配置upstream

1
$ curl -X POST http://localhost:8001/upstreams –data “name=helloUpstream”

配置 target

1
$ curl -X POST http://localhost:8001/upstreams/hello/targets –data “target=localhost:3000” –data “weight=100”

配置Consumer

添加Consumer

1
2
3
4
5
6
7
8
# 创建一个consumer
$ curl -X POST \
–data “username=oauthadmin” \
–data “custom_id=personapi” \
http://127.0.0.1:8001/consumers/
# 在key-auth插件中为此consumer生成key
$ curl -X POST \
http://127.0.0.1:8001/consumers/oauthadmin/key-auth

配置插件

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

1
2
3
$ curl -X POST http://localhost:8001/services/hello/plugins \
–data “name=rate-limiting” \
–data “config.second=50”

为 hello 服务添加 jwt 插件

1
2
$ curl -X POST http://localhost:8001/services/login/plugins \
–data “name=jwt”

将插件安装在路由上

1
2
3
4
5
6
$ 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”

配置Certificates

1
$

kong与Consul集成

您可以通过指定dns_resolver属性(在kong.conf配置文件中)指向Consul服务器(或通过设置KONG_DNS_RESOLVER=环境变量)使Kong与Consul一起使用。 通过这样做,迫使Kong使用Consul来解析upstream_url API 中的主机名地址。 参考

运维

管理kong

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 查看版本
$ kong version

# 启动
$ kong start -c /etc/kong/kong.conf

# 停止
$ kong stop

# 重新加载
$ kong reload

# 重启
$ kong restart

# 验证配置
$ kong check /etc/kong/kong.conf

# 健康检查
$ kong health

# 初始化数据库配置
$ kong migrations up -c /etc/kong/kong.conf

配置集群

配置健康检查

配置断路器

配置监控

插件

认证

Basic Authentication

JWT

Key Authentication

LDAP Authentication

OAuth 2.0 Authentication

OKTA

Upstream HTTP Basic Authentication

安全

Bot Detection

CORS

IP Restriction

Cleafy plugin for Kong

Kong Spec Expose

Kong Upstream JWT

Signal Sciences

Wallarm

流控

ACL

Rate Limiting

Request Termination

Response Rate Limiting

Kong Response Size Limiting

Kong Service Virtualization

Request Size Limiting

分析和监控

Datadog

Prometheus

Zipkin

Moesif API Insights

SignalFx

日志

TCP、UDP、HTTP、File、Syslog、StatsD、Loggly等

常见问题

附录

数据字典

acls

字段名类型默认值说明
iduuid
consumer_iduuid
grouptext

apis

字段名类型默认值说明
iduuid
nametext
upstream_urltext
preserve_hostbool
created_attimestamp(6)
retriesint25
https_onlybool
http_if_terminatedbool
hoststext
uristext
methodstext
strip_uribool
upstream_connect_timeoutint4
upstream_send_timeoutint4
upstream_read_timeoutint4

basicauth_credentials

字段名类型默认值说明
iduuid
consumer_iduuid
usernametext
passwordtext
created_attimestamp(6)

certificates

id | uuid | | |
cert | text | | |
key | text | | |
created_at | timestamptz | | – |

cluster_events

字段名类型默认值说明
iduuid
node_iduuid
attimestamp(6)
nbftimestamp(6)
expire_attimestamp(6)
channeltext
datatext

consumers

字段名类型默认值说明
iduuid
custom_idtext
usernametext
created_at

hmacauth_credentials

字段名类型默认值说明
iduuid
consumer_iduuid
usernametext
secrettext
created_attimestamp(6)

jwt_secrets

字段名类型默认值说明
iduuid
consumer_iduuid
keytext
secrettext
created_attimestamp(6)
algorithmtext
rsa_public_keytext

keyauth_credentials

字段名类型默认值说明
iduuid
consumer_iduuid
keytext
created_attimestamp(6)

oauth2_authorization_codes

字段名类型默认值说明
iduuid
codetext
authenticated_useridtext
scopetext
created_attimestamp(6)
credential_iduuid
api_iduuid
service_iduuid

oauth2_credentials

字段名类型默认值说明
iduuid
nametext
consumer_id
client_idtext
client_secrettext
redirect_uritext
created_attimestamp(6)

oauth2_tokens

字段名类型默认值说明
iduuid
credential_iduuid
access_tokentext
token_typetext
refresh_tokentext
expires_inint4
authenticated_useridtext
scopetext
created_attimestamp(6)
api_iduuid
service_iduuid

plugins

字段名类型默认值说明
iduuid
nametext
api_iduuid
consumer_iduuid
configjson
enabledbool
created_attimestamp(6)
route_iduuid
service_iduuid

ratelimiting_metrics

字段名类型默认值说明
iduuid
identifiertext
periodtext
period_datetimestamp(6)
valueint4
route_iduuid
service_iduuid

response_ratelimiting_metrics

字段名类型默认值说明
iduuid
identifiertext
periodtext
period_datetimestamp(6)
valueint4
route_iduuid
service_iduuid

routes

字段名类型默认值说明
iduuid
created_attimestamp(6)
updated_attimestamp(6)
protocolstext[]
methodstext[]
hoststext[]
pathstext[]
regex_priorityint8
strip_pathbool
preserve_hostbool
service_iduuid

schema_migrations

字段名类型默认值说明
iduuid
migrationsvarchar(100)[]

services

字段名类型默认值说明
iduuid
created_attimestamp(6)创建时间
updated_attimestamp(6)更新时间
nametextServiceName
retriesint8代理失败时要执行的重试次数。默认值为5。
protocoltext协议。http/https
hosttextThe host of the upstream server
portint8The upstream server port. Defaults to 80
pathtextThe path to be used in requests to the upstream server. Empty by default.
connect_timeoutint8The timeout in milliseconds for establishing a connection to the upstream server. Defaults to 60000.
write_timeoutint8The timeout in milliseconds between two successive write operations for transmitting a request to the upstream server. Defaults to 60000.
read_timeoutint8The timeout in milliseconds between two successive read operations for transmitting a request to the upstream server. Defaults to 60000.

snis

字段名类型默认值说明
iduuid
nametext
certificate_iduuid
created_attimestamp(6)

targets

字段名类型默认值说明
iduuid
targettext
weightint4
upstream_iduuid
created_attimestamp(6)

ttls

字段名类型默认值说明
primary_key_valuetext
primary_uuid_valueuuid
table_nametext
primary_key_nametext
expire_attimestamp(6)

upstreams

字段名类型默认值说明
iduuid
nametext
slotsint4
created_attimestamp(6)
healthchecksjson
hash_ontext
hash_fallbacktext
hash_on_headertext
hash_fallback_headertext
hash_on_cookietext
hash_on_cookie_pathtext

参考

开源

文档

Kong系列

文章