Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js in container always get the docker0 ip

Tags:

docker

nginx

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
like image 507
sundayku Avatar asked Dec 24 '15 17:12

sundayku


1 Answers

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');
like image 136
Tim Avatar answered Nov 15 '22 04:11

Tim