Oh My Iron man post - day eight
Oh my K8s service ! 談談如何暴露你的服務 - 2
- 目錄
- Introduce K8s service - Kube-proxy
- 💎 Introduce K8s service - 4 ways to apply service(1) 💎
- Introduce K8s service - 4 ways to apply service(2)
- Service Comparison & Introduce Ingress
- Service Debugging
- How to install Traefik
- Nginx-ingress vs Traefik
昨天簡單介紹完Service的背後元件kube-proxy的運作原理,今天要來看看Service的類型以及背後原理有什麼不一樣。
Service yaml長什麼樣子?
大概長這樣,type有四種可以自己填。
- ClusterIP
- NodePort
- LoadBalancer
- ExternalName
1 | apiVersion: v1 |
什麼是 Selector?
在Service deployment裡面可以找到一個叫做Selector的標籤, 根據官網文件,K8s會掃描所有Pods, 並指派一個VIP(Virtual IP),指到跟這個Selector名字匹配的Pods。

那如果不加Selector呢?
根據官方文件在以下兩種情況, 你會選擇不使用Selector去指定你要的Pods:
- 你使用的是在Cluster以外的Backend Service
- 你要指定的Service位在其他的namespace上
如果不使用Selector, 就必須自己指定IP + port,建立endpoint resource object, 但有幾點注意事項在官方文件上,這邊就不贅述了。
Service type
Service 總共有四種 types:
- ClusterIP
- NodePort
- LoadBalancer
- ExternalName
Cluster IP
預設的type, 沒有在service的yaml檔宣告任何type的話, K8s會給透過kube-proxy該service一組cluster IP, 這個ip只有在cluster裡面才能ping的到。
如果cluster IP沒辦法被ping到,就要檢查看看是不是endpoint沒有被設定
這種就是沒有被設定endpoint的service,原因是因為對應不到後面的pods。
一個或一堆pods在運行的時候,K8s其中的一個components Kubelet會啟動兩種probes(探針)來偵測pods是否運行正常:
- livenessProbe:偵測Pod是否運行中,如果probe結果失敗,kubelet會kill該Pod,後續該Pod會根據對應的重啟策略(restart policy)定義而重啟。
- readinessProbe:顯示Pod是否已經準備好可提供服務,如果Probe失敗,將會從Endpints 中刪除該Pod的資訊。
而只有 readinessProbe 檢查通過的Pods, 才會出現在Endpoints列表。所以這個Pods如果被users砍掉或是啟動失敗, services就會對應不到Pods。
Node port
簡單來說,就是在主機的iptables加開port, 讓服務可以透過這個port來serve request。
假設我們的cluster裡面已經有了一個nginx的deployment,就寫一個service yaml file, 記得selector要和該deployment的labels符合。
my-nginx-service.yaml
1 | apiVersion: v1 |
這份yaml file的意思是說我要將nginx1-7這個deployment指到的pods裡面container的port 80開出來給人連線,並且這個service名字就叫做my-nginx-service。
如果nodePort沒有被指定的話, K8s就會隨機分配30000 ~ 32767的ports給你, 這個預設範圍可以透過修改kube-apiserver這個參數去修改。
1 | kubectl apply my-nginx-service.yaml |
結果:
ssh into node檢查

我是用AWS instance,修改security groups的inbound rule之後就可以透過外部access

明天再介紹剩下兩個類型。
Reference
- k8s service document: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies
- 找到容器不容易 - 張磊:https://book.zouhl.com/fs/%E6%B7%B1%E5%85%A5%E5%89%96%E6%9E%90Kubernetes/37%20%20%E6%89%BE%E5%88%B0%E5%AE%B9%E5%99%A8%E4%B8%8D%E5%AE%B9%E6%98%93%EF%BC%9AService%E3%80%81DNS%E4%B8%8E%E6%9C%8D%E5%8A%A1%E5%8F%91%E7%8E%B0.pdf
- 官方文件 Services: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
- 官方文件 Probes: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
- 官方文件 Kubelet: https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/