I host an node.js server with express.js in a docker container. The address of my container is 172.17.0.62 And I use nginx to redirect the traffic to 172.17.0.62
I can access the my server. But when I use
console.log(req.ip + ' ' + req.protocol + ' ' + req.originalUrl);
to log the traffic. req.ip is always 172.17.42.1. I want to get the ip of viewer of my webpage
I use this in my nginx configuration
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
and
cat /proc/sys/net/ipv4/ip_forward # output 1
I haven't used docker - but you should be able to get the information you want from x-forwarded-for: Express.js: how to get remote client address
From the above link:
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
Oh and interesting to note - a second answer in the above thread might actually be superior for your needs. Instead of changing your code everywhere that gets tries to get the user's ip address. You can just change how you initialize express:
app.enable('trust proxy');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With