Nginx背后是Traefik Docker Swarm模式真正的ip

我在Docker swarm环境中使用Traefik作为nginx服务前的反向代理.这是我的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"

一切正常但我需要在我的Nginx访问日志中使用真正的客户端IP,而不是像10.0.1.37那样

我怎么能真正的客户端IP?

谢谢,

解决方法:

这个问题在github #614讨论过.

When the upstream service receives requests forwarded from Traefik, the X-Forwarded-For header contains an IP address from the overlay network, not the actual client address.

要克服这个问题,您可以使用declaring service ports in docker-compose >=3.2 (LONG SYNTAX)的新方法.

然后确保traefik连接到主机网络并发送正确的X-Forwarded-For标头(参见下面的模式:80端口的主机):

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

最后,您必须更改http {}部分中的nginx log_format.这可以通过nginx.conf配置文件的卷绑定来完成:

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

你有这个nginx.conf:

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

在AWS ec2上测试,traefik_nginx服务(我称之为我的堆栈traefik)记录如下:

$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"
上一篇:kubernetes集群traefik ingress实现同一命名空间不同微服务模块的访问


下一篇:traefik添加多证书