2

I have a Flask website running inside of a docker container. I would like to display the user's ip address to them, however it currently displays the IP address of the docker container, probably due to it being forwarded from docker. I retrieve the IP address using Flask's requests module.

It shouldn't make a difference, but I am using docker-compose.

version: '2'
services:
  web:
    build: .
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: "redis:alpine"

This is the code for the website using Flask:

from flask import Flask, request
from redis import Redis

app = Flask(__name__)
redis = Redis(host='redis', port=6379)

@app.route('/')
def hello():
    count = redis.incr('hits')
    return 'Your IP is: {0}. I have been visited {1} times and \'foo\' is set to {2}.\n'.format(request.remote_addr,count, redis.get('foo').decode('utf-8'))

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

I know that Nginx gives the request a header with the ip address before it was forwarded that you can use. Does Docker have anything similar that I can use or is there another approach. Get IP address of visitors using Python + Flask

Example of current behavior: example

Thank You.

Doseph
  • 199
  • 3
  • 17
  • Do you mean their external IP? Like using [ipify](http://api.ipify.org)? – tadman Jul 22 '17 at 23:20
  • Yes, like using ipify, although I could use their API I'd still be interested in doing it myself. – Doseph Jul 22 '17 at 23:26
  • I wanted to do it myself, to learn about docker – Doseph Jul 22 '17 at 23:28
  • You need an external service to give you that information. There's no other way to determine it. So you can either make your own ipify-type service, or just use that one. It's impossible to observe from the inside what your IP is, there's always too many layers of NAT in the way. – tadman Jul 22 '17 at 23:31
  • That's a shame. Thanks for the help though. – Doseph Jul 22 '17 at 23:34
  • How is this deployed? You may be able to get the IP. How are you configuring NGINX? – Sam H. Jul 23 '17 at 19:15

1 Answers1

5

I disagree with the comments. Depending on how much of the deployment you are in control of this is doable. You should add something like the following to the NGINX config:

      location / {
          proxy_pass  http://web;
          proxy_set_header   Connection "";
          proxy_http_version 1.1;
          proxy_set_header        Host            $host;
          proxy_set_header        X-Real-IP       $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }
Sam H.
  • 4,091
  • 3
  • 26
  • 34