How to access client IP of an HTTP request from Go

2019-02-15 09:21发布

问题:

I'm running a gunicorn+flask service in a docker container with Google Container Engine. I set up the cluster following the tutorial at http://kubernetes.io/docs/hellonode/

The REMOTE_ADDR environmental variable always contains an internal address in the Kubernetes cluster. What I was looking for is HTTP_X_FORWARDED_FOR but it's missing from the request headers. Is it possible to configure the service to retain the external client ip in the requests?

回答1:

I assume you set up your service by setting the service's type to LoadBalancer? It's an unfortunate limitation of the way incoming network-load-balanced packets are routed through Kubernetes right now that the client IP gets lost.

Instead of using the service's LoadBalancer type, you could set up an Ingress object to integrate your service with a Google Cloud HTTP(s) Load Balancer, which will add the X-Forwarded-For header to incoming requests.



回答2:

If anyone gets stuck on this there is a better approach. You can use the following annotations depending on your kubernetes version:

service.spec.externalTrafficPolicy: Local 

on 1.7

or

service.beta.kubernetes.io/external-traffic: OnlyLocal

on 1.5-1.6

before this is not supported

source: https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/

note that there are caveats: https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#caveats-and-limitations-when-preserving-source-ips