完全教程

Higress — 云原生 AI 网关

基于 Envoy + Istio 的下一代 API 网关,统一 AI / MCP / Ingress / 微服务网关四大场景

01

什么是 Higress

定位:AI Native API Gateway

Higress 是阿里巴巴开源的云原生 API 网关,内核基于 IstioEnvoy,并以 Wasm 插件 作为主要的扩展机制(支持 Go / Rust / JS / C++)。

它脱胎于阿里内部两年多生产验证:解决 Tengine reload 对长连接业务有损、gRPC/Dubbo 负载均衡能力不足等问题,目前承载了通义千问 APP、通义百炼、PAI 等核心 AI 应用流量。

四个关键词

  • 生产等级:支撑每秒数十万级请求;配置变更毫秒级生效且无连接抖动,对 AI 长连接 / SSE 场景极友好。
  • 流式处理:真正完全流式处理请求 / 响应 Body,Wasm 插件天然支持 SSE。
  • 便于扩展:数十个开箱即用的官方插件(AI / 安全 / 流量管理),Wasm 沙箱隔离 + 热更新无损。
  • 安全易用:兼容 Ingress API / Gateway API,自带控制台,支持 Let's Encrypt 自动证书。
02

核心使用场景

1. AI 网关

用统一协议(OpenAI 兼容)对接国内外所有主流 LLM 厂商:DeepSeek、通义、Kimi、Claude、GPT、Gemini、Ollama / vllm 等;提供 token 限流、多模型负载均衡 / fallback、语义缓存、AI 可观测等能力。

2. MCP Server 托管

Higress 通过 Wasm 插件机制把 OpenAPI 转换并托管为远程 MCP Server,统一处理认证 / 鉴权 / 限流 / 观测,简化 AI Agent 调用工具的复杂度。配合 openapi-to-mcpserver 工具可以在几分钟内把现有 REST API 变成 MCP 工具。

3. Kubernetes Ingress 网关

替代 ingress-nginx:兼容大量 nginx-ingress 注解,资源开销大幅下降、路由变更生效速度提升约 10 倍;同时支持 Gateway API。

4. 微服务网关

对接 Nacos / ZooKeeper / Consul / Eureka 等注册中心,深度集成 Dubbo / Sentinel;C++ 内核性能远超传统 Java 类网关。

5. 安全防护网关

提供 WAF 能力,以及 key-auth / hmac-auth / jwt-auth / basic-auth / oidc 等多种认证鉴权策略。

03

与 Nginx Ingress / APISIX 对比

维度 Higress APISIX Nginx Ingress
数据面内核Envoy (C++)OpenResty (Lua)Nginx (C)
配置变更xDS 毫秒级、无抖动etcd watch 秒级reload 有抖动
插件语言Wasm: Go/Rust/JS/C++LuaLua / 几乎不可扩展
流式 Body原生支持有限支持有限支持
AI 能力开箱即用需自行集成
控制台自带 UIDashboard 独立项目
04

整体架构

Higress 由 三大核心组件 组成:

  ┌────────────────────────────────────────┐
  │      Higress Console (Web UI)          │  管理控制台
  └──────────────┬─────────────────────────┘
                 │  REST API
  ┌──────────────▼─────────────────────────┐
  │      Higress Controller (控制面)        │
  │  ┌───────────────┐ ┌─────────────────┐ │
  │  │  Higress Core │ │ Pilot-Discovery │ │
  │  │ (Ingress/CRD) │ │  (xDS 服务端)   │ │
  │  └───────────────┘ └─────────────────┘ │
  └──────────────┬─────────────────────────┘
                 │  xDS / gRPC
  ┌──────────────▼─────────────────────────┐
  │      Higress Gateway (数据面)          │
  │   Pilot-Agent ⇄ Envoy (+ Wasm Plugins) │
  └────────────────────────────────────────┘
  • Console:管理路由、服务、域名、证书、插件配置。
  • Controller:把 Ingress / Gateway API / Higress CRD 翻译为 Istio 配置,再下发为 Envoy xDS。
  • Gateway:Envoy 数据面,加载 Wasm 插件并代理流量。
05

Higress Controller

Controller 内部由两个子组件组成:

Discovery(基于 Istio Pilot-Discovery)

  • Config Controller:聚合多种配置来源(K8s CRD、Gateway API、MCP-over-xDS、内存、文件)。
  • Service Controller:从 K8s Service / Endpoint、外部注册中心采集服务实例。
  • 把所有信息合并为 xDS 数据结构(LDS / RDS / CDS / EDS / SDS),通过 gRPC 下发给 Envoy。

