K8s Ingress

什麼是 Ingress ?

使用 Ingress ,我們只需開放一個對外的 port number,Ingress 可以在設定檔中設置不同的路徑,決定要將使用者的請求傳送到哪個 Service 物件
示意圖:沒有 ingress,我們需要開多個 NodePort 給不同 service
notion image
如果用了 ingress,則只需要一個 port 就可以導流去不同的 service
notion image
 
 
 
 
範例:jpetstore
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: jpetstore-ingress namespace: jpetstore spec: ingressClassName: traefik # 請務必看好看仔細 ingress class 的名字 rules: - host: jpetstore.cerana.tech http: paths: - path: / pathType: Prefix backend: service: name: jpetstore-backend-service port: number: 7050 # 這裡放的是 service port
  • rules
    • 代表這個 Ingress 的轉發規則,所有 Ingress 的設定都要寫在 rules 內。
  • host
    • 設定可以連接到 Service 物件的網域名稱。
  • path
    • 設定可以連接到 Service 物件的路徑名稱。
  • pathType
    • Each path in an Ingress is required to have a corresponding path type.
    • ImplementationSpecific: With this path type, matching is up to the IngressClass. Implementations can treat this as a separate pathType or treat it identically to Prefix or Exact path types.
    • Exact: URL 必須完全一致,不然不會吃進去這個參數
    • Prefix: subpath 不完全一樣也可以,給予一定程度的寬限
    • Kind
      Path(s)
      Request path(s)
      Matches?
      Prefix
      /
      (all paths)
      Yes
      Exact
      /foo
      /foo
      Yes
      Exact
      /foo
      /foo/
      No
      Exact
      /foo/
      /foo
      No
      Prefix
      /aaa/bb
      /aaa/bbb
      No
      Prefix
      /aaa/bbb
      /aaa/bbb/ccc
      Yes, matches subpath
      Prefix
      //aaa/aaa/bbb
      /ccc
      Yes, matches / prefix
  • service.name
    • 設定欲連接到的 Service 名稱,這裡要填寫的就是 Service 中在 metadata 內寫上的 name 。
  • service.port
    • 設定要經由哪個 port 連接到 Service 物件,就像 Service 的 port 要連接到 Pod 的 targetPort。
 
🔥
註:service port 如其名,是開在 service 上面的 port 而 node port 也如其名,是開在 node 上面的 port ingress 所做的事情就是統一開一個 80 / 443 port 然後轉接去 service port 再讓 service port 轉去 node port 再轉去 target port(開在 pod 上面的 port) 整體流程: 1. ingress 根據路徑,導流到不同的 service 上面 2. service port 3. node port 4. target port(通常數字會=service port)
 
 

建立 ingress

microk8s kubectl create -f YOUR_INGRESS.yaml
 

重啟 ingress

microk8s kubectl replace -f YOUR_INGRESS.yaml
個人心得:如果重啟後發現結果跟預期不一樣(比方像是 request 打不進去
可以刪除再創造,有機會可以解決你的問題
microk8s kubectl delete ingress YOUR_INGRESS_NAME
microk8s kubectl create -f YOUR_INGRESS.yaml
 

官方範例

apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: name-virtual-host-ingress spec: rules: - host: foo.bar.com http: paths: - pathType: Prefix path: "/" backend: service: name: service1 port: number: 80 - host: bar.foo.com http: paths: - pathType: Prefix path: "/" backend: service: name: service2 port: number: 80