1. 程式人生 > 其它 >修改nginx-ingress https重定向時的埠號

修改nginx-ingress https重定向時的埠號

問題

k8s叢集通過ingress-nginx暴露前端門戶。

在預設情況下ingress controller使用了80和443這一組慣用埠,因此當ingress中配置了nginx.ingress.kubernetes.io/ssl-redirect時,訪問http://url時會自動重定向至https://url,無需關心埠問題。

當部署ingress controller時443對應的hostPort由於種種原因不能使用443時,如果不進行額外的配置,redirect目標還是443埠,無法正常訪問。

解決

經過google並檢視ingress-nginx的程式碼,發現一個annotation:

nginx.ingress.kubernetes.io/use-port-in-redirects: true

該annotation可以在重定向時加入非標準的埠號。

於是在應用的前端頁面ingress中加入了該annotation,但是發現重定向後還是443埠。

此時發現遺漏了一個問題:annotation裡的user port,到底是use哪個port呢?經過測試,答案是ingress-controller自身的監聽埠。(從實現的角度想,這也是最為直接的方案;延展思考這裡是不是可以實現通過k8s的downward api把hostPort資訊傳進容器,直接重定向至hostPort?)

綜上,ingress-controller修改ssl重定向埠的方法如下:

  1. daemonset/deployment的yaml裡修改容器args,增加引數--https-port=8443
  2. daemonset/deployment的yaml裡相應地修改容器的containerPort
  3. 如果需要對整個叢集的所有ingress重定向時加上非標準埠,則可以在ingress-controller名稱空間的ingress-nginx configmap中增加use-port-in-redirects: "true"
  4. 如果僅需要對某個ingress重定向時加非標準埠,則只需要在特定的ingress檔案中加入annotation:nginx.ingress.kubernetes.io/use-port-in-redirects: true

參考

Path redirection appends port after the hostname · Issue #5222 · kubernetes/ingress-nginx (github.com)

k8s筆記——NodePort暴露nginx-controller實現https自動跳轉自定義nodePort埠 - a1010 - 部落格園 (cnblogs.com)