Nginx for Traefik Docker Swarm mode real ip

I am using Traefik as a reverse proxy in front of nginx service in swock-docker environment. Here's my docker-stack.yml:

traefik:
    image: traefik
    command: -c /dev/null --web --docker --docker.swarmmode --docker.watch --docker.domain=domain --logLevel=DEBUG
    ports:
      - "8080:8080"
      - "80:80"
      - "443:443"
    networks:
       - app
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    deploy:
      placement:
        constraints: [node.role == manager]

nginx:
    image: nginx
    networks:
      - app
    deploy:
      labels:
        traefik.port: 80
        traefik.docker.network: app
        traefik.frontend.rule: "Host:app.domain"

      

Everything works fine, but I need the real client IP in my Nginx access log, instead I get something like 10.0.1.37

How do I get the real client ip?

Thank,

+3


source to share


1 answer


This question was discussed on github # 614 .

When the upstream service receives requests sent from Traefik, the header X-Forwarded-For

contains the IP address from the overlay network, not the actual address of the client.

To overcome this, you can use the new way to declare service ports in docker-compose> = 3.2 ( LONG SYNTAX ) .

Then you make sure traefik is connected to the host's network and sends the correct header X-Forwarded-For

(see below mode: host

for port 80):

version: "3.2"
services:
  traefik:
    ...
    ports:
      - "8080:8080"
      - target: 80
        published: 80
        protocol: tcp
        mode: host
      - "443:443"
    ...

      

Finally, you must change the nginx log_format in http {} section

. This can be done by linking the volumes of the config file nginx.conf

:



nginx:
  ..
  volumes:
    - /data/nginx/nginx.conf:/etc/nginx/nginx.conf

      

you will have nginx.conf

with this:

http {
  ...
  log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
  '"$request" $status $body_bytes_sent "$http_referer" '
  '"$http_user_agent"' ;

      

Tested on AWS ec2, service traefik_nginx

(I named my stack traefik

) like this:

$ docker service logs -f traefik_nginx
...
traefik_nginx.1.qpxyjheql5uk@xxx    | 82.253.xxx.xxx - - [20/Jun/2017:08:46:51 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36"

      

+3


source







All Articles