如何通过Kubernetes(OpenShift) Ingress代理外部站点并实现Header重写
结论
完全可以通过OpenShift自带的Router(基于HAProxy实现)或标准K8s Ingress实现外部站点代理+请求头重写需求,无需额外部署Apache Pod。
原有方案失效原因
- ExternalName Service方案:OpenShift Router默认会校验后端Service的端点状态,ExternalName类型Service没有关联Endpoints资源,会被Router标记为不可用,直接返回503错误。
- Headless Service+手动Endpoints方案:默认没有配置Host头传递、端口匹配规则,外部站点收到错误的Host头后拒绝响应,同时缺少请求头重写的相关配置。
正确实现步骤
1. 配置外部服务关联
根据你的外部站点是IP还是域名选择对应方案:
方案A:外部站点为固定IP
apiVersion: v1 kind: Service metadata: name: external-svc spec: ports: - name: http port: 80 protocol: TCP targetPort: 80 type: ClusterIP --- apiVersion: v1 kind: Endpoints metadata: name: external-svc subsets: - addresses: - ip: 你的外部站点IP ports: - name: http port: 80 protocol: TCP
方案B:外部站点为域名(无需配置Endpoints)
kind: Service metadata: name: external-svc annotations: # 必须添加该注解,让Router跳过端点检查 route.openshift.io/endpoint-availability-policy: "None" spec: externalName: 你的外部站点域名,例如google.com type: ExternalName
2. 配置Route实现代理和请求头重写
通过HAProxy注解实现请求头的增、删、改,配置示例如下:
kind: Route apiVersion: route.openshift.io/v1 metadata: name: external-proxy-route annotations: # 跳过端点健康检查,ExternalName场景必加 route.openshift.io/endpoint-availability-policy: "None" # 关闭原始Host头传递,用下方配置的Host头访问外部站点 haproxy.router.openshift.io/preserve-host: "false" # 设置向后端传递的Host头为外部站点的域名,避免后端识别异常 haproxy.router.openshift.io/set-host: "你的外部站点域名" # 新增自定义请求头,格式为haproxy.router.openshift.io/header-[序号]: "[头名]: [头值]" haproxy.router.openshift.io/header-1: "X-Custom-Header: my-custom-value" haproxy.router.openshift.io/header-2: "X-Proxy-Source: openshift-cluster" # 重写已有请求头,例如重写User-Agent haproxy.router.openshift.io/header-3: "User-Agent: OpenShift-Router-Proxy" # 删除不需要的请求头,格式为haproxy.router.openshift.io/del-header-[序号]: "[头名]" haproxy.router.openshift.io/del-header-1: "X-Internal-Header" spec: host: host.my-cluster-url.net to: kind: Service name: external-svc weight: 100 port: targetPort: http # 和Service中定义的端口名保持一致 # 外部站点为HTTPS时添加以下tls配置 tls: termination: edge insecureEdgeTerminationPolicy: Redirect destinationCACertificate: | -----BEGIN CERTIFICATE----- 外部站点的CA根证书,公共可信任证书可省略该字段 -----END CERTIFICATE-----
OpenShift Router日志查看方法
OpenShift的Router Pod统一运行在openshift-ingress命名空间下:
- 首先查询Router Pod名称:
oc get pods -n openshift-ingress - 查看实时访问日志:
oc logs -f <替换为实际Router Pod名称> -n openshift-ingress
如果日志无请求输出,可以给Router的IngressController资源添加router.openshift.io/log-level: debug注解开启debug级别日志,排查完成后记得改回默认级别避免性能损耗。
内容的提问来源于stack exchange,提问作者JavaHead
相关产品推荐
相关产品推荐

