在k8s啟用rstudio的時候遇到302轉址的問題

研究k8s也有一段時間了,今天想從k8s上起一個rstudio搭配nginx controller來用用

當我把ingress的path設定成/rstudio的時候,如果我存取http://LB_URL/rstudio

他會回傳一個302 redirect轉址請求把我轉到http://LB_URL/auth-sign-in

原先設定的path跑掉了而出現404錯誤

ingress設定如下

{
  "kind": "Ingress",
  "apiVersion": "extensions/v1beta1",
  "metadata": {
    "annotations": {
      "kubernetes.io/ingress.class": "nginx",
      "nginx.ingress.kubernetes.io/rewrite-target": "/"  
    }
  },
  "spec": {
    "rules": [
      {
        "host": "LB_HOST",
        "http": {
          "paths": [
            {
              "path": "/rstudio",
              "backend": {
                "serviceName": "rstudio",
                "servicePort": 8787
              }
            }
          ]
        }
      }
    ]
  }
}

後來研究了一下這應該是nginx在轉發的時候出的問題

當有設定proxy_set_header Host xxxx的時候,redirect的對象會主動被改成xxxxx

所以需要新增proxy_redirect的設定把他轉回來

以前我在localhost設定nginx的時候設定如下

    location /rstudio/ {
      rewrite ^/rstudio/(.*)$ /$1 break;
      proxy_pass http://localhost:8787;
      proxy_redirect http://localhost:8787/ $scheme://$host/rstudio/;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }

那要怎麼在nginx-controller增加proxy_redirect的設定呢

查了一下官網有nginx.ingress.kubernetes.io/proxy-redirect-fromnginx.ingress.kubernetes.io/proxy-redirect-to可以用

又nginx controller在設定proxy的時候會自動新增一行proxy_set_header Host $best_http_host
得把proxy_redirect的對象改成$best_http_host

查看nginx controller config的方法如下

#查詢nginx controller的pod container名字
$ kubectl get pod -n ingress-nginx

#進入container
$ kubectl exec nginx-ingress-controller-xxxx -n ingress-nginx -i -t -- bash 

#查看config
$ cat etc/nginx/nginx.conf

修改過後的ingress設定如下

{
  "kind": "Ingress",
  "apiVersion": "extensions/v1beta1",
  "metadata": {
    "annotations": {
      "kubernetes.io/ingress.class": "nginx",
      "nginx.ingress.kubernetes.io/proxy-redirect-from": "http://$best_http_host/",
      "nginx.ingress.kubernetes.io/proxy-redirect-to": "$scheme://$host/rstudio/",
      "nginx.ingress.kubernetes.io/rewrite-target": "/"  
    }
  },
  "spec": {
    "rules": [
      {
        "host": "LB_HOST",
        "http": {
          "paths": [
            {
              "path": "/rstudio",
              "backend": {
                "serviceName": "rstudio",
                "servicePort": 8787
              }
            }
          ]
        }
      }
    ]
  }
}
            

這邊做個紀錄

comments powered by Disqus