利用Nginx做端口转发
需求
支持访问http://localhost和https://localhost,把80和443端口都转发到Nginx server,通过Nginx server再转发给Rails App的3000端口。
解决
首先搭建一个F5的load balance,把所有的request都转发到8680端口。
再搭建一个Nginx server,监听8086端口,把所有的request都转发到3000端口。正常情况下,Nginx server一般都是80端口,这里只是避免和本地80端口冲突,故用了8680端口。
此外,这个Nginx server有些鸡肋,本来就可以直接把F5转发到3000端口的,但是一般Rails都是搭配Nginx的,就单纯再模拟一次Nginx。
步骤
创建在主机上面创建self-trusted cert,放到tmp/ssl目录下
openssl req -x509 -sha256 -nodes -newkey rsa:2048 \-days 365 -keyout localhost.key -out localhost.crt
接着创建docker-compose.yml 文件和相关nginx配置文件。
docker-compose.yml
version: '2'services:f5:image: nginx:latestvolumes:./tmp/nginx/f5_https_pool.conf:/etc/nginx/conf.d/f5_https_pool.conf./tmp/nginx/f5_http_pool.conf:/etc/nginx/conf.d/default.conf./tmp/ssl:/etc/nginx/sslports:80:80443:443nginx:image: nginx:latestvolumes:./tmp/nginx/nginx_server.conf:/etc/nginx/conf.d/default.confports:8680:8680
tmp/nginx/nginx_server.conf
upstream rails {server host.docker.internal:3000;}server {listen 8680 default_server;server_name localhost;location / {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;proxy_redirect off;proxy_pass http://rails;}}
tmp/nginx/f5_http_pool.conf
upstream nginx_server {server host.docker.internal:8680;}server {listen 80;server_name localhost;# return 301 https://$host$request_uri;location / {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-Forwarded-Proto http;proxy_redirect off;proxy_pass http://nginx_server;}}
tmp/nginx/f5_https_pool.conf
server {listen 443 ssl default_server;server_name localhost;ssl_certificate /etc/nginx/ssl/localhost.crt;ssl_certificate_key /etc/nginx/ssl/localhost.key;ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";location / {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-Forwarded-Proto https;proxy_redirect off;proxy_pass http://nginx_server;}}
最后,执行docker-compose up,试试访问http://localhost和https://localhost吧。