Higress Core(6 个控制器)

  • Ingress Controller:把 K8s Ingress 转 Istio Gateway / VirtualService / DestinationRule。
  • Gateway Controller:监听 Istio 原生资源。
  • McpBridge Controller:把 Nacos / Eureka / Consul / Zookeeper 等注册中心服务转 ServiceEntry。
  • Http2Rpc Controller:HTTP ⇄ RPC(Dubbo)协议转换。
  • WasmPlugin Controller:支持全局 / 域名 / 路由 / 服务 4 个粒度的插件配置。
  • ConfigmapMgr:监听 higress-config 全局配置,生成 EnvoyFilter。
06

Higress Gateway

数据面由 Pilot-Agent + Envoy 组成,Agent 通过 UDS 代理 Envoy 的 xDS 请求。

Envoy 核心概念

  • Listener:监听地址 / 端口,由 LDS 动态下发。
  • Route:路由规则(路径、Header、权重),由 RDS 下发。
  • Cluster:上游服务集合,由 CDS 下发。
  • Endpoint:集群内的具体实例,由 EDS 下发。
  • Wasm Filter:在 HTTP / Network filter chain 中加载 .wasm 字节码,实现自定义逻辑。
07

Higress Console

Console 是基于 Higress Admin SDK(Java 17+)实现的 Web UI,提供:

  • 路由 / 域名 / 证书 / 服务 / 插件 / 来源管理
  • 开箱即用的 Grafana + Prometheus 监控面板
  • 插件市场:可视化下发 Wasm 插件配置,热更新生效

Admin SDK 也可独立集成到企业自有控制台中。

08

Docker 单机部署

最快的体验方式(带 AI Gateway 能力的 all-in-one 镜像):

mkdir higress && cd higress

docker run -d --rm --name higress-ai -v ${PWD}:/data \
    -p 8001:8001 -p 8080:8080 -p 8443:8443 \
    higress-registry.cn-hangzhou.cr.aliyuncs.com/higress/all-in-one:latest

端口说明:

  • 8001:Higress Console 控制台
  • 8080:HTTP 网关入口
  • 8443:HTTPS 网关入口

访问 http://localhost:8001 设置初始账号密码后即可使用。配置文件持久化在当前目录。

海外用户可换镜像源:higress-registry.us-west-1.cr.aliyuncs.com(北美)或 higress-registry.ap-southeast-7.cr.aliyuncs.com(东南亚)。

09

K8s + Helm 部署

# 添加 Helm 仓库
helm repo add higress.io https://higress.cn/helm-charts
helm repo update

# 安装到 higress-system namespace
helm install higress -n higress-system higress.io/higress \
    --create-namespace \
    --set global.local=false \
    --set higress-console.service.type=LoadBalancer

关键 values 参数(来源 helm/core/values.yaml):

  • global.ingressClass:默认 higress;设为 nginx 可平滑接管 nginx-ingress 资源。
  • global.watchNamespace:限制 Controller 仅监听某个 namespace。
  • global.enableIstioAPI:是否同时监听 Istio 原生 CRD(默认 true)。
  • global.enableGatewayAPI:是否启用 Gateway API(默认 true)。
  • global.enableRedis:开启内置 Redis(限流、AI 缓存使用)。
  • global.hub:替换镜像仓库,建议按部署区域选择。
10

部署后验证

kubectl get pods -n higress-system
# 预期看到:
# higress-controller-xxx   2/2  Running
# higress-gateway-xxx      1/1  Running
# higress-console-xxx      1/1  Running

# 看 IngressClass
kubectl get ingressclass higress

# 端口转发体验控制台
kubectl port-forward -n higress-system svc/higress-console 8080:8080
11

Ingress 路由配置

样例来源 samples/quickstart.yaml,部署两个 echo 服务并按路径前缀路由:

apiVersion: v1
kind: Service
metadata: { name: foo-service }
spec:
  selector: { app: foo }
  ports: [{ port: 5678 }]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata: { name: foo }
spec:
  ingressClassName: higress
  rules:
  - http:
      paths:
      - pathType: Prefix
        path: /foo
        backend:
          service:
            name: foo-service
            port: { number: 5678 }
curl http://<GATEWAY_IP>/foo
# foo
curl http://<GATEWAY_IP>/bar
# bar
12

常用注解 Annotations

Higress 注解前缀使用 higress.io/,并兼容大量 nginx.ingress.kubernetes.io/ 注解:

