背景: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; } }