Docker Swarm get real IP (client host) in Nginx

version: '3.8'
services:
    nginx :
        image: nginx:1.19.1
        environment:
            #- TZ=UTC
            - TZ=Asia/Shanghai
        ports:
            - 22:22
            - 80:80
            - 443:443
        volumes:
            - ./conf/nginx.conf:/etc/nginx/nginx.conf
            - ./conf.d:/etc/nginx/conf.d/
            - /data/nginx/nginx-data/logs:/var/log/nginx/
            - /data/nginx/nginx-data/run:/run/
            - /data/nginx/nginx-data/proxy_temp:/usr/local/nginx/proxy_temp
        extra_hosts:
            - "f-w-1.iot.xingfuture.com:172.17.229.53"
            - "f-w-1.cashier.xingfuture.com:172.17.229.53"
            - "f-w-1.open-api-gateway.xingfuture.com:172.17.229.53"
        dns:
            - 172.17.229.51
            # - 255.5.5.5
        #deploy:
            #mode: replicated
            #replicas: 1

获取到的 IP 地址是 10.0.0.2,而非客户端真实 IP


解决方案

ports:
    - target: 22
      published: 22
      protocol: tcp
      mode: host
    - target: 80
      published: 80
      protocol: tcp
      mode: host
    - target: 443
      published: 443
      protocol: tcp
      mode: host
  • http://www.cocoachina.com/articles/42296
  • https://docs.docker.com/compose/compose-file/#ports