Knative Serving 多服务路径路由实战:基于 Istio VirtualService 的 Go 示例深度解析
Knative Serving 多服务路径路由实战:基于 Istio VirtualService 的 Go 示例深度解析
本文以 Knative 官方文档仓库中的 knative-routing-go 示例为核心,完整讲解如何借助 Istio VirtualService 将多个 Knative Service 映射到同一域名下的不同路径(如 example.com/search、example.com/login),并深入解读 Host 头重写的工作机制、cluster-local 内部服务的进阶用法,以及与 http-protocol: Redirected、auto-tls 特性的协同配置。读完本文,你将掌握一套可复制、可验证的多服务入口聚合方案,并能按需将路由规则扩展为基于 Header 等其他请求数据的灵活路由。
示例全景:两个服务共享一个域名
在生产实践中,一个域名下往往要承载多个功能模块。Knative Serving 默认会给每个 Service 生成独立的域名(如 search-service.default.example.com),但通过 Istio VirtualService,我们可以把所有服务聚合到同一个域名下的不同路径上。
本示例在 default 命名空间下部署两个极简的 Web 服务:
search-service:读取环境变量SERVICE_NAME,收到请求后返回Search Service is called !login-service:读取环境变量SERVICE_NAME,收到请求后返回Login Service is called !
随后创建一个 host 为 example.com 的 VirtualService,定义两条路由规则:
| 外部请求 URI | 目标 Knative 服务 |
|---|---|
example.com/search |
search-service |
example.com/login |
login-service |
Istio 本身是通用反向代理,因此这套思路不仅限于路径路由,还可以扩展为按 Header 等其他请求数据路由,甚至把 Knative 服务与集群外部资源映射到同一个域名下。示例的完整代码与清单文件位于仓库的 code-samples/serving/knative-routing-go 目录。
示例应用源码解读:SERVICE_NAME 驱动的 Go 服务
两个服务的业务逻辑完全一致,唯一区别是 SERVICE_NAME 环境变量的取值。核心实现见 sample.go:
func handler(w http.ResponseWriter, r *http.Request) {
serviceName := os.Getenv("SERVICE_NAME")
if serviceName == "" {
serviceName = "NOT SPECIFIED"
}
log.Printf("%s received a request.", serviceName)
fmt.Fprintf(w, "%s is called !\n", serviceName)
}
func main() {
flag.Parse()
log.Print("Sample started.")
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
几个值得注意的实现细节:
- 服务监听
:8080,这是 Knative Serving 容器约定的默认端口,Knative 会自动把入站流量代理到该端口。 handler通过os.Getenv("SERVICE_NAME")读取服务身份,未设置时回退为NOT SPECIFIED,保证即使配置缺失也能正常响应。- 每收到一个请求都会通过
log.Printf输出一行日志,便于在 Knative Serving 的日志管道中观察流量走向。
SERVICE_NAME 的取值在 sample.yaml 中通过 env 注入:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: search-service
namespace: default
spec:
template:
spec:
containers:
- image: github.com/knative/docs/code-samples/serving/knative-routing-go
env:
- name: SERVICE_NAME
value: Search Service
readinessProbe:
httpGet:
path: /
initialDelaySeconds: 3
---
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: login-service
namespace: default
spec:
template:
spec:
containers:
- image: github.com/knative/docs/code-samples/serving/knative-routing-go
env:
- name: SERVICE_NAME
value: Login Service
readinessProbe:
httpGet:
path: /
initialDelaySeconds: 3
清单中的 image 字段默认填写的是 Go 导入路径(源码注释明确说明这是"the Go import path for the binary to containerize"),实际部署前需要替换为你自己的镜像仓库地址。每个 Service 都配置了基于 httpGet 的 readinessProbe(路径 /,延迟 3 秒启动探测),保证流量只进入就绪的 Revision。
前置条件
开始之前,请确认以下环境就绪:
- 一个已安装 Knative Serving 的 Kubernetes 集群,且网络层为 Istio(本示例依赖 Istio 的 Gateway 与 VirtualService 资源)。Knative 的
net-istio控制器会把 Knative 的 KIngress 资源映射为 Istio VirtualService,其架构细节可参考仓库文档 config-network-adapters.md。 - Docker:用于本地构建并推送示例镜像,构建命令使用
docker buildx完成多架构(linux/arm64、linux/amd64)推送。 - 一个域名:本文统一使用
example.com。若没有真实域名,可以在 Mac 或 Linux 的 hosts 文件中把example.com映射到集群的 ingress IP;如果已为 Knative 配置了自定义域名,后续步骤中统称<YOUR_DOMAIN_NAME>。 - 获取示例代码:示例位于当前仓库的
code-samples/serving/knative-routing-go/目录,包含 sample.go、sample.yaml、routing.yaml、routing-internal.yaml、Dockerfile 等文件,可直接以该目录为工作区使用。
环境准备:确认域名与构建镜像
检查 Knative 域名配置
先确认集群的域名配置是否符合预期:
kubectl get cm -n knative-serving config-domain -o yaml
检查 data 字段下的键值对,若看到 <YOUR_DOMAIN_NAME>: "" 格式的条目(空值表示默认域名后缀),说明配置可用。示例中默认假定 Knative 服务的域名格式为 search-service.default.example.com。
构建并推送应用镜像
- 进入示例目录(以本地 checkout 的仓库根目录为准):
cd code-samples/serving/knative-routing-go
- 设置镜像仓库。使用 Google Container Registry(GCR)时,需要在 GCP 项目中启用 GCR API,然后:
export REPO="gcr.io/<YOUR_PROJECT_ID>"
使用 Docker Hub 时,将 <username> 替换为你的 Docker Hub 用户名:
export REPO="docker.io/<username>"
- 使用 Docker 构建并推送多架构镜像(命令在仓库根目录执行):
docker buildx build --platform linux/arm64,linux/amd64 -t "${REPO}/knative-routing-go" --push . -f code-samples/serving/knative-routing-go/Dockerfile
Dockerfile 采用两阶段构建:第一阶段基于 golang:latest 执行 go mod tidy 并以 CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} 静态编译出二进制(TARGETOS/TARGETARCH 由 buildx --platform 自动注入,go.mod 中声明 Go 1.22);第二阶段基于 gcr.io/distroless/base 运行产物,仅暴露 8080 端口,镜像体积更小、更安全。
- 把 sample.yaml 中的镜像引用替换为已推送的镜像路径。可以手动把:
image: github.com/knative/docs/code-samples/serving/knative-routing-go
替换为:
image: ${REPO}/knative-routing-go
(若手动修改,需把 ${REPO} 换成实际仓库地址。)
或者直接执行一键替换命令:
perl -pi -e "s@github.com/knative/docs/code-samples/serving@${REPO}@g" code-samples/serving/knative-routing-go/sample.yaml
部署两个 Knative 服务
部署清单:
kubectl apply --filename code-samples/serving/knative-routing-go/sample.yaml
然后检查部署结果:
kubectl get ksvc
正常情况下应看到两个 Knative Service:search-service 与 login-service,状态均为 READY=True。
默认访问方式:通过 Host 头直达
部署完成后,Knative 会为每个 Service 生成独立的域名 URL,外部流量统一由共享 Gateway 接入。
认识共享 Gateway
Knative service mesh 使用一个名为 knative-ingress-gateway 的共享 Istio Gateway 承载所有入站流量,底层指向 istio-system 命名空间下的 istio-ingressgateway Kubernetes Service(详见 config-network-adapters.md 中 Istio 一节)。
- 查看共享 Gateway:
kubectl get Gateway --namespace knative-serving --output yaml
- 查看共享 Gateway 对应的 Kubernetes Service:
INGRESSGATEWAY=istio-ingressgateway
kubectl get svc $INGRESSGATEWAY --namespace istio-system --output yaml
通过 Host 头直连服务
- 获取共享 Gateway 的 IP 并导出为环境变量:
INGRESSGATEWAY=istio-ingressgateway
export GATEWAY_IP=`kubectl get svc $INGRESSGATEWAY --namespace istio-system \
--output jsonpath="{.status.loadBalancer.ingress[*]['ip']}"`
- 查看
Search服务的 URL:
kubectl get route search-service --output=custom-columns=NAME:.metadata.name,URL:.status.url
输出形如:
NAME URL
search-service http://search-service.default.example.com
- 携带
Host头发起请求:
curl http://${GATEWAY_IP} --header "Host:search-service.default.example.com"
应看到:Search Service is called !
- 同样方式访问
Login服务:
curl http://${GATEWAY_IP} --header "Host:login-service.default.example.com"
应看到:Login Service is called !
这种通过 Host 头区分服务的方式是 Knative 默认的路由模型,但要求客户端记住每个服务的完整域名。下面的自定义路由则把多个服务统一收敛到 example.com/search、example.com/login 两个入口上。
自定义路由:entry-route VirtualService 逐字段剖析
应用自定义路由规则
kubectl apply --filename code-samples/serving/knative-routing-go/routing.yaml
该清单会生成一个新的 VirtualService entry-route。完整内容见 routing.yaml,核心结构如下:
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: entry-route
namespace: default
spec:
# 复用 Knative service mesh 中的共享网关。
gateways:
- knative-ingress-gateway.knative-serving.svc.cluster.local
# 设为你的域名。
hosts:
- example.com
http:
- match:
- uri:
prefix: "/search"
rewrite:
# 把原始 Host 头改写为 Search 服务的 Host 头,
# 从而把请求重定向到 Search 服务。
authority: search-service.default.example.com
route:
# 将请求重新送回集群入口,但携带更新后的 Host 头,
# 请求最终会被引导到 Search 服务。
- destination:
host: istio-ingressgateway.istio-system.svc.cluster.local
port:
number: 80
weight: 100
- match:
- uri:
prefix: "/login"
rewrite:
# 改写为 Login 服务的 Host 头。
authority: login-service.default.example.com
route:
# 将请求送回集群入口,最终引导到 Login 服务。
- destination:
host: istio-ingressgateway.istio-system.svc.cluster.local
port:
number: 80
weight: 100
逐字段说明:
gateways:绑定到 Knative 共享网关knative-ingress-gateway.knative-serving.svc.cluster.local,使规则对进入该网关的外部流量生效。hosts:声明该 VirtualService 负责的域名,即example.com。http[].match[].uri.prefix:按 URI 前缀匹配,/search与/login分别命中两条规则。http[].rewrite.authority:核心的 Host 重写字段。将原始请求的 Host(example.com)改写为目标 Knative 服务的域名(如search-service.default.example.com),从而重置请求的最终目的地。http[].route[].destination:把改写后的请求送回istio-ingressgateway.istio-system.svc.cluster.local:80(端口 80、权重 100),即再次进入集群入口,由 Gateway 依据更新后的 Host 头转发到对应服务。
适配 domain-template 与自定义域名
如果你的服务使用了自定义域名,需要把 routing.yaml 中所有 example.com(包括 spec.hosts 与 spec.http.rewrite.authority)替换为 <YOUR_DOMAIN_NAME>。
此外,还必须核对集群的域名模板格式。Knative 默认使用 {{.Name}}.{{.Namespace}} 格式,即 search-service.default;但某些 Knative 环境可能使用 {{.Name}}-{{.Namespace}} 等其他格式。执行:
kubectl get cm -n knative-serving config-network -o yaml
查看 domain-template 字段。若值为 {{.Name}}-{{.Namespace}}.{{.Domain}},则还需把 routing.yaml 中的 search-service.default 改为 search-service-default、login-service.default 改为 login-service-default。
查看生成的 VirtualService
kubectl get VirtualService entry-route --output yaml
确认路由规则已正确创建。
验证自定义路由
重新获取 ingress IP:
INGRESSGATEWAY=istio-ingressgateway
export GATEWAY_IP=`kubectl get svc $INGRESSGATEWAY --namespace istio-system \
--output jsonpath="{.status.loadBalancer.ingress[*]['ip']}"`
- 请求
Search服务:
curl http://${GATEWAY_IP}/search --header "Host: example.com"
使用自定义域名时:
curl http://${GATEWAY_IP}/search --header "Host: <YOUR_DOMAIN_NAME>"
- 请求
Login服务:
curl http://${GATEWAY_IP}/login --header "Host: example.com"
或:
curl http://${GATEWAY_IP}/login --header "Host: <YOUR_DOMAIN_NAME>"
两种请求返回的结果,应与上一节通过完整域名直接访问两个服务时完全一致。
工作原理:Host 重写与二次入站
整个转发链路可以概括为以下三步:
- 首次入站:外部请求以
example.com为 Host、以/search或/login为 URI 到达knative-ingress-gateway网关。此时由entry-routeVirtualService 接管,检查 URI 前缀是否命中路由规则。 - Host 重写:若命中,
rewrite.authority会把请求的 Host 改写为对应 Knative 服务的域名(search-service.default.example.com或login-service.default.example.com),从而重置请求的最终目的地。 - 二次入站:改写后的请求被送回
istio-ingressgateway(即集群入口),Gateway 代理依据更新后的 Host 头,按照 Knative 自身的路由逻辑转发给对应的Search或Login服务。
值得注意的是,entry-route 本质上是把流量"绕"回入口做二次转发,这与 Knative 默认基于 Host 的路由模型自然衔接,无需修改任何 Knative 内部配置。这也意味着同样的 VirtualService 手法可以推广到基于 Header 等请求数据的路由,甚至可以把 Knative 服务和集群外部资源映射到同一域名之下。
进阶实践:cluster-local 化服务并配合 http-protocol: Redirected
问题:服务出现了两个入口
采用上述方案后,每个服务都会暴露两个集群入口:
- Knative Serving 原生提供的入口:
search-service.default.example.com、login-service.default.example.com; - 手动创建的 VirtualService(
entry-route)新增的入口:example.com/search、example.com/login。
如果希望服务只能通过手动创建的 VirtualService 访问,就需要把服务标记为 cluster-local,并改用内部网关转发。
步骤一:把服务标记为 cluster-local
kubectl label kservice search-service login-service networking.knative.dev/visibility=cluster-local
添加 networking.knative.dev/visibility: cluster-local 标签后,服务不再发布到外部网关,search-service.default.example.com 与 login-service.default.example.com 这两个外部入口随即失效(关于 cluster-local 标签的详细说明可参考仓库文档 private-services.md)。此时,之前基于外部网关的 routing.yaml 路由将不再可达。
步骤二:改用内部网关的路由
kubectl apply --filename code-samples/serving/knative-routing-go/routing-internal.yaml
routing-internal.yaml 与 routing.yaml 结构相同,但有两点关键差异:
rewrite.authority由外部域名(search-service.default.example.com)改为集群内部 DNS 名(search-service.default.svc.cluster.local);route[].destination.host由公共入口istio-ingressgateway.istio-system.svc.cluster.local改为内部网关knative-local-gateway.istio-system.svc.cluster.local(端口 80、权重 100)。
这样一来,流量经由内部网关在集群内闭环转发,example.com/search 与 example.com/login 恢复可用,且服务不再暴露外部直连入口。
步骤三:与 auto-tls 和 http-protocol: Redirected 协同
在完成上述改造后,还可以叠加 Knative 的 auto-tls 特性与全局设置 "http-protocol": "Redirected":
http-protocol的取值与行为在仓库文档 http-protocol.md 中有完整定义:enabled(默认,接受 HTTP 流量)与redirected(对所有 HTTP 连接返回 301 重定向,要求客户端改用 HTTPS)。若保持默认的enabled,Knative 会尝试把entry-routeVirtualService 的请求从 HTTP 301 重定向到 HTTPS,导致路由请求失败;改用内部网关方案后即可规避该问题。- auto-tls 的启用方式(
external-domain-tls等配置)详见仓库文档 external-domain-tls.md。
即在 cluster-local + 内部网关的基础上,再配合 http-protocol: Redirected 与 auto-tls,就能在只暴露聚合入口的前提下为服务启用 HTTPS 强制跳转与自动证书。
清理与注意事项
删除示例资源:
kubectl delete --filename code-samples/serving/knative-routing-go/sample.yaml
kubectl delete --filename code-samples/serving/knative-routing-go/routing.yaml
若应用过内部路由方案,还需一并清理:
kubectl delete --filename code-samples/serving/knative-routing-go/routing-internal.yaml
最后提醒三点实操注意事项:
- 域名模板务必核对:
domain-template的格式决定了rewrite.authority中服务名的写法(search-service.default还是search-service-default),不匹配会导致路由失效。 - 镜像引用替换不可遗漏:直接 apply 未替换镜像路径的
sample.yaml会因镜像不存在而无法就绪。 - 自定义域名需全量替换:使用真实域名时,
routing.yaml中hosts与rewrite.authority里的example.com都要替换为<YOUR_DOMAIN_NAME>。
