<pre><code>import uvicorn

app = FastAPI()


@app.get(&quot;/items/{item_id}&quot;)

def read_root(item_id: str, request: Request):

    client_host = request.client.host
    f= open(&quot;ipadress.txt&quot;,&quot;a+&quot;)
    f.write(client_host+&quot;\n&quot;)
    f.close()

    return {&quot;client_host&quot;: client_host, &quot;item_id&quot;: item_id}


if __name__ == &quot;__main__&quot;:
    uvicorn.run(app, host=&quot;0.0.0.0&quot;, forwarded_allow_ips=&quot;*&quot;)
</code></pre>
<p>The above is the python code which is hosted using uvicorn. When I run the code inside a docker container, it returns the correct client IP. But, when I host the same code on Kubernetes cluster using minikube the IP address which is returned is the localhost IP (127.0.0.1)</p>
<p>The docker command used to run the above code image is
<code>docker run -it -p 8080:8000 &lt;image-name&gt;</code>
I have exposed port 8080 to reach to the service from Virtual Machine</p>
<p>The kubernetes command used to expose the service is
<code>kubectl port-forward --address 0.0.0.0 services/sample-deploy 8080:80</code></p>
<p>The service.yaml for kubernetes is</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: sample-deploy
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: sample-deploy
</code></pre>
<p>I also tried to access the service using LoadBalancer where the service can be accessed using an External IP yet I am not able to get the real client IP address.
I think the IP address is masked in the kubernetes cluster.</p>

Kavya
<p>When you do a <code>port-forward</code> you create a tunnel from your local machine to the container. So, the connection is seen in the container as if it is coming from the local machine (hence the <code>127.0.0.1</code>). Port forwarding is usually just used for debugging purposes.</p>
<p>The typical way to access your application would be via a service of type <code>LoadBalancer</code> or via the <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/" rel="nofollow noreferrer">Kubernetes ingress</a> concept. In both cases you should get the correct client IP address. For the ingress the client IP is usually provided via a HTTP header (by the ingress load balancer/reverse proxy). Most ingress controllers use <code>X-Forwarded-For</code>. This header is usually picked up by the web app frameworks when checking for the client IP.</p>
