You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GCP Kubernetes Pod中保留客户端真实IP

解决GCP Kubernetes中Nginx无法获取真实客户端IP的问题

要在GCP Kubernetes环境中让Nginx获取到互联网请求的真实客户端IP,需要调整Service和Nginx配置,以下是具体方案:

1. 修改Service配置,保留客户端源IP

在LoadBalancer类型的Service中添加externalTrafficPolicy: Local,这会让GCP的负载均衡器跳过SNAT(源地址转换),直接将请求转发到运行目标Pod的节点,从而保留客户端真实IP。

修改后的Service YAML:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 8080
      targetPort: 80
  type: LoadBalancer
  externalTrafficPolicy: Local  # 新增配置,保留客户端IP

2. 调整Nginx配置,正确读取客户端IP

GCP负载均衡器会在转发请求时添加X-Forwarded-For头,包含客户端真实IP;同时开启externalTrafficPolicy: Local后,Nginx的$remote_addr变量也会直接显示客户端IP。可以同时返回这两个值来验证。

修改后的ConfigMap YAML:

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  nginx.conf: |
    events {}
    http {
      server {
        listen 80;
        location /info {
          default_type 'application/json';
          add_header 'X-Forwarded-For' '$http_x_forwarded_for';
          return 200 '{ "remote_port": "$remote_port", "remote_addr": "$remote_addr", "x_forwarded_for": "$http_x_forwarded_for", "server_time": "$msec", "client_timestamp": "$http_x_client_timestamp","tcpinfo_rtt": "$tcpinfo_rtt", "tcpinfo_rttvar": "$tcpinfo_rttvar", "tcpinfo_snd_cwnd": "$tcpinfo_snd_cwnd", "tcpinfo_rcv_space": "$tcpinfo_rcv_space" }';
        }
        location /headers {
          default_type 'application/json';
          add_header X-Forwarded-For $http_x_forwarded_for;
          return 200 '{ "headers": "$http_x_forwarded_for" }';
        }
      }
    }

3. 应用配置并验证

执行以下命令更新资源:

kubectl apply -f your-deployment-file.yaml

等待负载均衡器更新完成后,访问http://<LB-IP>:8080/info,查看返回的remote_addr和x_forwarded_for字段,两者都应显示客户端的真实公网IP。

内容的提问来源于stack exchange,提问作者Rumira Daksith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:49:53