使用Flask开发的项目,但部署到线上Docker容器中后,因为使用了Nginx做代理,所以Flask无法获取真实IP地址,获取到的都是192.0.0.1,解决方法如下:

首先是Nginx的配置,需要在转发的请求headers中设置好真实IP

location /path {
	root   html;
	proxy_pass http://127.0.0.1:5000/;
	proxy_set_header X-Real-IP $remote_addr;
}

然后在Flask通过headers获取IP,为了兼容使用nginx不使用nginx的情况,做了一些处理:

ip = request.remote_addr
    try:
        _ip = request.headers["X-Real-IP"]
        if _ip is not None:
            ip = _ip
    except Exception as e:
        print(e)

通过上述代码,就可以获取到真实IP了。