Kubernetes: 08-gateway-api
- TAGS: Kubernetes
安装
博文参考:Gateway-API-Setup
- 安装 Gateway API CRD
- Gateway API 的下游实现
- 安装 nginx gateway crd
- 安装 nginx-gateway-fabric
- Gatewayclass
- 创建 gateway
- 部署应用
- 使用 httproute 访问
ingress to gateway 转换工具
方案1:Ingress(2026.3 不维护)
- 创建ingress-controller,创建ingress-entrance: https://kubernetes.github.io/ingress-nginx/
方案2:gateway 之 NGINX Gateway Fabric
安装 Gateway API CRD
- 安装 Gateway API CRD
# 安装标准版 gateway api CRD GATEWAYAPI_VERSION=1.6.3 kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v${GATEWAYAPI_VERSION}/standard-install.yaml #kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/standard-install.yaml # 范例 root@ip-172-31-18-198:/docker/nginx/data/site.d# kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/standard-install.yaml customresourcedefinition.apiextensions.k8s.io/backendtlspolicies.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/gatewayclasses.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/gateways.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/grpcroutes.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/httproutes.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/listenersets.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/referencegrants.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/tcproutes.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/tlsroutes.gateway.networking.k8s.io serverside-applied customresourcedefinition.apiextensions.k8s.io/udproutes.gateway.networking.k8s.io serverside-applied validatingadmissionpolicy.admissionregistration.k8s.io/safe-upgrades.gateway.networking.k8s.io serverside-applied validatingadmissionpolicybinding.admissionregistration.k8s.io/safe-upgrades.gateway.networking.k8s.io serverside-applied root@ip-172-31-18-198:~# kubectl get crd |grep gateway.networking.k8s.io backendtlspolicies.gateway.networking.k8s.io 2026-08-26T09:10:31Z gatewayclasses.gateway.networking.k8s.io 2026-08-26T09:10:31Z gateways.gateway.networking.k8s.io 2026-08-26T09:10:31Z grpcroutes.gateway.networking.k8s.io 2026-08-26T09:10:31Z httproutes.gateway.networking.k8s.io 2026-08-26T09:10:31Z listenersets.gateway.networking.k8s.io 2026-08-26T09:10:32Z referencegrants.gateway.networking.k8s.io 2026-08-26T09:10:32Z tcproutes.gateway.networking.k8s.io 2026-08-26T09:10:32Z tlsroutes.gateway.networking.k8s.io 2026-08-26T09:10:33Z udproutes.gateway.networking.k8s.io 2026-08-26T09:10:33Z
安装 nginx gateway crd
# 安装 NGINX Gateway Fabric CRDs NGINXGAPI_VERSION=2.8.1 # https://github.com/nginx/nginx-gateway-fabric/tree/v2.6.7/deploy kubectl apply --server-side -f https://raw.githubusercontent.com/nginx/nginx-gateway-fabric/refs/tags/v${NGINXGAPI_VERSION}/deploy/crds.yaml # 普通 kubectl apply 是客户端 apply:本地保存一份注解 kubectl.kubernetes.io/last-applied-configuration,用来对比变更。 # --server‑side 是把合并逻辑交给 **k8s APIServer 服务端处理**,不在客户端存大段 last‑applied 注解。 # 范例 root@ip-172-31-18-198:~# kubectl apply --server-side -f https://raw.githubusercontent.com/nginx/nginx-gateway-fabric/refs/tags/v2.6.7/deploy/crds.yaml customresourcedefinition.apiextensions.k8s.io/authenticationfilters.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/clientsettingspolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/nginxgateways.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/nginxproxies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/observabilitypolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/proxysettingspolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/ratelimitpolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/snippetsfilters.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/snippetspolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/upstreamsettingspolicies.gateway.nginx.org serverside-applied customresourcedefinition.apiextensions.k8s.io/wafpolicies.gateway.nginx.org serverside-applied root@ip-172-31-18-198:~# kubectl get crd |grep nginx authenticationfilters.gateway.nginx.org 2026-08-26T09:37:50Z clientsettingspolicies.gateway.nginx.org 2026-08-26T09:37:50Z nginxgateways.gateway.nginx.org 2026-08-26T09:37:50Z nginxproxies.gateway.nginx.org 2026-08-26T09:37:50Z observabilitypolicies.gateway.nginx.org 2026-08-26T09:37:50Z # 可观测规则 proxysettingspolicies.gateway.nginx.org 2026-08-26T09:37:51Z # 代理设置规则 ratelimitpolicies.gateway.nginx.org 2026-08-26T09:37:51Z # 限速规则 snippetsfilters.gateway.nginx.org 2026-08-26T09:37:51Z snippetspolicies.gateway.nginx.org 2026-08-26T09:37:51Z upstreamsettingspolicies.gateway.nginx.org 2026-08-26T09:37:51Z wafpolicies.gateway.nginx.org 2026-08-26T09:37:51Z # 应用防火墙规则
安装 nginx-gateway-fabric
# mkdir ngfdir cd ngfdir/ # 下载 2.6.7 版本文件。拉取 OCI 格式 Helm chart,解压到本地 helm pull oci://ghcr.io/nginx/charts/nginx-gateway-fabric --version 2.8.1 --untar cd nginx-gateway-fabric/ helm install ngf . \ --create-namespace -n nginx-gateway \ --set nginx.service.type=LoadBalancer \ --set nginx.service.externalTrafficPolicy=Cluster \ --set nginxGateway.snippetsFilters.enable=true # --set nginx.service.type=LoadBalancer 使用负载均衡器。会自动分配公网 LB # --set nginx.service.externalTrafficPolicy=Cluster 外部流量转发策略。 # Cluster(这里配置的):源 IP 会被 SNAT 改写为节点 IP;可以做负载均衡跨节点转发。 # Local:保留真实客户端源 IP,但流量只能落到后端 Pod 所在节点。 # --set nginxGateway.snippets.enable=true NGF 的扩展能力,可以在 Gateway API 资源中嵌入原生 Nginx 配置片段(nginx.conf 片段)。同时启用 SnippetsFilter 和 SnippetsPolicy。 #或者将配置写到 value 文件中 cat <<EOF> values-dev.yaml # NGF 的扩展能力 nginxGateway: snippets: enable: true # nginxproxy 配置 nginx: replicas: 1 # 默认 1 个 service: type: LoadBalancer externalTrafficPolicy: Cluster EOF root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get ns |grep gateway nginx-gateway Active 16m root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get pods -n nginx-gateway NAME READY STATUS RESTARTS AGE ngf-nginx-gateway-fabric-746f6d68fc-hspmf 1/1 Running 0 85s root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get svc -n nginx-gateway NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ngf-nginx-gateway-fabric ClusterIP 10.210.167.53 <none> 443/TCP 2m7s # 查看 snippets 扩展是否开启 kubectl -n nginx-gateway get deploy ngf-nginx-gateway-fabric -oyaml spec: automountServiceAccountToken: true containers: - args: ... 略 - --snippets # 卸载 # helm uninstall ngf -n nginx-gateway # kubectl delete ns nginx-gateway --ignore-not-found
Gatewayclass
- 部署完后得到名为 nginx 的 gatewayclass
# 控制器 nginx root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get gatewayclasses -n nginx-gateway NAME CONTROLLER ACCEPTED AGE nginx gateway.nginx.org/nginx-gateway-controller True 2m55s
生成 ngixnxporxy
nginxproxy 比较重要。生产 service 定制全局日志都靠它。
# nginxproxy 相当于 configmap root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get nginxproxy -n nginx-gateway NAME AGE ngf-proxy-config 4m33s root@ip-172-31-18-198:~/.jasper/ngfdir/nginx-gateway-fabric# kubectl get nginxproxies -n nginx-gateway -oyaml apiVersion: v1 items: - apiVersion: gateway.nginx.org/v1alpha2 kind: NginxProxy metadata: labels: app.kubernetes.io/instance: ngf app.kubernetes.io/managed-by: Helm app.kubernetes.io/name: nginx-gateway-fabric app.kubernetes.io/version: 2.6.7 helm.sh/chart: nginx-gateway-fabric-2.6.7 name: ngf-proxy-config namespace: nginx-gateway spec: ipFamily: dual kubernetes: deployment: container: image: pullPolicy: IfNotPresent repository: ghcr.io/nginx/nginx-gateway-fabric/nginx tag: 2.6.7 replicas: 1 # helm 自定义参数 service: externalTrafficPolicy: Cluster type: LoadBalancer kind: List metadata: resourceVersion: "" # helm 设置的参数 # --set nginx.service.type=LoadBalancer \ # --set nginx.service.externalTrafficPolicy=Cluster \
创建 gateway
实际上 gateway 是 pod + service 的组合。
cat <<\EOF>> 01-gateway-test.yaml apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: nginx-gateway-test namespace: default spec: gatewayClassName: nginx listeners: - name: http protocol: HTTP port: 80 allowedRoutes: namespaces: from: All # 允许所有namespace的HTTPRoute绑定这个Gateway。默认为允许当前名称空间的规则 EOF # kubectl apply -f 01-gateway-test.yaml # gateway 的地址就是 service 的地址 root@ip-172-31-18-198:~/.jasper/ngfdir# kubectl get gateway NAME CLASS ADDRESS PROGRAMMED AGE nginx-gateway-test nginx k8s-d-1.amazonaws.com True 25m root@ip-172-31-18-198:~/.jasper/ngfdir# kubectl get svc nginx-gateway-test-nginx LoadBalancer 10.210.170.159 k8s-d-1.amazonaws.com 80:31363/TCP kubectl -n default get svc nginx-gateway-test-nginx \ -o jsonpath='class=[{.spec.loadBalancerClass}] ports={.spec.ports[*].port}{"\n"}'
部署应用
# 部署 echo ,打印请求信息 cat > 02-deploy-test.yaml <<\EOF apiVersion: apps/v1 kind: Deployment metadata: name: echo namespace: default spec: replicas: 1 selector: matchLabels: app: echo template: metadata: labels: app: echo spec: containers: - name: echo image: ealen/echo-server:latest ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: echo-svc namespace: default spec: selector: app: echo ports: - port: 80 targetPort: 80 name: http type: ClusterIP EOF kubectl apply -f 02-deploy-test.yaml
使用 httproute 访问
# 创建 gateway 规则 cat <<\EOF>> 03-httproute.yaml apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: ngfapp-httproute namespace: default spec: parentRefs: - name: nginx-gateway-test namespace: default hostnames: - "echo.jasper.org" rules: - backendRefs: - name: echo-svc port: 80 kind: Service matches: - path: type: PathPrefix value: / EOF root@ip-172-31-18-198:~/.jasper/ngfdir# kubectl apply -f 03-httproute.yaml root@ip-172-31-18-198:~/.jasper/ngfdir# kubectl get httproute NAME HOSTNAMES AGE echo-route ["www.echo.com"] 11m # 排查。查看 gateway 对应的 pod 日志。 kubectl logs -f nginx-gateway-test-nginx-79d64d4cc4-kcp5q # 查看 nginx 配置文件 root@ip-172-31-18-198:~/.jasper/ngfdir# kubectl exec -it nginx-gateway-test-nginx-79d64d4cc4-kcp5q -c nginx -- nginx -T nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # configuration file /etc/nginx/nginx.conf: load_module modules/ngx_http_js_module.so; include /etc/nginx/main-includes/*.conf; worker_processes auto; pid /var/run/nginx/nginx.pid;
访问
- 本机域名解析。修改
/etc/hosts - 浏览器访问
http://www.echo.com
# 真实客户端 ip "headers": { "host": "www.echo.com", "x-forwarded-for": "1.1.162.204", "x-real-ip": "1.1.162.204", # 或在 pod echo 所在主机使用 tcpdump 命令查看 tcpdump -i any -nn -vvv -A dst host 172.31.82.72 and port 80 |grep -C50 echo
配置
时区与日志格式化
#nginx-gateway-fabric 2.6.7 cat >values-ngf.yaml <<\EOF nginxGateway: snippets: enable: true nginx: service: type: LoadBalancer externalTrafficPolicy: Cluster patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: name: tz-shanghai hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: name: tz-shanghai mountPath: /etc/localtime readOnly: true config: logging: accessLog: escape: json format: >- {"time":"$time_iso8601","remote_addr":"$remote_addr","x_forwarded_for":"$http_x_forwarded_for","host":"$host","method":"$request_method","uri":"$request_uri","protocol":"$server_protocol","status":$status,"body_bytes_sent":$body_bytes_sent,"request_length":$request_length,"request_time":$request_time,"upstream_addr":"$upstream_addr","upstream_status":"$upstream_status","upstream_response_time":"$upstream_response_time","referer":"$http_referer","user_agent":"$http_user_agent","request_id":"$request_id"} EOF # 升级: helm upgrade --install ngf . \ --create-namespace -n nginx-gateway \ -f values-ngf.yaml \ --wait --timeout 5m
配置说明
# 配置说明 #nginxGateway.snippets.enable 同时启用 SnippetsFilter 和 SnippetsPolicy。 #nginxGateway.snippetsFilters.enable 已被 chart 标记为 deprecated,且只开前者 #nginx.service.type=LoadBalancer 使用负载均衡器 #nginx.service.externalTrafficPolicy=Cluster 外部流量转发策略 # Cluster(这里配置的):源 IP 会被 SNAT 改写为节点 IP;可以做负载均衡跨节点转发。 # Local:保留真实客户端源 IP,但流量只能落到后端 Pod 所在节点。 # ---- 时区:东八区 ---- # 数据面镜像是 Alpine,既没有 /etc/localtime 也没有 tzdata, # 所以 $time_iso8601 / $time_local / error log 的时间全是 UTC # (日志里是 +00:00,比北京时间晚 8 小时)。 # # 只设 TZ=Asia/Shanghai 是没用的:musl 会去找 # /usr/share/zoneinfo/Asia/Shanghai,镜像里没有这个文件,就静默回退 UTC。 # 必须把宿主机的时区文件挂进来。这里刻意不设 TZ 环境变量—— # musl 在 TZ 未设时直接读 /etc/localtime,正好是我们挂进去的那个。 # # 用 hostPath 挂宿主机的 /usr/share/zoneinfo/Asia/Shanghai 这个实际文件 # # NginxProxy CRD 的 container 字段只有 debug/hostPorts/image,给不了 # env 和 volumeMounts,所以只能走 patches。 # chart 会把 nginx.patches 渲染进 NginxProxy 的 kubernetes.deployment.patches。 # 必须用 JSONPatch,不能用 StrategicMerge(默认类型)。 # StrategicMerge 在 NGF provisioner 这条路径上会**按索引覆盖**而不是按 name 合并: # 只含一个元素的 volumes 会盖掉 volumes[0](原本是 projected 类型的 token), # API Server 报 "may not specify more than 1 volume type", # 同时 volumeMounts 的引用全部错位,Deployment 更新直接被拒。 # JSONPatch 的 "/-" 是追加到列表末尾,不碰任何现有元素。 # # containers/0 就是 nginx:数据面 Pod 只有这一个业务容器(另有 init 初始化容器)。 # ---- 日志 json 格式化 ---- # nginx.config 的内容会被原样渲染进 NginxProxy 的 spec # (chart 模板 templates/nginxproxy.yaml: toYaml .Values.nginx.config) # nginx.config.logging.accessLog.escape=json —— 让 nginx 按 JSON 规则转义变量值(引号、反斜杠、控制字符), # 否则 User-Agent 里带引号就会把整行 JSON 破坏掉。 # 注意两条硬性限制(来自 NginxProxy CRD 的 schema): # 1. 不能有单引号 —— 这段会被渲染进单引号包裹的 log_format 指令里 # 2. 不能有换行 —— 必须写成一行 # # 字段取舍:$status / $body_bytes_sent / $request_length / $request_time # 这几个 nginx 保证非空,所以不加引号,让它们在 JSON 里是数字类型, # Grafana 里可直接做数值比较和聚合。 # upstream 相关变量在未走到上游时会是空值,必须加引号,否则 # 会产生 "upstream_status":, 这种非法 JSON。
# 查看有没有生效 kubectl -n nginx-gateway get nginxproxies.gateway.nginx.org ngf-proxy-config -oyaml
# 自定义 nginxproxy cat <<\EOF> proxy-public-config.yaml apiVersion: gateway.nginx.org/v1alpha2 kind: NginxProxy metadata: labels: app.kubernetes.io/version: 2.8.1 name: proxy-public-config namespace: gw spec: # 信任 NLB 发来的 Proxy-Protocol v2 # in-tree NLB(instance 目标)+ externalTrafficPolicy: Cluster, # kube-proxy 会 SNAT,pod 看到的源是节点 IP rewriteClientIP: mode: ProxyProtocol trustedAddresses: - type: CIDR value: 172.31.0.0/16 logging: accessLog: escape: json format: '{"time":"$time_iso8601", "cf_ray":"$http_cf_ray", "request_id":"$request_id", "cf_connecting_ip":"$http_cf_connecting_ip","remote_addr":"$remote_addr", "x_forwarded_for":"$http_x_forwarded_for", "cf_country":"$http_cf_ipcountry", "method":"$request_method", "scheme":"$scheme","host":"$host", "path":"$uri", "protocol":"$server_protocol", "status":$status, "request_length":$request_length, "body_bytes_sent":$body_bytes_sent,"request_time":$request_time, "upstream_addr":"$upstream_addr", "upstream_connect_time":"$upstream_connect_time","upstream_header_time":"$upstream_header_time", "upstream_response_time":"$upstream_response_time", "upstream_status":"$upstream_status","referer":"$http_referer", "user_agent":"$http_user_agent", "xff_prefix":"$http_x_forwarded_prefix", "request_uri":"$request_uri"}' agentLevel: error errorLevel: warn kubernetes: deployment: container: image: pullPolicy: IfNotPresent repository: ghcr.io/nginx/nginx-gateway-fabric/nginx tag: 2.8.1 resources: requests: cpu: 500m memory: 256Mi limits: memory: 1Gi # 不要设 cpu limit,高流量下会被 throttle,症状很像限流 # 容器挂载上海时区 patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File name: tz-shanghai - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: mountPath: /etc/localtime name: tz-shanghai readOnly: true replicas: 2 EOF
强制 HTTPS
cat httproute-www.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: www
namespace: default
spec:
parentRefs:
- name: gw-public-admin
namespace: gw
hostnames:
- www.jasper.org
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: www-svc
port: 80
filters:
- type: RequestRedirect
requestRedirect:
scheme: https # 强制http --> https
hostname: www.jasper.org
statusCode: 301
- type: ExtensionRef
extensionRef:
group: gateway.nginx.org
kind: SnippetsFilter
name: global-security
Rewrite 路径重写
ingress-nginx
# 都重写为 $2 路径 apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/proxy-http-version: "1.1" nginx.ingress.kubernetes.io/rewrite-target: /$2 nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/use-regex: "true" name: gateway-ingress namespace: default spec: ingressClassName: nginx rules: - host: devg.xxx.me http: paths: - backend: service: name: cloud-gateway port: number: 8080 path: /(api)/(.*) pathType: ImplementationSpecific - backend: service: name: wallet-admin-server port: number: 8080 path: /(api)/alpha/v1/(system/exchangeRateFacede/.*) pathType: ImplementationSpecific
转为对应 gatewai api
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: gateway-httproute
namespace: default
spec:
hostnames:
- devg.xxx.me
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: nginx-gateway-test
namespace: default
rules:
- backendRefs:
- group: ""
kind: Service
name: cloud-gateway
port: 8080
weight: 1
filters:
- type: URLRewrite
urlRewrite:
path:
replacePrefixMatch: /
type: ReplacePrefixMatch
matches:
- path:
type: PathPrefix
value: /api/
- backendRefs:
- group: ""
kind: Service
name: wallet-admin-server
port: 8080
weight: 1
filters:
- type: URLRewrite
urlRewrite:
path:
replacePrefixMatch: /system/exchangeRateFacede/
type: ReplacePrefixMatch
matches:
- path:
type: PathPrefix
value: /api/alpha/v1/system/exchangeRateFacede/
上传限制
- https://gateway-api.sigs.k8s.io/geps/gep-713/
- nginx gateway fabric Custom policies
cat h5-web-antd-httproute.yaml
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: h5-web-antd-httproute
namespace: default
spec:
hostnames:
- xxx.com
- devpt.xxx.com
parentRefs:
- name: nginx-gateway-test
namespace: default
rules:
- backendRefs:
- name: h5-web-antd-svc
port: 80
matches:
- path:
type: PathPrefix
value: /
---
apiVersion: gateway.nginx.org/v1alpha1
kind: ClientSettingsPolicy
metadata:
name: h5-web-antd-client-policy
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: HTTPRoute
name: h5-web-antd-httproute
body:
maxSize: "100m"
kubectl get clientsettingspolicies.gateway.nginx.org h5-web-antd-client-policy
# 查看 nginx 对应配置
kubectl exec nginx-gateway-test-nginx-5f5dcf8454-9tdlp -c nginx -- nginx -T
server {
listen 80 proxy_protocol;
listen [::]:80 proxy_protocol;
server_name devpt.xxx.com;
set_real_ip_from 172.31.0.0/16;
real_ip_header proxy_protocol;
location / {
include /etc/nginx/includes/ClientSettingsPolicy_default_h5-web-antd-client-policy.conf;
# configuration file /etc/nginx/includes/ClientSettingsPolicy_default_h5-web-antd-client-policy.conf:
client_max_body_size 100m;
NGF 数据面的 gzip 压缩
数据面的 nginx.conf 由 NGF 控制器生成,不能直接改。注入配置有两条路:
- SnippetsFilter —— 作用于 HTTPRoute/GRPCRoute,要在每条路由里引用
- SnippetsPolicy —— 作用于 Gateway,一次配置对该 Gateway 下所有路由生效 <- 用这个
两者都由 helm 的 nginxGateway.snippets.enable 开启(旧的 snippetsFilters.enable 已废弃,且只开 SnippetsFilter)。
gzip 压缩说明
gzip on; # 4 是性价比拐点:再往上 CPU 涨得快、体积只多省几个百分点 gzip_comp_level 4; # 小响应压了反而更大(gzip 头部开销约 20 字节) gzip_min_length 1k; # 必须显式开。默认 off 时,带 Via 头的代理响应一律不压—— # 而网关本身就是反向代理,不加这行等于没开 gzip_proxied any; # 让 CDN / 中间代理按 Accept-Encoding 分别缓存, # 避免把压缩版发给不支持的客户端 gzip_vary on; # text/html 不用列,nginx 总是压缩它。 # 刻意【不包含】已经是压缩格式的类型: # 图片 png/jpg/gif/webp、字体 woff2、视频、zip/gz # 对它们再压一遍只烧 CPU,体积还可能变大。 gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml application/rss+xml application/atom+xml application/manifest+json application/vnd.api+json image/svg+xml;
Gateway 全局压缩 SnippetsPolicy
cat >ngf-gzip-snippetspolicy.yaml<<EOF
# gzip 必须下在 http 上下文,所以 context: http。
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsPolicy
metadata:
name: gzip-compression
namespace: default
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: gateway-public
snippets:
- context: http
value: |
gzip on;
gzip_comp_level 4;
gzip_min_length 1k;
gzip_proxied any;
gzip_vary on;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/rss+xml
application/atom+xml
application/manifest+json
application/vnd.api+json
image/svg+xml;
EOF
HTTPRoute 压缩 SnippetsFilter
cat >app1-httproute.yaml <<EOF
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app1-httproute
namespace: default
spec:
hostnames:
- app1.jasper.org
parentRefs:
- name: gateway-internal
namespace: default
- name: gateway-public
namespace: default
rules:
- backendRefs:
- name: app1-svc
port: 80
matches:
- path:
type: PathPrefix
value: /
- backendRefs:
- name: app1-backend-svc
port: 8080
matches:
- path:
type: PathPrefix
value: /alpha/v1
filters:
- type: URLRewrite
urlRewrite:
path:
type: ReplacePrefixMatch
replacePrefixMatch: /
- type: ExtensionRef
extensionRef: {group: gateway.nginx.org, kind: SnippetsFilter, name: app1-sinppetsfilter}
---
apiVersion: gateway.nginx.org/v1alpha1
kind: ClientSettingsPolicy
metadata:
name: app1-client-policy
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: HTTPRoute
name: app1-httproute
body:
maxSize: "100m"
---
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
name: app1-sinppetsfilter
namespace: risk
spec:
snippets:
- context: http.server.location
value: |
proxy_read_timeout 5m;
proxy_send_timeout 5m;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
gzip on;
gzip_comp_level 4;
gzip_min_length 1k;
gzip_proxied any;
gzip_vary on;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/rss+xml
application/atom+xml
application/manifest+json
application/vnd.api+json
image/svg+xml
EOF
案例
安装多个 gateway 内外网
gateway class 只能有一个。 可以创建内网和公网 gateway 区分访问,默认情况下使用 nginx-gateway 名称空间下的 nginxproxies 做为 gateway 配置,可指定自己生成的 nginxproxy。
公网 nginxporxy
AWS 公网 NLB
下面配置 externalTrafficPolicy: Cluster 是 Cluster,想要获得客户端真实 IP 需要 AWS 上负载均衡器的目标组开启 Proxy‑Protocol 。如果是 Local 建议开启跨区域负载均衡,因为空着的 AZ 会成为流量黑洞,所以必须靠跨区兜底。
- Cluster 如果开了跨区负载会多付跨 AZ 流量费却没好处:Cluster 模式下 kube-proxy 本来就在全集群的 endpoint 里挑 pod,跨 AZ 转发已经发生了;NLB 这层再做一次跨区只是多一跳。
如果生成 NBL 负载均衡分两种情况:
- 安装了 AWS LBC:使用
aws-load-balancer-type: "external", 目标组为 pod ip,同时生成专属安全组。需要开启跨区域负载均衡, NLB 注册的是 pod IP,不是节点。所以健康目标的分布取决于 pod 落在哪些 AZ,而不是节点分布。 - 未安装 AWS LBC:使用
aws-load-balancer-type: nlb, 目标组为 节点 IP,使用节点已有的安全组。不需要开启跨区域负载均衡
- 安装了 AWS LBC
- service 使用
externalTrafficPolicy: Cluster - service 注解
aws-load-balancer-type: "external" - 需要开启跨区域负载均衡。
- 自动创建安全组。
访客 → Cloudflare 边缘 → NLB → (PROXY v2) → nginx pod
- dev:external + target-type: ip,IP 目标默认不保留客户端 IP → pod 看到的 TCP 源是 NLB ENI(172.31.x.x)
# Helm value cat <<\EOF> values-dev.yaml nginxGateway: snippetsFilters: enable: true nginx: config: # 信任 NLB 发来的 Proxy-Protocol v2 # 注意:这里填的是 TCP 对端(NLB ENI),不是 Cloudflare 网段 # external + target-type:ip 不保留客户端 IP,pod 看到的源是 NLB 在 VPC 内的 ENI rewriteClientIP: mode: ProxyProtocol trustedAddresses: - type: CIDR value: "172.31.0.0/16" logging: errorLevel: warn accessLog: escape: json # 提醒:重写后 $remote_addr = Cloudflare 边缘 IP,访客真实 IP 在 $http_cf_connecting_ip format: '{"time":"$time_iso8601", "cf_ray":"$http_cf_ray", "request_id":"$request_id", "cf_connecting_ip":"$http_cf_connecting_ip","remote_addr":"$remote_addr", "x_forwarded_for":"$http_x_forwarded_for", "cf_country":"$http_cf_ipcountry", "method":"$request_method", "scheme":"$scheme","host":"$host", "path":"$uri", "protocol":"$server_protocol", "status":$status, "request_length":$request_length, "body_bytes_sent":$body_bytes_sent,"request_time":$request_time, "upstream_addr":"$upstream_addr", "upstream_connect_time":"$upstream_connect_time","upstream_header_time":"$upstream_header_time", "upstream_response_time":"$upstream_response_time", "upstream_status":"$upstream_status","referer":"$http_referer", "user_agent":"$http_user_agent", "xff_prefix":"$http_x_forwarded_prefix", "request_uri":"$request_uri"}' patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: name: tz-shanghai hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: name: tz-shanghai mountPath: /etc/localtime readOnly: true service: type: LoadBalancer externalTrafficPolicy: Cluster patches: - type: StrategicMerge value: metadata: annotations: # 由 AWS Load Balancer Controller 创建公网 NLB service.beta.kubernetes.io/aws-load-balancer-type: "external" service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: "ip" service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing" service.beta.kubernetes.io/aws-load-balancer-subnets: "subnet-0a415b6c7f8914523,subnet-0ef0b0cd6d66d7596,subnet-07bd62a59b71427dc" service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: "Env=Dev" # 让 NLB 向后端发 Proxy-Protocol v2 service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: "*" spec: # 2.7.0 不需要写 loadBalancerClass loadBalancerClass: service.k8s.aws/nlb # 只允许 Cloudflare 回源。规则落在 NLB 前端 SG 上, # 健康检查由 LBC 通过后端 SG 引用自动放行,无需在此放行 VPC 段。 # 来源:https://www.cloudflare.com/ips-v4 loadBalancerSourceRanges: # Cloudflare IPv4 - 173.245.48.0/20 - 103.21.244.0/22 - 103.22.200.0/22 - 103.31.4.0/22 - 141.101.64.0/18 - 108.162.192.0/18 - 190.93.240.0/20 - 188.114.96.0/20 - 197.234.240.0/22 - 198.41.128.0/17 - 162.158.0.0/15 - 104.16.0.0/13 - 104.24.0.0/14 - 172.64.0.0/13 - 131.0.72.0/22 # NLB 未设 ip-address-type,默认 ipv4-only,故无需 Cloudflare IPv6 段。 # 若将来加 aws-load-balancer-ip-address-type: dualstack,需补: # 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 # 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32 # # 按需要放行 - x.x.x.x/32 # jenkins-cli 出口,测完删 EOF helm install ngf . \ --create-namespace -n nginx-gateway \ -f ./values-dev.yaml \ --wait --timeout 5m # 更新用 helm upgrade --install ngf . \ --create-namespace -n nginx-gateway \ -f ./values-dev.yaml \ --wait --timeout 5m # 安装完成后校验 NginxProxy CR 是否渲染正确 patches: kubectl get nginxproxy ngf-proxy-config -n nginx-gateway -o yaml
或者直接新建个自定义 nginxproxy
kubectl create ns gw cat <<\EOF> gw-public.yaml apiVersion: gateway.nginx.org/v1alpha2 kind: NginxProxy metadata: labels: app.kubernetes.io/version: 2.6.7 name: proxy-public-config namespace: gw spec: ipFamily: dual kubernetes: deployment: container: image: pullPolicy: IfNotPresent repository: ghcr.io/nginx/nginx-gateway-fabric/nginx tag: 2.6.7 resources: limits: memory: 1Gi requests: cpu: 500m memory: 256Mi patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File name: tz-shanghai - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: mountPath: /etc/localtime name: tz-shanghai readOnly: true replicas: 1 service: externalTrafficPolicy: Cluster patches: - type: StrategicMerge value: spec: loadBalancerSourceRanges: # 只允许 Cloudflare 回源。规则落在 NLB 前端 SG 上, # 康检查由 LBC 通过后端 SG 引用自动放行,无需在此放行 VPC 段。 # 来源:https://www.cloudflare.com/ips-v4 (会变动) - 173.245.48.0/20 - 103.21.244.0/22 - 103.22.200.0/22 - 103.31.4.0/22 - 141.101.64.0/18 - 108.162.192.0/18 - 190.93.240.0/20 - 188.114.96.0/20 - 197.234.240.0/22 - 198.41.128.0/17 - 162.158.0.0/15 - 104.16.0.0/13 - 104.24.0.0/14 - 172.64.0.0/13 - 131.0.72.0/22 # 临时绕过 - x.x.x.x/32 # jp pc - type: StrategicMerge value: metadata: annotations: # 由 AWS Load Balancer Controller 创建公网 NLB service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: Env=Dev service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing service.beta.kubernetes.io/aws-load-balancer-subnets: subnet-x1,subnet-x2,subnet-x3 service.beta.kubernetes.io/aws-load-balancer-type: external # 让 NLB 向后端发 Proxy-Protocol v2 service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: '*' spec: loadBalancerClass: service.k8s.aws/nlb type: LoadBalancer logging: accessLog: escape: json # 提醒:重写后 $remote_addr = Cloudflare 边缘 IP,访客真实 IP 在 $http_cf_connecting_ip format: '{"time":"$time_iso8601", "cf_ray":"$http_cf_ray", "request_id":"$request_id", "cf_connecting_ip":"$http_cf_connecting_ip","remote_addr":"$remote_addr", "x_forwarded_for":"$http_x_forwarded_for", "cf_country":"$http_cf_ipcountry", "method":"$request_method", "scheme":"$scheme","host":"$host", "path":"$uri", "protocol":"$server_protocol", "status":$status, "request_length":$request_length, "body_bytes_sent":$body_bytes_sent,"request_time":$request_time, "upstream_addr":"$upstream_addr", "upstream_connect_time":"$upstream_connect_time","upstream_header_time":"$upstream_header_time", "upstream_response_time":"$upstream_response_time", "upstream_status":"$upstream_status","referer":"$http_referer", "user_agent":"$http_user_agent", "xff_prefix":"$http_x_forwarded_prefix", "request_uri":"$request_uri"}' agentLevel: error errorLevel: warn # 信任 NLB 发来的 Proxy-Protocol v2 # 注意:这里填的是 TCP 对端(NLB ENI),不是 Cloudflare 网段 # external + target-type:ip 不保留客户端 IP,pod 看到的源是 NLB 在 VPC 内的 ENI rewriteClientIP: mode: ProxyProtocol trustedAddresses: - type: CIDR value: 172.31.0.0/16 EOF # balancer-subnets 为公有子网,pod所在实例安全组允许该网段 kubect apply -f gw-public.yaml # 查看 nginxproxy kubectl -n gw get nginxproxy proxy-public-config
修改 LBC 兼容 NGF,这样可以自动更新 service nlb 端口
#确认来 lbc webhook 内容 kubectl get mutatingwebhookconfiguration aws-load-balancer-webhook \ -o jsonpath='{range .webhooks[*]}{@.name}{"\t"}{@.objectSelector}{"\n"}{end}' | nl -v0 # 输出如下 0 mservice.elbv2.k8s.aws {"matchExpressions":[{"key":"app.kubernetes.io/name","operator":"NotIn","values":["aws-load-balancer-controller"]}]} 1 mpod.elbv2.k8s.aws {"matchExpressions":[{"key":"app.kubernetes.io/name","operator":"NotIn","values":["aws-load-balancer-controller"]}]} 2 mtargetgroupbinding.elbv2.k8s.aws {} kubectl get mutatingwebhookconfiguration aws-load-balancer-webhook \ -o jsonpath='{range .webhooks[?(@.name=="mservice.elbv2.k8s.aws")]}{.objectSelector}{"\n"}{end}' # 合并,新增 NGF cat >lbc-webhook-objectselector.yaml <<\EOF webhooks: - name: mservice.elbv2.k8s.aws objectSelector: matchExpressions: - key: app.kubernetes.io/name # 原有:不 mutate LBC 自己 operator: NotIn values: - aws-load-balancer-controller - key: gateway.networking.k8s.io/gateway-name # 新增:不 mutate NGF 数据面 operator: DoesNotExist EOF kubectl patch mutatingwebhookconfiguration aws-load-balancer-webhook \ --type=strategic --patch-file=lbc-webhook-objectselector.yaml \ --dry-run=server \ -o jsonpath='{range .webhooks[*]}{@.name}{"\n sel="}{@.objectSelector}{"\n ns="}{@.namespaceSelector}{"\n ops="}{@.rules[*].operations}{"\n"}{end}' # 生效 kubectl patch mutatingwebhookconfiguration aws-load-balancer-webhook \ --type=strategic --patch-file=lbc-webhook-objectselector.yaml \ -o jsonpath='{range .webhooks[*]}{@.name}{"\n sel="}{@.objectSelector}{"\n ns="}{@.namespaceSelector}{"\n ops="}{@.rules[*].operations}{"\n"}{end}'
- service 使用
- 未安装 AWS LBC
- service 使用
externalTrafficPolicy: Cluster - service 注解
aws-load-balancer-type: nlb - 不需要开启跨区域负载均衡。
- 使用已有的节点安全组。
访客 → Cloudflare 边缘 → NLB → (PROXY v2) → nginx pod
- prod:in-tree NLB + instance 目标 + externalTrafficPolicy: Cluster → kube-proxy 做了 SNAT,pod 看到的是节点 IP(172.31.x.x)
cat <<\EOF> values-prod.yaml nginxGateway: snippets: enable: true nginx: replicas: 2 config: # 信任 TCP Proxy‑Protocol v2 四层 NLb rewriteClientIP: mode: ProxyProtocol # AWS VPC CIDR,信任NLB的来源网段 trustedAddresses: - type: CIDR value: "172.31.0.0/16" logging: errorLevel: warn accessLog: escape: json # 提醒:重写后 $remote_addr = Cloudflare 边缘 IP,访客真实 IP 在 $http_cf_connecting_ip format: '{"time":"$time_iso8601", "cf_ray":"$http_cf_ray", "request_id":"$request_id", "cf_connecting_ip":"$http_cf_connecting_ip","remote_addr":"$remote_addr", "x_forwarded_for":"$http_x_forwarded_for", "cf_country":"$http_cf_ipcountry", "method":"$request_method", "scheme":"$scheme","host":"$host", "path":"$uri", "protocol":"$server_protocol", "status":$status, "request_length":$request_length, "body_bytes_sent":$body_bytes_sent,"request_time":$request_time, "upstream_addr":"$upstream_addr", "upstream_connect_time":"$upstream_connect_time","upstream_header_time":"$upstream_header_time", "upstream_response_time":"$upstream_response_time", "upstream_status":"$upstream_status","referer":"$http_referer", "user_agent":"$http_user_agent", "xff_prefix":"$http_x_forwarded_prefix", "request_uri":"$request_uri"}' patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: name: tz-shanghai hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: name: tz-shanghai mountPath: /etc/localtime readOnly: true service: type: LoadBalancer externalTrafficPolicy: Cluster patches: - type: StrategicMerge value: spec: loadBalancerSourceRanges: # 只允许 Cloudflare 回源。in-tree NLB 的规则落在节点 SG 上, # 因此必须额外放行 VPC 段,否则健康检查会失败。 - 173.245.48.0/20 - 103.21.244.0/22 - 103.22.200.0/22 - 103.31.4.0/22 - 141.101.64.0/18 - 108.162.192.0/18 - 190.93.240.0/20 - 188.114.96.0/20 - 197.234.240.0/22 - 198.41.128.0/17 - 162.158.0.0/15 - 104.16.0.0/13 - 104.24.0.0/14 - 172.64.0.0/13 - 131.0.72.0/22 # 健康检查必须放行 - 172.31.0.0/16 # 按需放行 - 13.x.x.x/32 # jenkins-cli 出口,测完删掉 - type: StrategicMerge value: metadata: annotations: # 旧版 in-tree NLB(非 LBC)。 service.beta.kubernetes.io/aws-load-balancer-type: nlb service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing" service.beta.kubernetes.io/aws-load-balancer-subnets: "subnet-0f18f79849d93eeef,subnet-0ac7f4e0797b8b451,subnet-035af6d4bf2e63818" service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: "Env=Prod" service.beta.kubernetes.io/aws-load-balancer-attributes: load_balancing.cross_zone.enabled=true # 让 NLB 向后端发 Proxy-Protocol v2 service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: "*" EOF # 更新用 helm upgrade --install ngf . \ --create-namespace -n nginx-gateway \ -f ./values-prod.yaml \ --wait --timeout 5m
或者直接用自定义 nginxproxy
kubectl create ns gw cat <<\EOF> proxy-public-config.yaml apiVersion: gateway.nginx.org/v1alpha2 kind: NginxProxy metadata: labels: app.kubernetes.io/version: 2.8.1 name: proxy-public-config namespace: gw spec: # 信任 NLB 发来的 Proxy-Protocol v2 # in-tree NLB(instance 目标)+ externalTrafficPolicy: Cluster, # kube-proxy 会 SNAT,pod 看到的源是节点 IP rewriteClientIP: mode: ProxyProtocol trustedAddresses: - type: CIDR value: 172.31.0.0/16 kubernetes: deployment: container: image: pullPolicy: IfNotPresent repository: ghcr.io/nginx/nginx-gateway-fabric/nginx tag: 2.8.1 resources: requests: cpu: 500m memory: 256Mi limits: memory: 1Gi # 不要设 cpu limit,高流量下会被 throttle,症状很像限流 # 容器挂载上海时区 patches: - type: JSONPatch value: - op: add path: /spec/template/spec/volumes/- value: hostPath: path: /usr/share/zoneinfo/Asia/Shanghai type: File name: tz-shanghai - op: add path: /spec/template/spec/containers/0/volumeMounts/- value: mountPath: /etc/localtime name: tz-shanghai readOnly: true replicas: 2 service: externalTrafficPolicy: Cluster patches: - type: StrategicMerge value: spec: loadBalancerSourceRanges: # 只允许 Cloudflare 回源。in-tree NLB 的规则落在节点 SG 上, # 因此必须额外放行 VPC 段,否则健康检查会失败。 - 173.245.48.0/20 - 103.21.244.0/22 - 103.22.200.0/22 - 103.31.4.0/22 - 141.101.64.0/18 - 108.162.192.0/18 - 190.93.240.0/20 - 188.114.96.0/20 - 197.234.240.0/22 - 198.41.128.0/17 - 162.158.0.0/15 - 104.16.0.0/13 - 104.24.0.0/14 - 172.64.0.0/13 - 131.0.72.0/22 # 健康检查必须放行 - 172.31.0.0/16 # 临时放行 - x.x.x.x/32 # jp pc - type: StrategicMerge value: metadata: annotations: # 旧版 in-tree NLB(非 LBC)。待迁移至 external,见文末待办。 service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: Env=Prod service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true" service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing service.beta.kubernetes.io/aws-load-balancer-subnets: subnet-0f18f79849d93eeef,subnet-0ac7f4e0797b8b451,subnet-035af6d4bf2e63818 service.beta.kubernetes.io/aws-load-balancer-type: nlb # 让 NLB 向后端发 Proxy-Protocol v2 。需要手动开启。 #service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: '*' type: LoadBalancer logging: accessLog: escape: json format: '{"time":"$time_iso8601", "cf_ray":"$http_cf_ray", "request_id":"$request_id", "cf_connecting_ip":"$http_cf_connecting_ip","remote_addr":"$remote_addr", "x_forwarded_for":"$http_x_forwarded_for", "cf_country":"$http_cf_ipcountry", "method":"$request_method", "scheme":"$scheme","host":"$host", "path":"$uri", "protocol":"$server_protocol", "status":$status, "request_length":$request_length, "body_bytes_sent":$body_bytes_sent,"request_time":$request_time, "upstream_addr":"$upstream_addr", "upstream_connect_time":"$upstream_connect_time","upstream_header_time":"$upstream_header_time", "upstream_response_time":"$upstream_response_time", "upstream_status":"$upstream_status","referer":"$http_referer", "user_agent":"$http_user_agent", "xff_prefix":"$http_x_forwarded_prefix", "request_uri":"$request_uri"}' agentLevel: error errorLevel: warn EOF - service 使用
公网 gateway
# 生成证书 curl https://get.acme.sh | sh -s email[email protected] export CF_Token="cfut_xxxx" export CF_Email="[email protected]" acme.sh --set-default-ca --server letsencrypt acme.sh --issue --dns dns_cf -d jasper.org -d *.jasper.org --dnssleep 120 # 给 gateway 加证书 SSL_CRT=jasper.org.crt SSL_KEY=jasper.org.crt SECRET=jasper-tls NS=default SSL_CRT="${SSL_CRT:-origin.crt}" SSL_KEY="${SSL_KEY:-origin.key}" kubectl -n "$NS" create secret tls "$SECRET" \ --cert="$SSL_CRT" --key="$SSL_KEY" \ --dry-run=client -o yaml | kubectl apply -f - #先备份现有 Secret kubectl -n "$NS" get secret "$SECRET" -o yaml > /tmp/jasper-tls.backup.$(date +%F).yaml #验证新证书和私钥配对,再替换 # 两个 md5 必须一样,不然推上去 NGF 直接 ResolvedRefs=False openssl x509 -noout -modulus -in "$SSL_CRT" | openssl md5 openssl rsa -noout -modulus -in "$SSL_KEY" | openssl md5 # 确认 SAN 两条都在 openssl x509 -in "$SSL_CRT" -noout -ext subjectAltName -enddate # 替换证书 kubectl -n "$NS" create secret tls "$SECRET" \ --cert="$SSL_CRT" --key="$SSL_KEY" \ --dry-run=client -o yaml | kubectl apply -f - # 查看证书信息 kubectl -n "$NS" get secret "$SECRET" -o jsonpath='{.data.tls\.crt}' \ | base64 -d | openssl x509 -noout -subject -issuer -dates -ext subjectAltName cat > gateway-public.yaml <<\EOF apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: gateway-public namespace: default spec: gatewayClassName: nginx # 如果指定自定义 nginxproxy,需要单独写 infrastructure 段 listeners: - allowedRoutes: namespaces: # 默认Once 当前名称空间,All 所有名称空间能用这个 gateway。 select 指定名称空间 from: All name: http port: 80 protocol: HTTP - name: https port: 443 protocol: HTTPS hostname: "*.xxx.com" tls: mode: Terminate certificateRefs: - kind: Secret name: xxx-tls allowedRoutes: namespaces: from: All EOF kubectl apply -f gateway-public.yaml
cat <<\EOF> gw-public.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: gw-public
namespace: gw
spec:
gatewayClassName: nginx
# 指定 nginxproxy 配置
infrastructure:
parametersRef:
group: gateway.nginx.org
kind: NginxProxy
name: proxy-public-config
listeners:
- name: http
port: 80
protocol: HTTP
allowedRoutes:
# 仅 default 名称空间能用这个 gateway
namespaces:
from: Selector
selector:
matchLabels:
kubernetes.io/metadata.name: default
- name: https-xx
port: 443
protocol: HTTPS
hostname: "*.xxx.com"
tls:
mode: Terminate
certificateRefs:
# 默认引用当前名称空间下的证书文件。如果使用别的名称空间证书需要指定 ReferenceGrant 授权
- kind: Secret
name: xxx-tls-secret
namespace: default
allowedRoutes:
namespaces:
from: Selector
selector:
matchLabels:
kubernetes.io/metadata.name: default
# 泛域名证书不匹配 apex,xxx.com 必须单列 listener
- name: https-xx-apex
port: 443
protocol: HTTPS
hostname: "xxx.com"
tls:
mode: Terminate
certificateRefs:
- kind: Secret
name: xxx-tls-secret
namespace: default
allowedRoutes:
namespaces:
from: Selector
selector:
matchLabels:
kubernetes.io/metadata.name: default
---
# 没有这个 ReferenceGrant,上面所有 https listener 都是
# ResolvedRefs=False / RefNotPermitted,TLS 直接起不来。
#
# 注意它必须建在**证书所在的 namespace**(default),不是 gw。
# 语义是 default 的管理员主动授权,而不是 gw 单方面去取。
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
name: gw-to-default-secrets
namespace: default
spec:
from:
- group: gateway.networking.k8s.io
kind: Gateway
namespace: gw
to:
- group: ""
kind: Secret
# 限定只能读这两个证书,不写 name 就是 default 里的所有 Secret
name: admin-tls-secret
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
name: gw-to-default-secrets-xx
namespace: default
spec:
from:
- group: gateway.networking.k8s.io
kind: Gateway
namespace: gw
to:
- group: ""
kind: Secret
name: xx-tls-secret
EOF
内网 nginxproxy
安装了 AWS LBC
cat <<\EOF> gw-internal.yaml apiVersion: gateway.nginx.org/v1alpha2 kind: NginxProxy metadata: labels: app.kubernetes.io/version: 2.6.7 name: proxy-internal-config namespace: gw spec: ipFamily: dual kubernetes: deployment: container: image: pullPolicy: IfNotPresent repository: ghcr.io/nginx/nginx-gateway-fabric/nginx tag: 2.6.7 resources: requests: cpu: 500m memory: 256Mi limits: memory: 1Gi # 不要设 cpu limit,高流量下会被 throttle,症状很像限流 replicas: 1 service: externalTrafficPolicy: Cluster patches: - type: StrategicMerge value: metadata: annotations: service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: Env=Dev service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip service.beta.kubernetes.io/aws-load-balancer-proxy-protocol: '*' service.beta.kubernetes.io/aws-load-balancer-scheme: internal service.beta.kubernetes.io/aws-load-balancer-subnets: subnet-in1,subnet-in2,subnet-in3 service.beta.kubernetes.io/aws-load-balancer-type: external service.beta.kubernetes.io/aws-load-balancer-attributes: load_balancing.cross_zone.enabled=true type: LoadBalancer rewriteClientIP: mode: ProxyProtocol trustedAddresses: - type: CIDR value: 172.31.0.0/16 EOF # 注意子网使用内网网段 kubectl apply -f gw-internal.yaml
内网 gateway
# 创建内网 gateway cat <<\EOF> gateway-internal.yaml apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: gateway-internal namespace: gw spec: gatewayClassName: nginx infrastructure: parametersRef: group: gateway.nginx.org kind: NginxProxy name: proxy-internal-config listeners: - name: http protocol: HTTP port: 80 allowedRoutes: namespaces: from: All EOF kubectl apply -f gateway-internal.yaml
httproute
安装设置 SnippetsFilter
cat <<\EOF> 30-security-snippets.yaml
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
name: global-security
namespace: default
spec:
snippets:
# http.server 上下文 == ingress-nginx 的 server-snippet,语义一一对应。
# $request_uri 是未经解码的原始 URI(含 query string),~* 为不区分大小写的
# 子串匹配 —— /api/actuator/health、/ACTUATOR 都会被拦,这点和原来一致,
# 用 PathPrefix 的 HTTPRoute 做不到等价。
- context: http.server
value: |
if ($request_uri ~* "/actuator") { return 403; }
if ($request_uri ~* "snail-?job") { return 403; }
if ($http_x_forwarded_prefix ~* "actuator|snail-?job") { return 403; }
if ($request_uri ~* "~*/(v[23]/api-docs|swagger-ui|swagger-resources|knife4j|webjars)(/|\?|$)") {return 403; }
# 路径穿越 / 多重 URL 编码绕过
#
# 捕获:GET /api/basic/..%252fchain/v2/zz9608t → 200
# %25 = '%',nginx 解码一次得到 ..%2f,对它而言只是普通字符串,
# 内建的路径规范化不会触发,请求被原样转给后端;
# 后端(尤其 Spring Cloud Gateway)若再解码一次就变成 ../,
# 可用于在微服务之间横向跳转。
#
# 用 $request_uri(未解码的原始 URI)匹配,才能看到 %252f 这层。
# 只拦 ".." 紧跟分隔符的形式,不拦裸 %25 / %2f ——
# 那两个在搜索参数、含斜杠的资源 ID 里是合法的,会误伤。
if ($request_uri ~* "\.\.(/|%2f|%252f|%5c|%255c)") { return 403; }
if ($request_uri ~* "(%2e%2e|%252e)") { return 403; }
# ── 支付状态 / 金额篡改参数 ──────────────────────────────────
# 捕获: 拿真实收银台会话,在 03:54 一分钟内连打
# ?payStatus=1 ?payStatus=PAID ?tradeStatus=SUCCESS ?success=true
# ?amount=999 ?amount=0.01 ?payAmount=1 ?sign=1
# 04:10 又补了方法覆盖 ?_method=POST&status=1&tradeStatus=SUCCESS
# 和参数污染 ?status=1&status=0、数组写法 ?status[]=1。
if ($args ~* "(^|&)_method=") { return 403; }
if ($args ~* "(^|&)(pay_?status|trade_?status|order_?status|payment_?status)=") { return 403; }
if ($args ~* "(^|&)(pay_?amount|total_?amount|real_?amount|paid_?amount)=") { return 403; }
if ($args ~* "(^|&)(mock|sandbox|test_?mode|debug)=(1|true|yes|on)") { return 403; }
# ── 扫描工具 UA ──────────────────────────────────────────────
# 只封明确自报家门的攻击工具。**不按爬虫 UA 封** —— 34.48 用了 24 个
# 伪造爬虫 UA(Googlebot/GPTBot/Claude-User/Kimi/Qwenbot…),按 UA 封拦不住
# 他(换一个就行),却会误伤真实 Googlebot 影响 SEO。
# 伪造爬虫的正确解法是 Cloudflare 的 Verified Bots(按 ASN + 反向解析校验)。
if ($http_user_agent ~* "(sqlmap|nikto|nuclei|acunetix|nessus|openvas|wpscan|dirbuster|gobuster|feroxbuster|ffuf|masscan|zgrab|nmap|hydra|metasploit|xray)") { return 403; }
# ── 从不合法的 HTTP 方法 ─────────────────────────────────────
# TRACE/TRACK 可用于 XST 跨站追踪,CONNECT 是代理方法,正常业务永远用不到。
# 注意这里没有拦 PUT/PATCH/DELETE —— 那几个在其他 REST 接口上是合法的,
# 全局拦会误伤;"只读支付查询接口上出现写方法"由 Loki 告警检测。
if ($request_method ~ "^(TRACE|TRACK|CONNECT)$") { return 405; }
# ── 扫描器 payload 字典(34的 352 个请求)───────────
# 这些路径在平台上完全不存在,出现即为探测。
# 上面的 ".." 规则已经挡下了当晚的全部样本,这里补的是不带 ../ 的变体。
if ($request_uri ~* "/proc/self/(environ|cmdline|status|fd)") { return 403; }
if ($request_uri ~* "/userfiles(/|\?|$)") { return 403; }
if ($request_uri ~* "jobs_u/get_log_file") { return 403; }
if ($request_uri ~* "/api/console/api_server") { return 403; }
if ($request_uri ~* "(wp-login|wp-admin|wp-content|xmlrpc\.php)") { return 403; }
if ($request_uri ~* "/(_profiler|telescope|phpinfo|server-status|solr|phpmyadmin|adminer)(/|\?|$)") { return 403; }
if ($request_uri ~* "[?&](rest_route|input_file|SPX_KEY|SPX_UI_URI|cmd|exec)=") { return 403; }
# ── 按真实访客 IP 封禁 ─────────────────
if ($http_cf_connecting_ip = "x.x.x.x") { return 403; } # GCP:12 分钟 352 请求,24 个伪造爬虫 UA
if ($http_cf_connecting_ip = "x.x.x.x1") { return 403; } # Cogent:支付篡改 + 目录爆破
if ($http_cf_connecting_ip = "x.x.x.x2") { return 403; } # Oracle(IN):actuator 注入 + 凭据爆破
# X-Forwarded-Prefix 注入防护(原 ingress-nginx 没有,是迁移中发现的真实攻击)
#
# 捕获到的探测:
# X-Forwarded-Prefix: /socket/actuator/env
# GET /api?Authorization=... cf_country=MY status=200
#
# Spring Cloud Gateway 用这个头重建请求路径,攻击者借此绕过基于
# $request_uri 的过滤直达内部 actuator。原规则只看 URI,完全没命中。
#
# 两层防护缺一不可:
# · 下面的 proxy_set_header 把头清空 —— 后端收不到,堵死利用链
# · 上面的 if 当场返回 403 —— 在日志里留痕,才能告警
# 只有前者的话攻击确实被挡住了,但日志里是 200,看不出有人在打。
- context: http.server.location
value: |
proxy_set_header X-Forwarded-Prefix "";
---
# 通用的"拒绝"过滤器 —— 给兜底规则用,让未显式放行的路径返回 403 而不是 404。
#
# 用法:在 HTTPRoute 里加一条 PathPrefix: / 的规则引用它。
# Gateway API 按最长前缀匹配,具体路径的规则会压过 /,所以白名单照常工作。
#
# ⚠ 兜底规则必须保留 backendRefs(随便指一个存在的 Service)。
# NGF 对没有 backendRef 的规则会渲染成 return 500,和这里的 return 403
# 撞车且先后顺序不可控。留占位 backend 后,return 403 在 rewrite 阶段
# 就短路了,proxy_pass 永远不会执行,不会真的产生回源流量。
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
name: deny-all
namespace: default
spec:
snippets:
- context: http.server.location
value: |
return 403;
EOF
后端业务域名
cat <<\EOF> httproute-openapi.yaml
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: in-openapi
namespace: default
spec:
hostnames:
- openapi.test.jp
parentRefs:
- name: gateway-internal
namespace: gw
sectionName: http
rules:
- backendRefs:
# nginx 内部配置做安装兜底
- name: jp-gateway-svc
port: 8080
matches:
- path:
type: PathPrefix
value: /api/pay
- path:
type: PathPrefix
value: /api/pay/createOrder
- path:
type: PathPrefix
value: /api/pay/payout
filters:
- type: ExtensionRef
extensionRef: {group: gateway.nginx.org, kind: SnippetsFilter, name: global-security}
# ── 兜底:其余路径 403
- matches:
- path: {type: PathPrefix, value: /}
filters:
- type: ExtensionRef
extensionRef: {group: gateway.nginx.org, kind: SnippetsFilter, name: deny-all}
backendRefs:
- name: jp-gateway-svc
port: 8080
EOF
前端业务
cat <<\EOF> httproute-admin.yaml
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: in-admin
namespace: default
spec:
hostnames:
- admin.test.jp
parentRefs:
- name: gateway-internal
namespace: gw
sectionName: http
rules:
- backendRefs:
- name: admin-svc
port: 80
matches:
- path:
type: PathPrefix
value: /
filters:
- type: ExtensionRef
extensionRef:
group: gateway.nginx.org
kind: SnippetsFilter
name: global-security
- backendRefs:
- name: admin-server-svc
port: 8080
matches:
- path:
type: PathPrefix
value: /alpha/v1/
filters:
- type: ExtensionRef
extensionRef: {group: gateway.nginx.org, kind: SnippetsFilter, name: global-security}
- type: URLRewrite
urlRewrite:
path:
type: ReplacePrefixMatch
replacePrefixMatch: /
- type: ExtensionRef
extensionRef: {group: gateway.nginx.org, kind: SnippetsFilter, name: admin-sinppetsfilter}
---
apiVersion: gateway.nginx.org/v1alpha1
kind: ClientSettingsPolicy
metadata:
name: admin-client-policy
namespace: default
spec:
targetRef:
group: gateway.networking.k8s.io
kind: HTTPRoute
name: in-admin
body:
maxSize: "100m"
---
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
name: admin-sinppetsfilter
namespace: default
spec:
snippets:
- context: http.server.location
value: |
proxy_read_timeout 5m;
proxy_send_timeout 5m;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
EOF