需求:访问 https://tensorboard.liu12.com/train-123/ 时,动态反向代理到 docker swarm 集群中的主机名为 "train-123" 的节点的 tensorboard
首先考虑用 location 正则匹配网址,将匹配的结果用于 proxy_pass(tensorboard 端口号 20060)
server {
listen 80;
server_name tensorboard.liu12.com
location ~ /([^\/]+)/(.+) {
proxy_redirect off;
proxy_set_header Host $host;
proxy_pass http://$1:20060/$2?$args;
break;
}
location ~ /([^\/]+)/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_pass http://$1:20060/?$args;
break;
}
location / {
default_type text/html;
return 200 'tensorboard';
}
}
访问网站时,产生以下错误:
... no resolver defined to resolve ...
这是因为proxy_pass 的主机名中中包含变量时,需要指定DNS服务器
进入到任意一个节点 查看 /etc/resolv.conf,
nameserver 127.0.0.11
options ndots:0
复制 nameserver 的值,在 nginx 配置文件中添加 resolver 配置项,最终配置结果如下:
server {
listen 80;
server_name tensorboard.liu12.com
resolver 127.0.0.11;
location ~ /([^\/]+)/(.+) {
proxy_redirect off;
proxy_set_header Host $host;
proxy_pass http://$1:20060/$2?$args;
break;
}
location ~ /([^\/]+)/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_pass http://$1:20060/?$args;
break;
}
location / {
default_type text/html;
return 200 'tensorboard';
}
}