2020-08-31|閱讀時間 ‧ 約 5 分鐘

透過K8S Ingress 和 NodePort service直接連線Pod中的App

上一篇介紹如何將Docker image部屬到Minikube,由於Pod 使用的是 K8S內部的 IP,無法從外部直接連線,所以是用minikube ssh來做測試,但是在真實環境中,總是要能有url可以直接連線到app,因此這邊可以使用k8s的Service。
建立一個監聽5001 port 的 NodePort Service hello-world,將連線導向pod的5000 port:
$ kubectl expose pod hello-world --port=5001 --target-port=5000 --type=NodePort
取得 service 的對外k8s node ip 和 port:
$ minikube service hello-world --url
#NodePort 模式下,Service 的port會對應到 k8s node上的port,所以只要得到k8s node的 IP 和port,就可以從node外部直接連線到 Service。
#Note:
刪除service:
$ kubectl delete svc hello-world
取得services:
$ kubectl get services
到這邊已經可以直接從外部ip連到k8s內部的app了,但是用ip來記是不是很不方便呢? 這邊可以使用k8s的ingress元件,先啟用:
$ minikube addons enable ingress
Ingress需要撰寫yaml檔來做設定,以 minikube 內建的 Nginx Ingress 為例,建立一個hello-world-ingress.yaml:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: vic-example
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - host: hello.world.minikube
    http:
      paths:
      - path: /(.*|$)
        backend:
          serviceName: hello-world
          servicePort: 5001
其中host是對外的domain name,有點類似在設定apache的server name,設定好申請的domain即可從外部直接連線過來。 serviceName跟servicePort則填寫上面建立好的Service。 建立一個名為vic-example的Ingress:
$ kubectl apply -f hello-world-ingress.yaml
查看Ingress:
$ kubectl get ingress
由於這只是範例,並不是真的有hello.world.minikube這個domain name,因此為了模擬測試,可以在/etc/hosts中加入host ip mapping:
$ sudo nano /etc/hosts
測試:
到這邊為止,就可以透過好記的url來連線到開發的app了呢!
#Note:
刪除Ingress:
$ kubectl delete ingress vic-example
分享至
成為作者繼續創作的動力吧!
小弟是一位軟體工程師,樂於幫助他人,撰寫技術文章除了幫助自己複習以外,也希望可以幫助到他人,若文章內容有誤,還請大大不吝給予指教!
© 2024 vocus All rights reserved.