Traefik 在本地机器上获取客户端真实IP

Traefik 在本地机器上获取客户端真实IP

我遇到了一个本地问题,当我在我的在线专用服务器上进行部署以获取客户端的真实 IP 时,这个问题并不存在。

在本地,whoami 服务返回容器的 IP 给我,而不是我自己的私有 IP(192.168.2.9)。

通过在我的专用服务器上部署相同的配置,我可以在日志中获取客户端的真实 IP。

我也在本地测试了添加以下选项:

  • 通过将不安全设置为 True 来设置代理协议。
  • 通过将 insecure 设置为 True 来转发Headers。
  • 可信 IP:127.0.0.1/8、192.0.0.1/8、172.0.0.1/8

以不同方式混合的这些选项都无法让我在本地获取真实 IP。

我坚持这样的特殊性:即使不做这些,使用相同的在线配置,我也拥有客户端的真实 IP,并且本地只有容器 IP,而不是我本地电脑的 IP。(192.168.2.9)

这里是我的配置文件:

traefik.yml

---
global:
  sendAnonymousUsage: "false"
  checkNewVersion: "false"

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: "false"
    watch: "true"
    swarmMode: "false"
  file:
    directory: "/etc/traefik/dynamic"
    watch: "true"
accessLog: {}
api:
  dashboard: "true"
log:
  level: "INFO"
  format: "json"
entryPoints:
  web:
    address: ":80"
    http:
      redirections:
        entryPoint:
          to: "web-tls"
          scheme: "https"
  web-tls:
    address: ":443"

dynamic_traefik.yml

---
http:
  routers:
    http:
      rule: "Host(`traefik.myhome.be`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
      entryPoints: "web"
      service: "api@internal"
      middlewares:
        - "https-dashboard"
    https:
      rule: "Host(`traefik.myhome.be`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
      entryPoints: "web-tls"
      tls: "true"
      service: "api@internal"
      middlewares:
        - "auth"
  
  middlewares:
    https-dashboard:
      redirectScheme:
        permanent: "true"
        scheme: "https"
    auth:
      basicAuth:
        users:
          - "admin:$apr1$IfhjvHv8$YH44Wy783yEghLwkGy9gi1"
tls:
  certificates:
    - certFile: /certificates/myhome.be.rsa.pem
      keyFile: /certificates/myhome.be.rsa.key
    - certFile: /certificates/myhome.be.ecdsa.pem
      keyFile: /certificates/myhome.be.ecdsa.key

docker-compose.yml

version: "3.6"

services:
  traefik:
    image: "poc_traefik:latest"
    container_name: "ge-traefik"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - "/etc/localtime:/etc/localtime:ro"
      - "/etc/timezone:/etc/timezone:ro"
    ports:
      - "80:80"
      - "443:443"
    networks:
      - "network-frontend"
      - "network-backend"
  whoami:
    image: "traefik/whoami:latest"
    container_name: "whoami"
    hostname: "whoami"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.entrypoints=web-tls"
      - "traefik.http.routers.whoami.tls=true"
      - "traefik.http.routers.whoami.rule=Host(`whoami.myhome.be`)"
      - "traefik.http.services.whoami.loadbalancer.server.port=${HTTP}"

有什么解决方案吗?我确实需要真正的客户端 IP 来进行开发。

答案1

问题比较简单,内部从dev站出发,不离开docker网络层,所以只要拿到网关和容器的ip就可以了。

如果我从本地网络上的另一个工作站发出请求,我会得到正确的 IP:)。

相关内容