01 - Core Concepts - Services

Services

$ kubectl get service       
$ kubectl get svc            

That is a default service created by Kubernetes at launch.


$ kubectl describe service                       
$ kubectl describe svc <service-name>     




Create a new service to access the web application using the YAML file.

  • Name: webapp-service
  • Type: NodePort
  • targetPort: 8080
  • port: 8080
  • nodePort: 30080
  • selector:
    • name: simple-webapp

$ kubectl create -f service-definition-1.yaml             
```yaml
---
apiVersion: v1
kind: Service
metadata:
  name: webapp-service
  namespace: default
spec:
  ports:
  - nodePort: 30080
    port: 8080
    targetPort: 8080
  selector:
    name: simple-webapp
  type: NodePort
```




補充:Deployment 與 Service 的關係

User → Service → Pod(由 Deployment 管理)

這樣的設計確保了 高可用性(HA)和 auto-scaling,即使 Pod 被刪除或重啟,Service 仍能找到新的 Pod 來處理請求。 

(1)Deployment 是用來創建和管理 Pod

  • 作用:
    • Deployment 負責定義和管理 Pod 的生命週期,確保應用程式可以水平擴展(Scaling)、自動更新(Rolling Update)、自我修復(Self-healing)。
    • 但 Pod 的 IP 會變動,無法直接存取。
  • 內容:
    • Pod Template:定義 Pod 的規格,例如使用的 Container 映像、環境變數、資源限制等。
    • ReplicaSet:確保有指定數量的 Pod 在運行。

(2)Service 用來暴露 Pod,讓外部或內部存取

  • 作用:
    • Pod 可能會頻繁變動(例如:Rolling Update),所以直接存取 Pod IP 不是可靠的方式。
    • Service 透過 Label Selector 來對應 Deployment 創建的 Pod,並提供一個固定的存取點,確保流量能夠正確導向到後端 Pod。
  • 內容:
    • Selector:透過 Label 來綁定對應的 Pod。
    • ClusterIP / NodePort / LoadBalancer:
      • ClusterIP(預設):只能在 Kubernetes 內部存取。
      • NodePort:將 Service 透過每個節點的固定 Port 對外暴露。
      • LoadBalancer:由雲端供應商提供的負載均衡器,適用於雲端環境。

留言