Kong
Kong是一个云原生、快速、可扩展的分布式微服务抽象层(API网关),基于OpenResty(Nginx + Lua)构建,提供高性能的API管理和微服务治理功能。
核心特性
高性能架构
- 基于Nginx - 继承Nginx的高性能和稳定性
- Lua脚本 - 使用Lua进行插件开发,执行效率高
- 异步非阻塞 - 支持高并发处理
- 低延迟 - 请求处理延迟通常在毫秒级别
插件生态
- 丰富插件 - 提供50+官方插件和社区插件
- 热插拔 - 支持运行时动态加载和卸载插件
- 自定义插件 - 支持Lua和Go语言开发自定义插件
- 插件链 - 支持多个插件的组合使用
多种部署模式
- 传统模式 - 使用数据库存储配置
- DB-less模式 - 无数据库模式,配置文件驱动
- 混合模式 - 控制平面和数据平面分离
- 容器化 - 支持Docker和Kubernetes部署
架构设计
核心组件
点击查看完整代码实现
Kong架构:
├── Kong Gateway(数据平面)
│ ├── Nginx核心
│ ├── OpenResty框架
│ ├── Lua虚拟机
│ └── 插件运行时
├── Kong Manager(管理界面)
│ ├── Web GUI
│ ├── 配置管理
│ ├── 监控面板
│ └── 用户管理
├── Admin API
│ ├── RESTful API
│ ├── 配置管理
│ ├── 插件配置
│ └── 运行时管理
└── 数据存储
├── PostgreSQL
├── Cassandra
└── 内存缓存请求处理流程
Kong请求处理流程:
1. 客户端发送请求
2. Kong接收请求
3. 路由匹配
4. 插件处理(请求阶段)
5. 代理到上游服务
6. 插件处理(响应阶段)
7. 返回响应给客户端快速开始
Docker安装
使用PostgreSQL
点击查看完整代码实现
bash
# 启动PostgreSQL
docker run -d --name kong-database \
-p 5432:5432 \
-e "POSTGRES_USER=kong" \
-e "POSTGRES_DB=kong" \
-e "POSTGRES_PASSWORD=kong" \
postgres:13
# 初始化数据库
docker run --rm \
--link kong-database:kong-database \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
-e "KONG_PG_USER=kong" \
-e "KONG_PG_PASSWORD=kong" \
kong:latest kong migrations bootstrap
# 启动Kong
docker run -d --name kong \
--link kong-database:kong-database \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
-e "KONG_PG_USER=kong" \
-e "KONG_PG_PASSWORD=kong" \
-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 8000:8000 \
-p 8443:8443 \
-p 8001:8001 \
-p 8444:8444 \
kong:latestDB-less模式
点击查看完整代码实现
yaml
# kong.yml配置文件
_format_version: "3.0"
services:
- name: my-service
url: http://httpbin.org
routes:
- name: my-route
paths:
- /mock
plugins:
- name: rate-limiting
service: my-service
config:
minute: 5
hour: 100bash
# 使用配置文件启动Kong
docker run -d --name kong-dbless \
-v "$(pwd)/kong.yml:/kong/declarative/kong.yml" \
-e "KONG_DATABASE=off" \
-e "KONG_DECLARATIVE_CONFIG=/kong/declarative/kong.yml" \
-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" \
-p 8000:8000 \
-p 8001:8001 \
kong:latest基本配置
创建服务
bash
# 创建服务
curl -i -X POST http://localhost:8001/services/ \
--data "name=example-service" \
--data "url=http://httpbin.org"创建路由
bash
# 为服务创建路由
curl -i -X POST http://localhost:8001/services/example-service/routes \
--data "hosts[]=example.com" \
--data "paths[]=/example"测试访问
bash
# 测试API访问
curl -i -X GET \
--url http://localhost:8000/example/get \
--header "Host: example.com"Admin API使用
服务管理
点击查看完整代码实现
bash
# 创建服务
curl -X POST http://localhost:8001/services \
-H "Content-Type: application/json" \
-d '{
"name": "user-service",
"url": "http://user-api:8080",
"retries": 3,
"connect_timeout": 60000,
"write_timeout": 60000,
"read_timeout": 60000
}'
# 获取所有服务
curl http://localhost:8001/services
# 获取特定服务
curl http://localhost:8001/services/user-service
# 更新服务
curl -X PATCH http://localhost:8001/services/user-service \
-H "Content-Type: application/json" \
-d '{
"retries": 5,
"connect_timeout": 30000
}'
# 删除服务
curl -X DELETE http://localhost:8001/services/user-service路由管理
点击查看完整代码实现
bash
# 创建路由
curl -X POST http://localhost:8001/routes \
-H "Content-Type: application/json" \
-d '{
"name": "user-route",
"service": {"name": "user-service"},
"paths": ["/api/users"],
"methods": ["GET", "POST"],
"strip_path": true,
"preserve_host": false
}'
# 创建带正则表达式的路由
curl -X POST http://localhost:8001/routes \
-H "Content-Type: application/json" \
-d '{
"name": "api-v1-route",
"service": {"name": "user-service"},
"paths": ["/api/v1/~"],
"methods": ["GET", "POST", "PUT", "DELETE"],
"regex_priority": 100
}'
# 获取所有路由
curl http://localhost:8001/routes
# 删除路由
curl -X DELETE http://localhost:8001/routes/user-route上游服务和目标
点击查看完整代码实现
bash
# 创建上游服务
curl -X POST http://localhost:8001/upstreams \
-H "Content-Type: application/json" \
-d '{
"name": "user-upstream",
"algorithm": "round-robin",
"healthchecks": {
"active": {
"healthy": {
"interval": 10,
"successes": 3
},
"unhealthy": {
"interval": 10,
"http_failures": 3,
"timeouts": 3
}
}
}
}'
# 添加目标服务器
curl -X POST http://localhost:8001/upstreams/user-upstream/targets \
-H "Content-Type: application/json" \
-d '{
"target": "192.168.1.100:8080",
"weight": 100
}'
curl -X POST http://localhost:8001/upstreams/user-upstream/targets \
-H "Content-Type: application/json" \
-d '{
"target": "192.168.1.101:8080",
"weight": 100
}'
# 创建指向上游的服务
curl -X POST http://localhost:8001/services \
-H "Content-Type: application/json" \
-d '{
"name": "balanced-user-service",
"host": "user-upstream"
}'插件系统
认证插件
Key Authentication
点击查看完整代码实现
bash
# 启用Key认证插件
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "key-auth",
"config": {
"key_names": ["apikey", "X-API-Key"],
"hide_credentials": true
}
}'
# 创建消费者
curl -X POST http://localhost:8001/consumers \
-H "Content-Type: application/json" \
-d '{
"username": "john",
"custom_id": "user123"
}'
# 为消费者创建API Key
curl -X POST http://localhost:8001/consumers/john/key-auth \
-H "Content-Type: application/json" \
-d '{
"key": "my-secret-api-key"
}'
# 测试认证
curl -H "X-API-Key: my-secret-api-key" \
http://localhost:8000/api/usersJWT Authentication
点击查看完整代码实现
bash
# 启用JWT插件
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "jwt",
"config": {
"claims_to_verify": ["exp"],
"key_claim_name": "iss",
"secret_is_base64": false
}
}'
# 创建JWT凭证
curl -X POST http://localhost:8001/consumers/john/jwt \
-H "Content-Type: application/json" \
-d '{
"algorithm": "HS256",
"key": "my-key",
"secret": "my-secret"
}'安全插件
CORS插件
bash
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "cors",
"config": {
"origins": ["http://localhost:3000", "https://example.com"],
"methods": ["GET", "POST", "PUT", "DELETE"],
"headers": ["Accept", "Accept-Version", "Content-Length", "Content-MD5", "Content-Type", "Date", "X-Auth-Token"],
"exposed_headers": ["X-Auth-Token"],
"credentials": true,
"max_age": 3600
}
}'IP限制插件
bash
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "ip-restriction",
"config": {
"allow": ["127.0.0.1", "192.168.1.0/24"],
"deny": ["10.0.0.0/8"]
}
}'流量控制插件
限流插件
bash
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "rate-limiting",
"config": {
"minute": 20,
"hour": 500,
"day": 10000,
"policy": "redis",
"redis_host": "localhost",
"redis_port": 6379,
"redis_database": 0
}
}'请求大小限制
bash
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "request-size-limiting",
"config": {
"allowed_payload_size": 1024
}
}'分析和监控插件
Prometheus插件
bash
curl -X POST http://localhost:8001/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "prometheus",
"config": {
"per_consumer": true,
"status_code_metrics": true,
"latency_metrics": true,
"bandwidth_metrics": true,
"upstream_health_metrics": true
}
}'文件日志插件
bash
curl -X POST http://localhost:8001/services/user-service/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "file-log",
"config": {
"path": "/tmp/kong-access.log",
"reopen": true
}
}'自定义插件开发
Lua插件开发
点击查看完整代码实现
lua
-- kong/plugins/my-plugin/schema.lua
local typedefs = require "kong.db.schema.typedefs"
return {
name = "my-plugin",
fields = {
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ message = { type = "string", default = "Hello Kong!" } },
{ status_code = { type = "number", default = 200 } }
}
}}
}
}点击查看完整代码实现
lua
-- kong/plugins/my-plugin/handler.lua
local BasePlugin = require "kong.plugins.base_plugin"
local MyPluginHandler = BasePlugin:extend()
MyPluginHandler.PRIORITY = 1000
MyPluginHandler.VERSION = "0.1.0"
function MyPluginHandler:new()
MyPluginHandler.super.new(self, "my-plugin")
end
function MyPluginHandler:access(conf)
MyPluginHandler.super.access(self)
-- 插件逻辑
local message = conf.message
kong.log.info("My plugin executed: " .. message)
-- 添加请求头
kong.service.request.set_header("X-My-Plugin", message)
end
function MyPluginHandler:header_filter(conf)
MyPluginHandler.super.header_filter(self)
-- 添加响应头
kong.response.set_header("X-Kong-Response", conf.message)
end
return MyPluginHandlerGo插件开发(Kong 2.0+)
点击查看完整代码实现
go
package main
import (
"github.com/Kong/go-pdk"
"github.com/Kong/go-pdk/server"
)
type Config struct {
Message string
}
func New() interface{} {
return &Config{}
}
func (conf Config) Access(kong *pdk.PDK) {
// 插件逻辑
kong.Log.Info("Go plugin executed: " + conf.Message)
// 设置请求头
kong.ServiceRequest.SetHeader("X-Go-Plugin", conf.Message)
}
func (conf Config) Response(kong *pdk.PDK) {
// 设置响应头
kong.Response.SetHeader("X-Kong-Go", conf.Message)
}
func main() {
server.StartServer(New, "0.1.0", 1000)
}高可用部署
Docker Compose集群
点击查看完整代码实现
yaml
version: '3.7'
services:
kong-database:
image: postgres:13
environment:
POSTGRES_DB: kong
POSTGRES_USER: kong
POSTGRES_PASSWORD: kong
volumes:
- kong-database:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U kong"]
interval: 10s
timeout: 5s
retries: 5
kong-migration:
image: kong:latest
command: kong migrations bootstrap
depends_on:
kong-database:
condition: service_healthy
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_DATABASE: kong
KONG_PG_USER: kong
KONG_PG_PASSWORD: kong
restart: on-failure
kong-gateway-1:
image: kong:latest
depends_on:
kong-database:
condition: service_healthy
kong-migration:
condition: service_completed_successfully
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_DATABASE: kong
KONG_PG_USER: kong
KONG_PG_PASSWORD: kong
KONG_ADMIN_LISTEN: 0.0.0.0:8001
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_ADMIN_ERROR_LOG: /dev/stderr
ports:
- "8000:8000"
- "8001:8001"
healthcheck:
test: ["CMD", "kong", "health"]
interval: 10s
timeout: 10s
retries: 10
kong-gateway-2:
image: kong:latest
depends_on:
kong-database:
condition: service_healthy
kong-migration:
condition: service_completed_successfully
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_DATABASE: kong
KONG_PG_USER: kong
KONG_PG_PASSWORD: kong
KONG_ADMIN_LISTEN: 0.0.0.0:8001
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_ADMIN_ERROR_LOG: /dev/stderr
ports:
- "8080:8000"
- "8081:8001"
healthcheck:
test: ["CMD", "kong", "health"]
interval: 10s
timeout: 10s
retries: 10
volumes:
kong-database:Kubernetes部署
点击查看完整代码实现
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: kong-gateway
spec:
replicas: 3
selector:
matchLabels:
app: kong-gateway
template:
metadata:
labels:
app: kong-gateway
spec:
containers:
- name: kong
image: kong:latest
env:
- name: KONG_DATABASE
value: "postgres"
- name: KONG_PG_HOST
value: "postgres-service"
- name: KONG_PG_USER
value: "kong"
- name: KONG_PG_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
- name: KONG_ADMIN_LISTEN
value: "0.0.0.0:8001"
ports:
- containerPort: 8000
name: proxy
- containerPort: 8001
name: admin
resources:
requests:
memory: "256Mi"
cpu: "200m"
limits:
memory: "512Mi"
cpu: "500m"
readinessProbe:
httpGet:
path: /status
port: 8001
initialDelaySeconds: 30
periodSeconds: 10
livenessProbe:
httpGet:
path: /status
port: 8001
initialDelaySeconds: 60
periodSeconds: 30
---
apiVersion: v1
kind: Service
metadata:
name: kong-proxy-service
spec:
selector:
app: kong-gateway
ports:
- name: proxy
port: 80
targetPort: 8000
type: LoadBalancer
---
apiVersion: v1
kind: Service
metadata:
name: kong-admin-service
spec:
selector:
app: kong-gateway
ports:
- name: admin
port: 8001
targetPort: 8001
type: ClusterIP监控与运维
健康检查
bash
# Kong健康状态
curl http://localhost:8001/status
# 服务状态
curl http://localhost:8001/services/user-service/health
# 上游服务健康状态
curl http://localhost:8001/upstreams/user-upstream/health日志配置
bash
# 启用详细日志
export KONG_LOG_LEVEL=debug
export KONG_PROXY_ACCESS_LOG=/dev/stdout
export KONG_ADMIN_ACCESS_LOG=/dev/stdout
export KONG_PROXY_ERROR_LOG=/dev/stderr
export KONG_ADMIN_ERROR_LOG=/dev/stderr性能监控
bash
# Prometheus指标端点
curl http://localhost:8001/metrics
# 关键指标包括:
# - kong_http_requests_total
# - kong_latency_bucket
# - kong_bandwidth_bytes
# - kong_datastore_reachable最佳实践
性能优化
- 合理配置Nginx worker进程数
- 启用缓存减少数据库查询
- 使用连接池优化数据库连接
- 监控关键性能指标
安全配置
- 关闭不必要的Admin API端口
- 使用HTTPS和证书管理
- 配置适当的CORS策略
- 实施IP白名单和黑名单
高可用部署
- 部署多个Kong实例
- 使用负载均衡器分发流量
- 配置数据库主从复制
- 建立监控告警机制
运维管理
- 建立配置版本管理
- 实现插件的CI/CD流程
- 定期备份配置和数据
- 制定故障恢复计划
Kong凭借其高性能的Nginx内核、丰富的插件生态系统和灵活的部署方式,成为企业级API网关的优秀选择,特别适合对性能要求较高的微服务架构。
