Cuối bài trước ba Pod TaskFlow API đã chạy ổn định qua nhiều lần rolling update, nhưng mỗi lần như vậy các Pod đều mang IP mới. Bài này mình sẽ giới thiệu với mọi người về Service trong Kubernetes: một địa chỉ cố định đứng trước nhóm Pod, tự cập nhật khi Pod đến và đi. Bài dùng lại cụm taskflow, namespace mặc định taskflow và Deployment taskflow-api.
1. Vì sao cần Service?
Mỗi Pod có một IP riêng trong mạng của cụm, nhưng IP đó sống và chết theo Pod. Ba Pod của Deployment đang có IP 10.244.1.2, 10.244.2.2, 10.244.1.3; xóa cả ba rồi để Deployment tạo lại là thấy ngay:
kubectl delete pod -l app.kubernetes.io/name=taskflow-api --wait=false
# ...
kubectl get pods -o wide
# NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
# taskflow-api-6f85c99cdf-b7ks8 1/1 Running 0 6s 10.244.1.4 taskflow-worker <none> <none>
# taskflow-api-6f85c99cdf-qt46j 1/1 Running 0 6s 10.244.2.3 taskflow-worker2 <none> <none>
# taskflow-api-6f85c99cdf-wb9fz 1/1 Running 0 6s 10.244.2.4 taskflow-worker2 <none> <none>
Ba IP cũ biến mất. Rolling update, scale hay node hỏng cũng vậy, nên không ai nên ghi cứng IP Pod. Trong Docker, container gọi nhau bằng tên nhờ DNS của user-defined network (bài network trong Docker); Kubernetes giải quyết việc này bằng Service.
Service là một resource cho một nhóm Pod một IP ảo và một tên DNS cố định. Nhóm Pod được chọn bằng label selector, và request gửi tới Service được chia cho các Pod đang sẵn sàng trong nhóm.
client (Pod khác)
|
| http://taskflow-api → 10.96.227.157:80 (IP ảo, không đổi)
v
Service taskflow-api selector: name=taskflow-api, component=api
|
+--> 10.244.1.4:8080 Pod taskflow-api-...-b7ks8
+--> 10.244.2.3:8080 Pod taskflow-api-...-qt46j
+--> 10.244.2.4:8080 Pod taskflow-api-...-wb9fz
2. Service ClusterIP cho TaskFlow API.
Service đầu tiên của project, loại ClusterIP (chỉ gọi được từ bên trong cụm):
apiVersion: v1
kind: Service
metadata:
name: taskflow-api
namespace: taskflow
labels:
app.kubernetes.io/name: taskflow-api
app.kubernetes.io/component: api
app.kubernetes.io/part-of: taskflow
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: taskflow-api
app.kubernetes.io/component: api
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
Trong đó:
apiVersion: v1: Service thuộc core group như Pod.type: ClusterIPlà mặc định, ghi ra cho rõ (các loại khác ở phần 7).selector: mọi Pod trong namespacetaskflowmang đủ hai label này là đích của Service. Selector của Service chỉ hỗ trợ dạngmatchLabelsrút gọn như trên, không cómatchExpressions.port: 80: port của Service, client gọihttp://taskflow-apilà đủ, không cần nhớ 8080.targetPort: http: port trên Pod, ở đây tham chiếu theo tên tớicontainerPortmangname: http. Ghi số8080cũng chạy.
Selector giống selector của Deployment, chỉ gồm name và component như đã giải thích ở Bài 9: có thêm version thì lúc rolling update Pod bản mới không nhận traffic. Service không quan tâm Pod do ai tạo, Pod nào khớp label cũng nhận request (lý do Bài 9 xóa pod-debug.yaml).
containerPort trong k8s/deployment.yaml đã mang name: http từ Bài 6, nên file Deployment không cần sửa. Nhờ tên, ứng dụng đổi port thì chỉ sửa containerPort, Service giữ nguyên, và lúc rolling update Pod cũ lẫn Pod mới đều nhận traffic đúng port của mình.
kubectl apply -f k8s/service.yaml
# service/taskflow-api created
kubectl get service taskflow-api -o wide
# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
# taskflow-api ClusterIP 10.96.227.157 <none> 80/TCP 0s app.kubernetes.io/component=api,app.kubernetes.io/name=taskflow-api
CLUSTER-IP được cấp từ dải riêng cho Service (kubectl get servicecidr cho thấy cụm kind dùng 10.96.0.0/16), tách biệt với dải IP Pod 10.244.0.0/16. IP này giữ nguyên tới khi xóa Service. kubectl describe service taskflow-api có thêm dòng Endpoints: 10.244.2.3:8080,10.244.2.4:8080,10.244.1.4:8080, đúng IP:port của ba Pod hiện tại. svc là tên tắt của services.
3. Gọi Service từ bên trong cụm.
ClusterIP chỉ có nghĩa bên trong cụm, nên mình chạy một Pod tạm bằng image busybox để gọi thử. --rm -it gắn terminal vào Pod và xóa nó khi lệnh kết thúc:
kubectl run tmp --rm -it --image=busybox:1.37 -- wget -qO- http://taskflow-api/health
# ok
# ...
# pod "tmp" deleted from taskflow namespace
ok là body của /health, các dòng lược đi là thông báo của kubectl run. Pod tmp nằm cùng namespace taskflow nên gọi được bằng tên ngắn taskflow-api; tên đầy đủ taskflow-api.taskflow.svc.cluster.local, gọi sang namespace khác và CoreDNS là nội dung Bài 12. Gọi thẳng http://10.96.227.157/ready cũng ra ok.
4. EndpointSlice: danh sách Pod phía sau Service.
Service không tự giữ danh sách Pod. EndpointSlice controller trong control plane theo dõi Pod khớp selector và ghi IP của chúng vào các EndpointSlice, mỗi slice chứa tối đa 100 endpoint. Slice của một Service mang label kubernetes.io/service-name:
kubectl get endpointslices -l kubernetes.io/service-name=taskflow-api
# NAME ADDRESSTYPE PORTS ENDPOINTS AGE
# taskflow-api-d2gvk IPv4 8080 10.244.2.3,10.244.2.4,10.244.1.4 0s
kubectl get endpointslices -l kubernetes.io/service-name=taskflow-api -o yaml
# ...
# endpoints:
# - addresses:
# - 10.244.2.3
# conditions:
# ready: true
# serving: true
# terminating: false
# nodeName: taskflow-worker2
# targetRef:
# kind: Pod
# name: taskflow-api-6f85c99cdf-qt46j
# ...
Mỗi endpoint có IP, node, Pod nguồn và ba trạng thái ready, serving, terminating. Port http đã được dịch thành số 8080, và slice có ownerReferences trỏ về Service. Resource cũ Endpoints vẫn đọc được nhưng kubectl get endpoints in cảnh báo v1 Endpoints is deprecated in v1.33+; use discovery.k8s.io/v1 EndpointSlice.
5. Traffic được chia như thế nào?
ClusterIP không gắn vào card mạng nào. Trên mỗi node, kube-proxy (DaemonSet ở kube-system, đã gặp ở Bài 2) đọc Service và EndpointSlice rồi viết luật cho kernel: gói tin tới 10.96.227.157:80 được đổi đích (DNAT) sang IP:port của một Pod. Trên Linux, kube-proxy có chế độ iptables (mặc định) và nftables (GA từ 1.33, nhanh hơn khi cụm có rất nhiều Service). Cụm kind của chúng ta dùng iptables: ConfigMap kube-proxy ghi mode: iptables và log của nó có dòng "Using iptables Proxier". Xem luật trên node taskflow-worker (node kind là container nên dùng docker exec):
docker exec taskflow-worker iptables -t nat -S KUBE-SVC-TU646RS4HFA45MCY
# ...
# -A KUBE-SVC-TU646RS4HFA45MCY -m comment --comment "taskflow/taskflow-api:http -> 10.244.1.4:8080" -m statistic --mode random --probability 0.33333333349 -j KUBE-SEP-MF3EVFM5NOUQAEAK
# -A KUBE-SVC-TU646RS4HFA45MCY -m comment --comment "taskflow/taskflow-api:http -> 10.244.2.3:8080" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-TRJJ6XZWYIUQ4W35
# -A KUBE-SVC-TU646RS4HFA45MCY -m comment --comment "taskflow/taskflow-api:http -> 10.244.2.4:8080" -j KUBE-SEP-TTDXKYUNOCTVOFAZ
Tên chain lấy từ luật KUBE-SERVICES khớp 10.96.227.157/32. Ba luật chọn ngẫu nhiên: 1/3 vào Pod thứ nhất, phần còn lại chia đôi cho hai Pod sau, tức mỗi Pod 1/3. Việc chọn diễn ra một lần cho mỗi kết nối TCP chứ không phải mỗi request: client giữ kết nối keep-alive (hay gRPC, Bài 21) sẽ dính một Pod suốt kết nối đó.
Gửi 30 request, mỗi lần wget mở một kết nối mới, rồi đếm theo log request của TaskFlow API (--tail=-1 vì kubectl logs -l mặc định chỉ lấy 10 dòng mỗi Pod):
kubectl run tmp --rm -it --restart=Never --image=busybox:1.37 -- sh -c 'for i in $(seq 30); do wget -qO /dev/null http://taskflow-api/health; done; echo xong'
# ...
# xong
# ...
kubectl logs -l app.kubernetes.io/name=taskflow-api --prefix --tail=-1 --since=1m | grep path=/health | cut -d/ -f2 | sort | uniq -c
# 8 taskflow-api-6f85c99cdf-b7ks8
# 13 taskflow-api-6f85c99cdf-qt46j
# 9 taskflow-api-6f85c99cdf-wb9fz
Gần đều nhưng không tròn 10, đúng với cách chọn ngẫu nhiên. Muốn mọi kết nối từ một client vào cùng một Pod thì đặt sessionAffinity: ClientIP (mặc định None; giữ 10800 giây, chỉnh bằng sessionAffinityConfig). TaskFlow API dùng JWT, không giữ session trong bộ nhớ nên không cần.
6. Endpoint thay đổi theo Pod.
Scale và theo dõi endpoint
EndpointSlice được cập nhật mỗi khi Pod đến và đi. Mở một terminal theo dõi slice, chỉ lấy IP và hai trạng thái ready, terminating của từng endpoint:
kubectl get endpointslices -l kubernetes.io/service-name=taskflow-api -w -o custom-columns='IP:.endpoints[*].addresses[0],READY:.endpoints[*].conditions.ready,TERM:.endpoints[*].conditions.terminating'
Terminal kia chạy kubectl scale deployment taskflow-api --replicas=5, đợi Pod chạy rồi kubectl apply -f k8s/deployment.yaml để về 3 (như Bài 9). Terminal theo dõi in ra (IP hơi khác phần trên vì mình đã scale thử một lần trước đó):
# IP READY TERM
# 10.244.2.4,10.244.1.4,10.244.1.13 true,true,true false,false,false
# 10.244.2.4,10.244.1.4,10.244.1.13,10.244.2.9 true,true,true,true false,false,false,false
# 10.244.2.4,10.244.1.4,10.244.1.13,10.244.2.9,10.244.2.8 true,true,true,true,true false,false,false,false,false
# 10.244.2.4,10.244.1.4,10.244.1.13,10.244.2.9,10.244.2.8 true,true,true,false,false false,false,false,true,true
# 10.244.2.4,10.244.1.4,10.244.1.13,10.244.2.9 true,true,true,false false,false,false,true
# 10.244.2.4,10.244.1.4,10.244.1.13 true,true,true false,false,false
Hai Pod mới vào slice ngay khi chạy. Lúc về 3, hai Pod bị xóa không biến mất ngay mà chuyển sang ready: false, terminating: true, nên không nhận request mới trong lúc dừng, rồi mới rời slice. ClusterIP thì không đổi suốt quá trình, client không cần biết gì.
Pod chưa sẵn sàng thì không nhận traffic
Service chỉ chuyển request tới endpoint ready: true, tức là Pod có condition Ready. Pod của chúng ta chưa có readiness probe nên chạy là Ready ngay (Bài 10 đã lưu ý). Để thấy trường hợp ngược lại, mình tạo một Pod lẻ mang label của TaskFlow API, có readiness probe cố tình gọi đường dẫn không tồn tại (file pod-chua-san-sang.yaml ngoài repo; probe học kỹ ở Bài 15):
readinessProbe:
httpGet:
path: /khong-co
port: http
kubectl apply -f pod-chua-san-sang.yaml
# pod/taskflow-api-chua-san-sang created
kubectl get endpointslices -l kubernetes.io/service-name=taskflow-api -o custom-columns='IP:.endpoints[*].addresses[0],READY:.endpoints[*].conditions.ready'
# IP READY
# 10.244.2.4,10.244.1.4,10.244.1.13,10.244.2.6 true,true,true,false
Pod lẻ chạy nhưng kubectl get pods hiện 0/1; nó có mặt trong slice với ready: false nên kube-proxy bỏ qua. Gửi 30 request như phần 5 thì tất cả rơi vào ba Pod 1/1, log của Pod lẻ chỉ có các lần probe nhận 404. Bài 15 dựa vào chính cơ chế này. Xóa Pod lẻ bằng kubectl delete -f pod-chua-san-sang.yaml.
7. Các loại Service.
spec.type quyết định Service được gọi từ đâu. Các loại sau xây chồng lên nhau: NodePort có cả ClusterIP, LoadBalancer có cả NodePort.
ClusterIP
Loại mặc định, chỉ gọi được từ trong cụm. Đây là loại dùng cho giao tiếp giữa các thành phần: api gọi notifier, api gọi PostgreSQL, Redis. Project chỉ giữ Service ClusterIP; đưa TaskFlow API ra ngoài là việc của Gateway API ở Bài 17.
NodePort
NodePort mở thêm một port (dải mặc định 30000–32767) trên mọi node, gói tin tới IP-node:nodePort được chuyển vào Service. Cụm kind ở Bài 3 đã map 127.0.0.1:8080 của máy vào port 30080 của node control-plane, nên một Service NodePort dùng nodePort: 30080 sẽ gọi được từ máy mình. Port này dành cho Gateway ở Bài 17, nên mình chỉ mượn tạm rồi xóa ngay, file để ngoài repo:
File service-nodeport.yaml giống k8s/service.yaml, chỉ khác tên taskflow-api-nodeport và phần sau:
spec:
type: NodePort
# selector giữ nguyên
ports:
- name: http
port: 80
targetPort: http
nodePort: 30080
kubectl apply -f service-nodeport.yaml
# service/taskflow-api-nodeport created
kubectl get service taskflow-api-nodeport
# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
# taskflow-api-nodeport NodePort 10.96.52.190 <none> 80:30080/TCP 6s
curl -sS -m 5 http://localhost:8080/health
# ok
kubectl delete -f service-nodeport.yaml
# service "taskflow-api-nodeport" deleted from taskflow namespace
curl -sS -m 5 http://localhost:8080/health
# curl: (52) Empty reply from server
80:30080 là port Service 80, NodePort 30080. Request vào node control-plane rồi qua luật kube-proxy tới Pod trên worker: NodePort mở trên mọi node, kể cả node không chạy Pod. Bỏ trống nodePort thì Kubernetes tự chọn trong dải. Vừa apply mà curl báo Empty reply thì chờ vài giây cho kube-proxy viết xong luật.
NodePort ít khi đưa thẳng cho người dùng (port lạ, phải biết IP node); nó thường là tầng dưới của load balancer hay Gateway, đúng như Bài 17 sẽ dùng port 30080.
LoadBalancer
Trên cloud (EKS, GKE, AKS...), Service type: LoadBalancer khiến cloud controller tạo một load balancer thật có IP công khai, trỏ vào NodePort của các node. kind không có cloud controller (file service-lb.yaml khác file trên ở tên, type và không có nodePort):
kubectl apply -f service-lb.yaml
# service/taskflow-api-lb created
kubectl get service taskflow-api-lb
# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
# taskflow-api-lb LoadBalancer 10.96.231.150 <pending> 80:31038/TCP 10s
EXTERNAL-IP đứng ở <pending> mãi, NodePort 31038 được tự chọn; xem xong thì kubectl delete -f service-lb.yaml. Muốn LoadBalancer chạy trên kind thì cài cloud-provider-kind; cụm bare metal hay VPS thì dùng MetalLB, còn k3s ở Bài 31 có sẵn ServiceLB. Trên cloud mỗi Service LoadBalancer là một load balancer tính tiền riêng, nên nhiều ứng dụng thường đi chung một Gateway.
ExternalName và headless
ExternalName không chọn Pod, chỉ là một bí danh DNS (CNAME) trỏ ra tên bên ngoài cụm. Service email-api với spec gồm type: ExternalName và externalName: api.sendgrid.com hiện trong kubectl get service với CLUSTER-IP <none> và EXTERNAL-IP api.sendgrid.com. Ứng dụng gọi email-api, đổi nhà cung cấp chỉ cần sửa Service. kube-proxy không tham gia, và với HTTPS chứng chỉ vẫn phải khớp tên thật.
Service headless là Service đặt clusterIP: None: không có IP ảo, không có kube-proxy chia tải, tên DNS trả thẳng về IP của từng Pod. Nó cần cho StatefulSet, nơi mỗi Pod PostgreSQL phải có tên riêng. Bài 12 xem DNS của headless Service, Bài 19 dùng nó cho postgres.
8. Truy cập Service từ máy với port-forward.
Lúc phát triển, cách nhanh nhất để gọi một Service ClusterIP từ máy là kubectl port-forward như Bài 6, nhưng trỏ vào Service:
kubectl port-forward svc/taskflow-api 8081:80
# Forwarding from 127.0.0.1:8081 -> 8080
# Forwarding from [::1]:8081 -> 8080
Terminal khác gọi curl -sS http://localhost:8081/health nhận ok (8081 vì 8080 đã dành cho cụm kind). Dòng 8081 -> 8080 cho thấy kubectl dịch port Service 80 thành port Pod: port-forward chọn một Pod sau Service rồi nối thẳng vào đó, không qua kube-proxy. Ba request mình gửi đều vào Pod b7ks8 (log ghi client_ip=127.0.0.1), Pod đó chết thì port-forward dừng, nên nó chỉ dùng để debug.
Cuối bài, thư mục k8s/ có namespace.yaml, deployment.yaml và service.yaml; trên cụm chỉ còn Service taskflow-api loại ClusterIP. Các bạn có thể xem thêm về Service tại đây, và về các chế độ của kube-proxy tại đây.
Code đầy đủ của series sau bài này nằm ở tag bai-11 trên GitHub; các thay đổi của riêng bài này: so sánh bai-10...bai-11.
9. Lời kết.
Như vậy mình đã giới thiệu với mọi người về Service trong Kubernetes: IP ảo và tên cố định trước nhóm Pod, selector theo label, targetPort theo tên, EndpointSlice và trạng thái ready, kube-proxy chia kết nối bằng iptables, các loại ClusterIP, NodePort, LoadBalancer, ExternalName và port-forward. Pod tmp gọi được http://taskflow-api mà chưa rõ tên đó được phân giải ra sao. Bài sau chúng ta sẽ tìm hiểu DNS và service discovery trong Kubernetes: CoreDNS, tên đầy đủ của Service và headless Service.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments