NGINX(Proxy)
で接続元IP(X-Forwarded-For
)を設定します。
オンプロミスで本番環境はBIG-IP
が存在して、検証にはない場合など使えるかもしれません。
検証はdocker-composeで実施します。
設定
http, server, location
ディレクティブにproxy_set_headerで追加するだけです。
nginx.conf
location / {
proxy_set_header X-Forwarded-for $remote_addr; <-----------追加
proxy_pass http://web;
}
$http_x_forwarded_for
はlog_format
にデフォルトで存在するため、上記のみでwebサーバ側のログに出力されるはずです。
$http_x_forwarded_for
が存在しない場合は、下記の様にlog_format
を修正してください。
nginx.conf
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
検証
- コンテナ起動
bash
$ git clone https://github.com/Thirosue/docker-sample.git
$ cd docker-sample/nginx_x_forwarded_forpwd/
$ docker-compose up -d
Creating proxy ... done
Creating proxy ...
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
782e7e485bba nginx:1.13.1-alpine "nginx -g 'daemon of…" Less than a second ago Up 2 seconds 80/tcp web
5e8a5f7c6e59 proxy "nginx -g 'daemon of…" Less than a second ago Up 2 seconds 0.0.0.0:8080->80/tcp proxy
- アクセス
ローカルPCからブラウザで以下に接続
- 確認
proxyサーバの
$remote_addr
がwebサーバの$http_x_forwarded_for
に設定されていることが確認できる
bash
################ proxyサーバの$remote_addrが
$ docker logs proxy
172.20.0.1 - - [16/Jan/2018:06:52:03 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
################ webサーバの$http_x_forwarded_forに設定されていることが確認できる
$ docker logs web
172.20.0.3 - - [16/Jan/2018:06:52:03 +0000] "GET / HTTP/1.0" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "172.20.0.1"