gpt4 book ai didi

Traefik Docker Swarm 模式真实 ip 背后的 Nginx

转载 作者:行者123 更新时间:2023-12-04 18:02:01 27 4
gpt4 key购买 nike

我在 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 header (见下文 mode: host 用于 80 端口):
version: "3.2"
services:
traefik:
...
ports:
- "8080:8080"
- target: 80
published: 80
protocol: tcp
mode: host
- "443:443"
...

最后,您必须更改 http {} section 中的 nginx log_format .这可以通过 nginx.conf 的卷绑定(bind)来完成。配置文件:
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"

关于Traefik Docker Swarm 模式真实 ip 背后的 Nginx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44639958/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com