Google 云 TCP 负载均衡器转发 ip

Google Cloud TCP Load Balancer forward ip

我使用 Google 云 TCP 负载均衡器将请求转发到 Kubernetes NGINX 服务。正如预期的那样,NGINX 上的日志显示了负载均衡器 IP。如何检索实际 IP

使用$http_x_forwarded_for变量记录用户的原始ip。

Load Balancer转发的headers是

X-Forwarded-For
X-Forwarded-Proto

因此在 nginx 上应使用“$http_x_forwarded_for”

location / {
  ...
  proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
  ...
}

如果您使用的是 Kubernetes 和服务,则需要将外部流量策略设置为本地

kind: Service
apiVersion: v1
metadata:
  name: proxy-service
spec:
  selector:
    app: the-application
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
  - protocol: TCP
    port: 443
    targetPort: 443
    name: https