metadata:
  annotations:
    # 路径重写
    higress.io/rewrite-target: /$2
    # 跨域
    higress.io/enable-cors: "true"
    higress.io/cors-allow-origin: "https://example.com"
    # 重定向
    higress.io/permanent-redirect: https://new.example.com$request_uri
    # 超时
    higress.io/proxy-connect-timeout: "5"
    higress.io/proxy-read-timeout: "60"
    # 请求 / 响应头
    higress.io/request-header-control-add: "X-Real-IP $remote_addr"
    # 灰度
    higress.io/canary: "true"
    higress.io/canary-weight: "20"
    higress.io/canary-by-header: "x-user-id"
13

域名与 TLS 证书

Higress 支持手动上传证书和 Let's Encrypt 自动签发。在 Console 中:

  1. 「域名管理」→ 添加域名 api.example.com → 启用 HTTPS。
  2. 「证书管理」→ 选择「自动签发」→ 选 ACME / Let's Encrypt。
  3. HTTPS 流量打到 8443,并可一键开启 HSTS、HTTP → HTTPS 重定向。

YAML 方式则通过 Secret 引用:

spec:
  tls:
  - hosts: [api.example.com]
    secretName: example-tls
  rules:
  - host: api.example.com
    http: { ... }
14

服务来源(McpBridge)

把外部注册中心服务接入网关。例:Nacos:

apiVersion: networking.higress.io/v1
kind: McpBridge
metadata:
  name: default
  namespace: higress-system
spec:
  registries:
  - name: my-nacos
    type: nacos2
    domain: nacos.example.com
    port: 8848
    nacosNamespaceId: public
    nacosGroups: [DEFAULT_GROUP]

之后 Ingress 的 backend.service.name 可写为 my-service.DEFAULT_GROUP.public.nacos 形式直接路由到 Nacos 中的实例。

15

Wasm 插件机制

Higress 采用 proxy-wasm 规范扩展 Envoy。一个 Wasm 插件就是一个 .wasm 字节码文件,被 Envoy 在 HTTP filter chain 中加载执行。

4 级生效粒度

  • 全局:所有请求都过
  • 域名:匹配特定 host
  • 路由:匹配特定 Ingress 路由
  • 服务:匹配特定 upstream

关键钩子

onHttpRequestHeaders    →  请求头到达
onHttpRequestBody       →  请求体(支持流式)
onHttpResponseHeaders   →  响应头返回
onHttpResponseBody      →  响应体(支持流式)
onTick / onQueueReady   →  定时器 / 跨实例通信

Wasm 沙箱隔离了内存与系统调用,插件升级不会断连

16

官方插件总览

位于 plugins/wasm-go/extensions/ 下的常用插件:

分类 插件
AIai-proxy ai-cache ai-token-ratelimit ai-statistics ai-rag ai-intent ai-history ai-prompt-decorator ai-prompt-template ai-security-guard ai-load-balancer ai-transformer ai-quota ai-search ai-json-resp ai-agent
认证basic-auth key-auth jwt-auth hmac-auth-apisix oidc ext-auth
流量cluster-key-rate-limit cors cache-control custom-response frontend-gray geo-ip
安全bot-detect ip-restriction waf
协议转换de-graphql jsonrpc-converter
MCPmcp-router mcp-server(OpenAPI→MCP)
其他log-request-response http-call hello-world
17

开发第一个 Go 插件

来源 plugins/wasm-go/extensions/hello-world/main.go,只需 30 行代码:

package main

import (
    "net/http"

    "github.com/higress-group/proxy-wasm-go-sdk/proxywasm"
    "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types"
    "github.com/higress-group/wasm-go/pkg/log"
    "github.com/higress-group/wasm-go/pkg/wrapper"
)

func main() {}

func init() {
    wrapper.SetCtx(
        "hello-world",
        wrapper.ProcessRequestHeadersBy(onHttpRequestHeaders),
    )
}

type HelloWorldConfig struct{}

func onHttpRequestHeaders(ctx wrapper.HttpContext, config HelloWorldConfig, log log.Log) types.Action {
    _ = proxywasm.AddHttpRequestHeader("hello", "world")
    proxywasm.SendHttpResponseWithDetail(http.StatusOK, "hello-world", nil, []byte("hello world"), -1)
    return types.ActionContinue
}

解析:

  • wrapper.SetCtx:声明插件名 + 注册钩子。
  • HelloWorldConfig:插件配置结构体,控制台填的 YAML 会被自动反序列化进来。
  • proxywasm.SendHttpResponseWithDetail:直接由网关返回响应,不再透传给上游。
18

