Search code examples
nginxgoogle-cloud-platformgoogle-cloud-load-balancer

Google Cloud TCP Load Balancer forward ip


I use Google Cloud TCP load balancer forwarding requests to a Kubernetes NGINX service. As expected the logs on the NGINX show the Load Balancer IP. How can I retrieve the actual IP


Solution

  • The forwarded headers from the Load Balancer are

    X-Forwarded-For
    X-Forwarded-Proto
    

    Thus on nginx "$http_x_forwarded_for" shall be used

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

    If you are using Kubernetes and services you need to set the extrernal traffic policy to local

    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