docker内的服务无法获取用户真实IP
背景:MySQL数据库和Redis运行在宿主机上(Linux),server运行在docker内,web运行在Nginx内(Nginx运行在docker内),获取的用户IP为10.0.0.10类似的docker内部IP
需求:获取真实IP
方法:
一、修改Nginx配置文件,docker容器内【/etc/nginx/conf.d/default.conf】
server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/host.access.log main; location / { root /web; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # location /api/ { proxy_pass http://base-framework-server/; #下边是为获取真实IP所做的设置 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect default; } }
二、增加工具类【HttpUtil】
import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; /** * @ClassName HttpUtil * @Description Http工具类 * @Author AAFE(WeChat:xskdjs945) * @Date 2019/11/28 10:19 * @Version 1.0 **/ public class HttpUtil { /** * 获取客户端真实IP * * @param request * @return */ public static String getClientIP(HttpServletRequest request) { // nginx 中需要设置相关配置 String ip = request.getHeader("X-Real-IP"); if (StringUtils.isEmpty(ip)) { ip = request.getRemoteAddr(); } return ip; } }
相关推荐
王道革 2020-11-25
bwyyziq 2020-11-22
pigsmall 2020-11-19
changecan 2020-11-19
helloWorldAndYou 2020-11-16
nginxs 2020-11-14
红石丶 2020-11-13
WanKaShing 2020-11-12
yangkang 2020-11-12
滴水穿石点石成金 2020-11-12
张荣珍 2020-11-12
wuxunanjing 2020-11-11
魅惑青花瓷 2020-11-11
lihongtai 2020-11-09
yangkang 2020-11-09
worldsnow 2020-11-06
MichaelJScofield 2020-11-06
TaoTaoFu 2020-11-06