插件构建与发布

# 编译 wasm(需要 TinyGo)
tinygo build -o main.wasm -scheduler=none -target=wasi ./main.go

# 打成 OCI 镜像(Higress 直接从镜像仓库拉取)
docker buildx build \
    --platform wasi/wasm \
    -t docker.io/yourname/hello-world:v1 \
    --push .

在控制台「插件市场」→ 输入镜像地址 → 选择生效范围(全局/域名/路由/服务)→ 填 YAML 配置 → 保存即可热生效。

# 对应的 WasmPlugin CR
apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata:
  name: hello-world
  namespace: higress-system
spec:
  priority: 100
  url: oci://docker.io/yourname/hello-world:v1
  defaultConfig: {}
19

ai-proxy 多模型代理

ai-proxy 是 Higress AI 网关的核心:把任意 LLM 厂商接口统一适配为 OpenAI 协议。下面让所有走 /v1/chat/completions 的请求转发到 DeepSeek:

apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata:
  name: ai-proxy-deepseek
  namespace: higress-system
spec:
  defaultConfig:
    provider:
      type: deepseek
      apiTokens:
        - sk-xxxxxxxxxxxxxxxx
      modelMapping:
        gpt-4: deepseek-chat
        gpt-3.5-turbo: deepseek-chat
  matchRules:
    - domain: ["api.example.com"]
      config: {}

调用方依然用 OpenAI SDK,无需任何代码改造:

curl https://api.example.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}'

支持的 provider 见 plugins/wasm-go/extensions/ai-proxy/provider/,包括 openai / azure / deepseek / qwen / moonshot / baichuan / minimax / claude / gemini / ollama / vllm 等数十种。

20

Token 流控与配额

ai-token-ratelimit 按 token 数(而不是 QPS)限流,更贴合 LLM 计费模型;ai-quota 提供按 consumer / API key 的额度管理:

apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata:
  name: ai-token-ratelimit
spec:
  defaultConfig:
    rule_name: per-user-token-limit
    rule_items:
      - limit_by_header: x-user-id
        limit_keys:
          - key: default
            token_per_minute: 10000
    redis:
      service_name: redis.higress-system.svc.cluster.local
      service_port: 6379
21

AI 缓存(语义缓存)

ai-cache 支持:

  • 精确匹配:相同 prompt 直接返回缓存
  • 语义匹配:通过 Embedding + 向量库判断相似度,命中即返回缓存(大幅降低 token 成本与延迟)
defaultConfig:
  embeddingProvider:
    type: dashscope
    apiKey: sk-xxxx
  vectorBaseProvider:
    type: dashvector
    apiKey: vk-xxxx
    collectionID: ai_cache
  cacheKeyFrom:
    requestBody: "messages.@reverse.0.content"
  similarityThreshold: 0.85
22

RAG 与意图识别

ai-rag 在 LLM 调用前自动检索知识库并把片段注入 prompt;ai-intent 先做一层小模型意图分类,把请求分流到不同 LLM 或拒绝。两者组合可以快速搭出企业知识助手。

# ai-rag 关键配置
defaultConfig:
  dense:
    provider:
      type: dashscope
      serviceName: dashscope.dns
      apiKey: sk-xxx
      embeddingModel: text-embedding-v2
  vector:
    provider:
      type: dashvector
      apiKey: vk-xxx
      collection: kb_docs
      threshold: 0.5
      topK: 5
  promptTemplate: |-
    # 知识库
    {context}
    # 问题
    {question}
23

MCP Server 托管

把已有 OpenAPI 转换为 MCP Server,让 AI Agent 直接调用:

# 1. 用工具把 swagger.yaml 转 MCP 配置
openapi-to-mcpserver -i swagger.yaml -o mcp.yaml

# 2. 通过 ConfigMap 下发 mcpServer 配置
kubectl create cm higress-config -n higress-system \
    --from-file=mcp.yaml --dry-run=client -o yaml | kubectl apply -f -

启用后,AI Agent 通过 SSE 连接 https://<gateway>/mcp/<server-name>/sse 就能枚举 / 调用所有工具,认证 / 限流 / 审计统一由网关接管。

体验官方平台:https://mcp.higress.ai/

24

案例:灰度发布

把 20% 流量切到 v2,并允许带 x-user-id: beta 的请求走 v2:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-v1
  annotations: { higress.io/destination: "app-v1.dns 100%" }
