通过链接的docker容器从nginx到jetty传递正确的ip

我有两个docker容器运行,一个是nginx接受http和https请求,并将它们传递给另一个是docker容器。 自从我切换到docker工人后,我注意到了一个问题。 我无法得到正确的请求IP。 docker应用程序检查请求IP以确保请求来自特定的服务器。 在Servlet中,我使用下面的代码来获取IP:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... String remoteIpAddress = request.getRemoteAddr(); ... } 

但是我得到了IP 172.17.0.x,这似乎是来自docker的IP,而不是来自请求者的预期IP。

我的docker图像运行以下参数:

 docker run -d --read-only --name=jetty -v /tmp -v /run/jetty jetty:9 docker run -d --read-only --name=nginx --link jetty:jetty -v /var/run -p 80:80 -p 443:443 nginx 

重要的部分是 – --link参数,在那里我把docker连接到nginx。

在nginxconfiguration中,我定义了一个代理传递给jetty:

 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

 location / { proxy_pass http://jetty:8080; } 

我的问题是:如何从请求中获得正确的IP,而不是127.17.0.x?

如果使用Jetty 9,请启用ForwardRequestCustomizer

要做到这一点 …

 $ mkdir /path/to/jetty-base/etc $ cp /path/to/jetty-dist/etc/jetty.xml /path/to/jetty-base/etc/ $ edit /path/to/jetty-base/etc/jetty.xml 

取消注释行

  <Call name="addCustomizer"> <Arg><New class="org.eclipse.jetty.server.ForwardedRequestCustomizer"/></Arg> </Call> 

开始您的${jetty.base}

 $ cd /path/to/jetty-base $ java -jar /path/to/jetty-dist/start.jar 

完成

当你做request.getRemoteAddr(); 你得到请求的ip,在这个例子中是运行在docker中的nginx。

您在nginxconfiguration文件中添加的行添加了原始IP的标头,因此您唯一需要做的就是获取X-Real-IP标头