spec:
  ingressClassName: higress
  rules: [{ http: { paths: [{ pathType: Prefix, path: /, backend: { service: { name: app-v1, port: { number: 80 }}}}]}}]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-v2
  annotations:
    higress.io/canary: "true"
    higress.io/canary-weight: "20"
    higress.io/canary-by-header: "x-user-id"
    higress.io/canary-by-header-value: "beta"
spec:
  ingressClassName: higress
  rules: [{ http: { paths: [{ pathType: Prefix, path: /, backend: { service: { name: app-v2, port: { number: 80 }}}}]}}]
25

案例:JWT 鉴权

apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata: { name: jwt-auth, namespace: higress-system }
spec:
  defaultConfig:
    global_auth: false
    consumers:
      - name: app-a
        issuer: app-a-issuer
        jwks: |
          { "keys": [{"kty":"RSA","n":"...","e":"AQAB","kid":"app-a"}] }
        from_headers: [{ name: Authorization, value_prefix: "Bearer " }]
  matchRules:
    - ingress: ["default/my-api"]
      config:
        allow: [app-a]

未携带合法 JWT 的请求会被网关直接拒绝(401),不会消耗上游资源。

26

案例:限流防护

按 IP 维度全局 100 QPS,并对登录接口单独限制 10 QPS:

apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata: { name: cluster-rl, namespace: higress-system }
spec:
  defaultConfig:
    rule_name: ip-global
    rule_items:
      - limit_by_header: x-forwarded-for
        limit_keys:
          - { key: default, query_per_second: 100 }
    redis:
      service_name: redis.higress-system.svc.cluster.local
  matchRules:
    - ingress: ["default/login"]
      config:
        rule_name: login-strict
        rule_items:
          - limit_by_header: x-forwarded-for
            limit_keys: [{ key: default, query_per_second: 10 }]
27

可观测性

Metrics

Envoy 暴露的 Prometheus 指标包含每路由 / 集群的 QPS / 延迟 / 状态码分布;Higress 在控制台直接内嵌了 Grafana 面板,也可对接自建 Prometheus。

Tracing

通过 higress-config 配置 OpenTelemetry / SkyWalking / Zipkin sampler 与 collector 地址,即可生成完整调用链。

Access Log

data:
  mesh: |-
    accessLogEncoding: JSON
    accessLogFormat: |
      {"start_time":"%START_TIME%","route":"%REQ(:PATH)%","status":%RESPONSE_CODE%,
       "duration_ms":%DURATION%,"upstream":"%UPSTREAM_HOST%",
       "user":"%REQ(X-USER-ID)%"}

AI 专属指标

ai-statistics 插件输出每模型 / 每用户的 input_tokens / output_tokens / TTFT / 总耗时,是 LLM 成本治理的核心数据源。

28

hgctl 命令行工具

仓库 hgctl/ 提供官方 CLI,类比 istioctl

hgctl install                  # 安装 Higress 到 K8s
hgctl uninstall                # 卸载
hgctl profile dump             # 查看当前安装 profile
hgctl plugin ls                # 列出已加载 Wasm 插件
hgctl plugin install foo.wasm  # 加载本地 Wasm
hgctl dashboard console        # 打开控制台
29

常见问题排查

  • 路由不生效:检查 ingressClassName: higress 是否正确;kubectl logs deploy/higress-controller -n higress-system -c discovery 看 xDS 推送日志。
  • 503 no_healthy_upstream:上游 Service 的 selector / Endpoint 为空;或健康检查失败。
  • Wasm 插件报错:在 Envoy 日志里搜 wasm log,定位插件名称;本地用 tinygo test 跑单测。
  • AI 流式响应被截断:检查 proxy-read-timeout 是否过小,AI 长响应建议 ≥ 600s;并确认未启用 response-body 缓冲类插件。
  • 证书自动签发失败:80 端口需对公网开放,否则 ACME HTTP-01 校验过不去。
30

总结与资源

一句话总结

Higress = Envoy 数据面 + Istio 控制面 + Wasm 插件生态 + AI / MCP 原生能力,覆盖 K8s Ingress、微服务网关、AI 网关、MCP 网关、安全网关五大形态。

推荐学习路径

  1. Docker all-in-one 跑通最简 Ingress 路由(30 分钟)。
  2. docs/architecture.md,理解 Controller → xDS → Envoy 链路。
  3. ai-proxy 接一个 DeepSeek,再叠加 ai-cache + ai-token-ratelimit
  4. 仿照 hello-world 写一个 Go Wasm 插件并热加载。
  5. 把一个 OpenAPI 通过 openapi-to-mcpserver 转成 MCP Server 接入 Claude / Cursor。

官方资源