Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 29: Debug ứng dụng trên Kubernetes

Bài trước khép lại phần bảo mật, và cũng thêm vào cụm mấy kiểu lỗi mới: Pod bị Pod Security từ chối, kết nối bị NetworkPolicy chặn, image distroless không có shell để exec vào. Bài này mình sẽ giới thiệu với mọi người về debug ứng dụng trên Kubernetes: một quy trình đi từ get tới mạng, rồi lần lượt tạo ra từng lỗi hay gặp, đọc dấu hiệu của nó và sửa. Cuối bài là bảng checklist để tra nhanh.

Các lỗi chung (image, env, Pending, Service...) làm trong một namespace thử thu-debug, không có label Pod Security và không có NetworkPolicy, để không đụng vào TaskFlow. Những lỗi gắn với các giới hạn của namespace taskflow thì làm ngay trong taskflow.

kubectl create namespace thu-debug
# namespace/thu-debug created

1. Quy trình debug.

Gặp lỗi thì đừng đoán, đi theo thứ tự từ ngoài vào trong. Mỗi bước trả lời một câu hỏi và cho biết bước sau cần xem gì:

1. get         Pod ở trạng thái nào? READY, STATUS, RESTARTS, NODE (-o wide)
2. describe    State / Last State của container, Conditions, Events ở cuối
3. events      kubectl events --for <loại>/<tên>, kubectl get events --sort-by
4. logs        log của ứng dụng; --previous cho lần chạy trước
5. exec/debug  vào trong Pod: kubectl exec, hoặc kubectl debug khi image không có shell
6. network     Service, EndpointSlice, DNS, NetworkPolicy

Cột STATUS của bước 1 gần như quyết định hướng đi:

  • Pending: Pod chưa được xếp lên node. Ứng dụng chưa chạy nên không có log, chỉ có event.
  • ImagePullBackOff, CreateContainerConfigError: kubelet không tạo được container, lý do nằm trong event và state.waiting.message.
  • CrashLoopBackOff, Error, OOMKilled: container chạy rồi chết. Xem log và lastState.terminated.
  • Running nhưng 0/1: readiness lỗi, Pod không nhận traffic. 1/1 mà vẫn không gọi được thì là chuyện mạng.

Chưa biết bắt đầu từ đâu thì xem mọi cảnh báo mới nhất của cả cụm: kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | tail. API server chỉ giữ event khoảng một giờ (cờ --event-ttl), lỗi từ hôm qua chỉ còn lại status của object.

2. Container không lên: ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError.

ImagePullBackOff

Tạo một Deployment với tag không tồn tại:

kubectl -n thu-debug create deployment thu-app --image=taskflow-api:0.53.9
# deployment.apps/thu-app created
kubectl -n thu-debug get pods
# NAME                       READY   STATUS             RESTARTS   AGE
# thu-app-76dfc9d686-6g8gw   0/1     ImagePullBackOff   0          25s
kubectl -n thu-debug describe pod -l app=thu-app | sed -n "/^Events:/,\$p"
# Events:
#   Type     Reason     Age                From               Message
#   ----     ------     ----               ----               -------
# ...
#   Warning  Failed     8s (x2 over 24s)   kubelet            spec.containers{taskflow-api}: Failed to pull image "taskflow-api:0.53.9": failed to pull and unpack image "docker.io/library/taskflow-api:0.53.9": failed to resolve reference "docker.io/library/taskflow-api:0.53.9": pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed
# ...

Node không có tag 0.53.9 nên kubelet đi pull ở Docker Hub, thất bại, rồi chờ ngày càng lâu giữa các lần thử (Bài 5, Bài 10). not found là sai tag, pull access denied là sai tên hoặc thiếu imagePullSecrets, timeout là node không ra được registry.

Chỉ cần event thì kubectl events --for pod/<tên> --types=Warning gọn hơn describe. Nhưng kubectl -n thu-debug events --for deployment/thu-app chỉ in một dòng Scaled up replica set thu-app-76dfc9d686 from 0 to 1: --for chỉ lấy event của chính object đó, không lấy của ReplicaSet hay Pod con. Deployment "ổn", lỗi nằm ở Pod, nên luôn đi xuống tới Pod.

CrashLoopBackOff

Sửa tag cho đúng. Image này không được cấu hình gì nên container chạy rồi thoát ngay:

kubectl -n thu-debug set image deploy/thu-app taskflow-api=taskflow-api:0.53.0
# deployment.apps/thu-app image updated
kubectl -n thu-debug get pods
# NAME                       READY   STATUS   RESTARTS      AGE
# thu-app-74c955df57-85jm4   0/1     Error    2 (28s ago)   30s
kubectl -n thu-debug logs deploy/thu-app
# cấu hình không hợp lệ:
# TASKFLOW_JWT_SECRET: cần ít nhất 32 byte, VD tạo bằng openssl rand -base64 32

STATUS đổi qua lại giữa Error và CrashLoopBackOff tùy lúc xem. Lỗi thiếu TASKFLOW_JWT_SECRET đã gặp ở Bài 6, cả cái bẫy của --previous (lúc container đang dừng nó có thể báo unable to retrieve container logs, còn kubectl logs không cờ đã in log của lần chạy vừa chết). Log không nói gì thì xem mã thoát:

kubectl -n thu-debug get pod -l app=thu-app -o jsonpath='{.items[0].status.containerStatuses[0].lastState.terminated}'; echo
# {"containerID":"containerd://48deaca13759e8f0bac4d6d47c4eb7dec92f201f9c5169682ee729405330583a","exitCode":2,"finishedAt":"2026-11-25T14:19:31Z","reason":"Error","startedAt":"2026-11-25T14:19:30Z"}

TaskFlow thoát mã 2 khi cấu hình sai, 1 khi migration lỗi (Bài 20) hoặc server dừng vì lỗi (VD không nối được PostgreSQL lúc khởi động); 137 là bị SIGKILL (OOM hoặc liveness), 143 là SIGTERM. Thêm biến là chạy:

kubectl -n thu-debug set env deploy/thu-app TASKFLOW_JWT_SECRET=doi-chuoi-bi-mat-nay-dai-it-nhat-32-byte
# deployment.apps/thu-app env updated

CreateContainerConfigError

Giờ lấy biến đó từ Secret, nhưng gõ sai tên key (Secret có key jwt, Deployment đòi jwt-secret):

kubectl -n thu-debug create secret generic thu-app --from-literal=jwt=doi-chuoi-bi-mat-nay-dai-it-nhat-32-byte
# secret/thu-app created
kubectl -n thu-debug patch deploy thu-app --type=json -p '[{"op":"replace","path":"/spec/template/spec/containers/0/env/0","value":{"name":"TASKFLOW_JWT_SECRET","valueFrom":{"secretKeyRef":{"name":"thu-app","key":"jwt-secret"}}}}]'
# deployment.apps/thu-app patched
kubectl -n thu-debug events --types=Warning | tail -3
# ...
# 7s (x2 over 7s)         Warning   Failed    Pod/thu-app-5fbbcf8668-q4v6x    Error: couldn't find key jwt-secret in Secret thu-debug/thu-app

Kubelet dựng env trước khi tạo container, thiếu ConfigMap/Secret hay thiếu key là dừng ở đây (Bài 13, Bài 14). Pod mới đứng ở CreateContainerConfigError, Pod cũ vẫn Running nhờ rolling update, ứng dụng không chết, chỉ rollout đứng yên. Cùng STATUS này còn có lỗi của Bài 28: runAsNonRoot với image ghi USER bằng tên (image has non-numeric user), sửa bằng runAsUser dạng số. Quay về bản trước:

kubectl -n thu-debug rollout undo deploy/thu-app
# deployment.apps/thu-app rolled back

3. Pod Pending và OOMKilled.

Không node nào đủ chỗ

kubectl -n thu-debug set resources deploy/thu-app --requests=cpu=20
# deployment.apps/thu-app resource requirements updated
kubectl -n thu-debug get pods
# NAME                       READY   STATUS    RESTARTS   AGE
# thu-app-7457c5b7f4-zg57n   0/1     Pending   0          5s
# thu-app-b7d4759c6-2r7dt    1/1     Running   0          37s
kubectl -n thu-debug events --types=Warning | grep FailedScheduling
# 4s (x2 over 5s)        Warning   FailedScheduling   Pod/thu-app-7457c5b7f4-zg57n    0/3 nodes are available: 1 node(s) had untolerated taint(s), 2 Insufficient cpu. preemption: 0/3 nodes are available: 3 Preemption is not helpful for scheduling.

Event FailedScheduling đếm lý do theo từng node: control plane có taint (Bài 26), hai worker không đủ CPU cho requests (Bài 16). Scheduler so với requests, không so với mức dùng thật. Các lý do hay gặp khác: didn't match Pod's node affinity/selector (nodeSelector, affinity), untolerated taint, và với volume local-path: Pod dùng PVC đã gắn với taskflow-worker mà bị ép sang taskflow-worker2 thì báo 1 node(s) didn't match PersistentVolume's node affinity, chính là lý do mọi Pod API nằm cùng node ở Bài 18. Trả lại như cũ bằng kubectl -n thu-debug rollout undo deploy/thu-app.

Pod không được tạo: ResourceQuota

Có trường hợp get pods không thấy Pod nào bị Pending, vì Pod chưa từng được tạo:

kubectl -n thu-debug create quota thu-quota --hard=pods=1
# resourcequota/thu-quota created
kubectl -n thu-debug scale deploy/thu-app --replicas=2
# deployment.apps/thu-app scaled
kubectl -n thu-debug get deploy thu-app -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'
# Progressing=True NewReplicaSetAvailable: ReplicaSet "thu-app-b7d4759c6" has successfully progressed.
# Available=False MinimumReplicasUnavailable: Deployment does not have minimum availability.
# ReplicaFailure=True FailedCreate: pods "thu-app-b7d4759c6-qj6mp" is forbidden: exceeded quota: thu-quota, requested: pods=1, used: pods=1, limited: pods=1

Deployment 1/2, nhưng API server từ chối Pod thứ hai ngay lúc tạo: lỗi chỉ có ở event FailedCreate của ReplicaSet và condition ReplicaFailure (phần status.conditions của -o yaml), giống Pod bị Pod Security từ chối ở Bài 28. Quota của taskflow (Bài 16) xem bằng kubectl describe quota. Dọn: kubectl -n thu-debug delete quota thu-quota, kubectl -n thu-debug scale deploy/thu-app --replicas=1.

OOMKilled

Dựng lại thu-mem của Bài 16 (limit 32Mi, tail /dev/zero) bằng Deployment: create deployment thu-mem --image=busybox:1.37 --replicas=0 -- tail /dev/zero, set resources deploy/thu-mem --limits=memory=32Mi, rồi mới scale --replicas=1 (tạo với 0 replica để container không chạy khi chưa có limit):

kubectl -n thu-debug get pod -l app=thu-mem -o jsonpath='{.items[0].status.containerStatuses[0].lastState.terminated.reason} {.items[0].status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}'
# OOMKilled 137

STATUS chỉ hiện OOMKilled một lúc rồi thành CrashLoopBackOff, còn lastState.terminated.reason thì giữ lại lý do. Ứng dụng không kịp ghi log gì, và kubectl top lấy mẫu theo chu kỳ nên thường không bắt được đỉnh RAM. Xóa: kubectl -n thu-debug delete deploy thu-mem.

4. Pod chạy nhưng không nhận request.

Service không có endpoint

Tạo Service cho thu-app và một Pod busybox để gọi thử, rồi làm sai selector của Service:

kubectl -n thu-debug expose deploy/thu-app --port=80 --target-port=8080
# service/thu-app exposed
kubectl -n thu-debug run thu-curl --image=busybox:1.37 -- sleep 3600
# pod/thu-curl created
kubectl -n thu-debug exec thu-curl -- wget -qO- http://thu-app/ready
# ok
kubectl -n thu-debug set selector svc thu-app app=thu-ap
# service/thu-app selector updated
kubectl -n thu-debug exec thu-curl -- wget -qO- -T 3 http://thu-app/ready
# wget: can't connect to remote host (10.96.8.145): Connection refused
# command terminated with exit code 1
kubectl -n thu-debug get endpointslice -l kubernetes.io/service-name=thu-app
# NAME            ADDRESSTYPE   PORTS     ENDPOINTS   AGE
# thu-app-pswj5   IPv4          <unset>   <unset>     3s
kubectl -n thu-debug get pods -l app=thu-ap
# No resources found in thu-debug namespace.

Service vẫn có ClusterIP và tên DNS, nhưng EndpointSlice rỗng (Bài 11), kube-proxy từ chối kết nối ngay (Connection refused). Cách kiểm tra: chạy get pods -l với đúng selector của Service, so với get pods --show-labels. Endpoint có mà vẫn bị từ chối thì xem targetPort có khớp port container đang nghe không. Sửa lại: kubectl -n thu-debug set selector svc thu-app app=thu-app.

Readiness lỗi, Gateway trả 503: một sự cố trong taskflow

Giờ một sự cố thật trên TaskFlow. Giả sử ai đó xóa nhầm NetworkPolicy postgres (cho API gọi vào PostgreSQL). Ngay sau đó mọi thứ vẫn chạy: các kết nối đang mở trong pool của API không bị cắt, chỉ kết nối mới bị chặn. Đó là cách kindnet của kind làm (và nhiều plugin khác); docs Kubernetes để việc xử lý kết nối đang mở tùy implementation. Lỗi chỉ lộ ra khi PostgreSQL khởi động lại:

kubectl delete networkpolicy postgres
# networkpolicy.networking.k8s.io "postgres" deleted from taskflow namespace
kubectl delete pod postgres-0
# pod "postgres-0" deleted from taskflow namespace
kubectl get pods
# NAME                                 READY   STATUS      RESTARTS        AGE
# postgres-0                           1/1     Running     0               40s
# ...
# taskflow-api-6bc77ccc89-9v9pk        0/1     Running     3 (8m31s ago)   8m51s
# taskflow-api-6bc77ccc89-jl87d        0/1     Running     3 (8m30s ago)   8m50s
# ...

PostgreSQL Ready, nhưng hai Pod API 0/1, và curl -s -i --resolve taskflow.local:8080:127.0.0.1 http://taskflow.local:8080/ready nhận HTTP/1.1 503 Service Unavailable với nội dung no available server: câu trả lời của Traefik khi backend không còn endpoint ready, không phải của TaskFlow (như Bài 19). Đi theo quy trình:

kubectl events --for pod/taskflow-api-6bc77ccc89-9v9pk | tail -3
# ...
# 2s (x10 over 44s)       Warning   Unhealthy   Pod/taskflow-api-6bc77ccc89-9v9pk   Readiness probe failed: HTTP probe failed with statuscode: 503
kubectl logs taskflow-api-6bc77ccc89-9v9pk --tail=3
# {"time":"2026-11-25T14:24:21.375786709Z","level":"WARN","msg":"ready: database không phản hồi","request_id":"KOTVQCBBSDZILYGNAN7YMMQIOH","err":"failed to connect to `user=taskflow database=taskflow`: 10.244.1.14:5432 (postgres): dial error: timeout: context deadline exceeded"}
# ...
kubectl get endpointslice -l kubernetes.io/service-name=taskflow-api -o jsonpath='{range .items[*].endpoints[*]}{.targetRef.name} ready={.conditions.ready}{"\n"}{end}'
# taskflow-api-6bc77ccc89-9v9pk ready=false
# taskflow-api-6bc77ccc89-jl87d ready=false

Đọc ngược: endpoint ready=false ← readiness /ready trả 503 (Bài 15) ← API nối PostgreSQL bị timeout, không phải connection refused. Liveness /health không đụng DB nên Pod không restart. Cột ENDPOINTS của kubectl get endpointslice in cả IP của Pod chưa ready, nên phải xem conditions.ready.

NetworkPolicy chặn một đường

PostgreSQL đang chạy, mà kết nối timeout trong namespace có NetworkPolicy thì xem policy trước (Bài 28):

kubectl get networkpolicy
# NAME                POD-SELECTOR                                                                    AGE
# allow-dns           <none>                                                                          8m56s
# default-deny        <none>                                                                          8m56s
# postgres-clients    app.kubernetes.io/component in (backup,migration)                               8m56s
# ...

Với mỗi đầu của kết nối, tìm policy có POD-SELECTOR khớp label của Pod: bên gọi cần rule egress, bên nhận cần rule ingress. Không còn policy nào chọn postgres-0 ngoài default-deny. Để chắc, dùng Pod thu-net của Bài 28 (đạt mức restricted), gắn label để nó đóng vai Job backup:

kubectl apply -f thu/thu-net.yaml
# pod/thu-net created
kubectl exec thu-net -- nc -zv -w 3 postgres 5432
# nc: postgres (10.244.1.14:5432): Connection timed out
# command terminated with exit code 1
kubectl label pod thu-net app.kubernetes.io/component=backup
# pod/thu-net labeled
kubectl exec thu-net -- nc -zv -w 3 postgres 5432
# nc: postgres (10.244.1.14:5432): Connection timed out
# command terminated with exit code 1
kubectl apply -k kustomize/overlays/dev | grep networkpolicy
# networkpolicy.networking.k8s.io/allow-dns unchanged
# networkpolicy.networking.k8s.io/default-deny unchanged
# networkpolicy.networking.k8s.io/postgres created
# ...
kubectl exec thu-net -- nc -zv -w 3 postgres 5432
# postgres (10.244.1.14:5432) open

Không label thì bị chặn ngay chiều đi. Có label backup thì postgres-clients mở chiều đi, vẫn timeout vì phía PostgreSQL thiếu chiều vào. Apply lại overlay, vài giây sau hai Pod API Ready và /ready lại trả ok. kubectl diff -k kustomize/overlays/dev cũng phát hiện được kiểu lệch này (policy bị xóa hiện thành một khối diff). Đừng gắn component: api cho Pod thử: Service taskflow-api sẽ chọn nó.

DNS hay mạng?

Debug DNS đã có ở Bài 12. Từ thu-curl, nslookup postgres báo NXDOMAIN cho postgres.thu-debug.svc.cluster.local và các đuôi search khác, còn nslookup postgres.taskflow.svc.cluster.local ra IP. Tên đúng rồi, nhưng:

kubectl -n thu-debug exec thu-curl -- nc -zv -w 3 postgres.taskflow 5432
# nc: postgres.taskflow (10.244.1.14:5432): Connection timed out
# command terminated with exit code 1

Bốn kiểu thông báo cần phân biệt:

  • NXDOMAIN: DNS chạy, tên sai (thiếu namespace, gõ nhầm).
  • no servers could be reached: không tới được CoreDNS (thiếu policy allow-dns, CoreDNS chết: kubectl -n kube-system get pods -l k8s-app=kube-dns).
  • Connection refused: tới được IP nhưng không có gì nghe: Service không có endpoint, sai targetPort, ứng dụng chưa listen.
  • Connection timed out sau khi tên đã ra IP: gói tin bị bỏ, gần như luôn là NetworkPolicy. Ở trên là policy postgres chỉ nhận từ Pod trong taskflow.

5. kubectl debug và ephemeral container.

Image TaskFlow là distroless (Bài 6): kubectl exec taskflow-api-6bc77ccc89-9v9pk -- sh báo exec: "sh": executable file not found in $PATH. kubectl debug thêm một ephemeral container vào Pod đang chạy: container tạm, image tùy chọn (ở đây busybox), dùng chung network namespace với Pod, và với --target thì nhìn thấy cả tiến trình của container đích. Thử với profile mặc định (general):

kubectl debug taskflow-api-6bc77ccc89-9v9pk --image=busybox:1.37 --target=api -- id
# ...
# Error from server (Forbidden): pods "taskflow-api-6bc77ccc89-9v9pk" is forbidden: violates PodSecurity "restricted:v1.37": allowPrivilegeEscalation != false (container "debugger-9sgqt" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "debugger-9sgqt" must set securityContext.capabilities.drop=["ALL"]; container "debugger-9sgqt" must not include "SYS_PTRACE" in securityContext.capabilities.add)

Pod Security kiểm tra cả ephemeral container, và profile general thêm SYS_PTRACE. Dùng --profile=restricted. Thường các bạn chạy kubectl debug -it ... -- sh để vào shell; ở đây mình cho nó sleep, đặt tên dbg, rồi exec vào:

kubectl debug taskflow-api-6bc77ccc89-9v9pk -c dbg --image=busybox:1.37 --target=api --profile=restricted -- sleep 1800
# Targeting container "api". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- id
# uid=65532 gid=65532 groups=65532
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- ps
# PID   USER     TIME  COMMAND
#     1 65532     0:01 /api
#    27 65532     0:00 sleep 1800
#    44 65532     0:00 ps
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- ls /proc/1/root
# api
# bin
# ...
# data
# ...
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- wget -qO- localhost:8080/health
# ok
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- nc -zv -w 3 redis 6379
# redis (10.96.62.138:6379) open
kubectl exec taskflow-api-6bc77ccc89-9v9pk -c dbg -- wget -q -T 3 -O /dev/null http://example.com
# wget: download timed out
# command terminated with exit code 1

Trong đó:

  • Profile restricted đặt đủ các field mà mức restricted đòi; uid lấy từ runAsUser: 65532 mức Pod của Bài 28, cùng uid với /api.
  • --target=api: chung process namespace với container api, ps thấy /api là PID 1, filesystem của nó xem qua /proc/1/root (được vì cùng uid).
  • Chung network namespace: localhost:8080 là TaskFlow, NetworkPolicy của Pod API áp lên cả container debug (tới Redis được, ra Internet timeout), tức là thấy mạng đúng như ứng dụng thấy.

Ephemeral container không xóa được, không restart: nó nằm trong spec.ephemeralContainers tới khi Pod bị xóa. Pod không ghi runAsUser mà image debug chạy bằng root như busybox thì profile restricted làm container kẹt ở CreateContainerConfigError (container has runAsNonRoot and image will run as root, mình thử trên thu-curl). Khi đó thêm uid bằng --custom, một file JSON trộn vào container spec: với thu/nobody.json chứa {"securityContext":{"runAsUser":65534}}, lệnh kubectl -n thu-debug debug thu-curl -c dbg2 --image=busybox:1.37 --profile=restricted --custom=thu/nobody.json -- sleep 600 chạy được với uid=65534(nobody).

Debug node

kubectl debug node/<tên> tạo một Pod trên node đó, dùng chung PID, network, IPC namespace của node, filesystem của node mount ở /host. Trong taskflow nó bị từ chối thẳng (host namespaces (hostNetwork=true, hostPID=true, hostIPC=true), restricted volume type "hostPath"...), nên chạy trong thu-debug:

kubectl -n thu-debug debug node/taskflow-worker2 --image=busybox:1.37 -- chroot /host crictl ps --name api
# Creating debugging pod node-debugger-taskflow-worker2-qt42j with container debugger on node taskflow-worker2.
kubectl -n thu-debug logs node-debugger-taskflow-worker2-qt42j
# CONTAINER           IMAGE               CREATED             STATE               NAME                ATTEMPT             POD ID              POD                             NAMESPACE
# ...
# 26bac26fd2b1b       167e936b43652       10 minutes ago      Running             api                 3                   a17fe226e2b8f       taskflow-api-6bc77ccc89-9v9pk   taskflow

Pod này chạy bằng root trong namespace của node, gần như root trên node: chỉ admin cụm nên có, chỉ chạy ở namespace không bị Pod Security giới hạn, xong việc xóa ngay (kubectl -n thu-debug delete pod node-debugger-taskflow-worker2-qt42j).

6. port-forward, cp, top, auth can-i và log của control plane.

kubectl port-forward không cần gì trong container: kubelet và container runtime nối tới localhost bên trong network namespace của Pod (Bài 6). Vì vậy nó chạy với distroless, và không bị NetworkPolicy chặn: kubectl port-forward deploy/redis 16379:6379 rồi gửi PING vào localhost:16379 nhận được -NOAUTH Authentication required. của Redis, dù trong cụm chỉ API gọi được Redis. Tiện để debug, và cũng là lý do quyền pods/portforward phải được cấp cẩn thận.

kubectl cp thì ngược lại, nó chạy tar trong container, nên kubectl cp taskflow-api-6bc77ccc89-9v9pk:/data/uploads ./uploads báo exec: "tar": executable file not found in $PATH. Đi vòng qua container debug:

kubectl cp -c dbg taskflow-api-6bc77ccc89-9v9pk:/proc/1/root/etc/passwd ./passwd
# tar: removing leading '/' from member names
grep nonroot passwd
# nonroot:x:65532:65532:nonroot:/home/nonroot:/sbin/nologin

Busybox có tar, /proc/1/root trỏ vào filesystem của api. kubectl cp bỏ qua symlink, nên file như /etc/os-release (symlink trong distroless) không chép được theo cách này.

kubectl top (metrics-server, Bài 25) cho biết Pod nào đang ăn CPU, RAM; --containers tách từng container:

kubectl top pod -l app.kubernetes.io/name=taskflow-api --containers
# POD                             NAME   CPU(cores)   MEMORY(bytes)
# taskflow-api-6bc77ccc89-9v9pk   api    4m           13Mi
# taskflow-api-6bc77ccc89-9v9pk   dbg    2m           2Mi
# taskflow-api-6bc77ccc89-jl87d   api    2m           9Mi

Lỗi Forbidden từ API server là chuyện RBAC (Bài 27), không phải lỗi của ứng dụng. kubectl debug cần quyền patch trên subresource pods/ephemeralcontainers, thứ mà taskflow-deployer hay ClusterRole view không có:

kubectl debug taskflow-api-6bc77ccc89-9v9pk -c dbg3 --image=busybox:1.37 --profile=restricted --as=system:serviceaccount:taskflow:taskflow-deployer -- true
# Error from server (Forbidden): pods "taskflow-api-6bc77ccc89-9v9pk" is forbidden: User "system:serviceaccount:taskflow:taskflow-deployer" cannot patch resource "pods/ephemeralcontainers" in API group "" in the namespace "taskflow"

Thông báo đã ghi đủ user, verb, resource, namespace; kubectl auth can-i patch pods/ephemeralcontainers --as=... (ra no) để thử lại sau khi sửa Role.

Log của control plane và kubelet trên kind

Trên kind, control plane là các static Pod trong kube-system, xem bằng kubectl -n kube-system logs kube-controller-manager-taskflow-control-plane (cùng kiểu cho scheduler, apiserver); kubelet và containerd là service systemd trong container Docker của node (Bài 3). Log của kubelet: docker exec taskflow-worker2 journalctl -u kubelet --no-pager (lọc bằng grep theo tên Pod), có cùng lỗi ErrImagePull như event. docker exec <node> crictl ps, crictl logs xem container ngay cả khi API server không trả lời. Trên k3s (Bài 31) thì là journalctl -u k3s trên VPS.

Dọn dẹp

kubectl delete pod taskflow-api-6bc77ccc89-9v9pk
# pod "taskflow-api-6bc77ccc89-9v9pk" deleted from taskflow namespace
kubectl delete -f thu/thu-net.yaml --now
# pod "thu-net" deleted from taskflow namespace
kubectl delete namespace thu-debug
# namespace "thu-debug" deleted
kubectl diff -k kustomize/overlays/dev; echo diff exit $?
# diff exit 0

Xóa Pod API đang có container dbg để Deployment tạo Pod mới sạch; xóa namespace thử là xóa luôn mọi Deployment, Service, Secret trong đó. kubectl diff -k trống: cụm khớp với project, project không đổi gì ở bài này ngoài phần "Debug" trong README.

7. Checklist debug.

Dấu hiệuXem ở đâuNguyên nhân hay gặp
Pendingevent FailedSchedulingrequests quá lớn, taint, affinity, PV ở node khác
READY thiếu, không có Pod lỗistatus.conditions, event FailedCreateResourceQuota, Pod Security
ImagePullBackOffevent Failed to pull imagesai tag/tên, thiếu imagePullSecrets
CreateContainerConfigErrorevent, state.waitingthiếu ConfigMap/Secret/key, USER không phải số
CrashLoopBackOfflogs, lastState.terminatedthiếu cấu hình (mã 2), DB không tới được
OOMKilled (137)lastState.terminated.reasonmemory limit thấp, rò rỉ bộ nhớ
Running 0/1event Unhealthy, logdependency chết hoặc bị chặn, probe sai
Connection refused, 503EndpointSlice (ready)selector sai, không Pod nào ready, sai targetPort
Connection timed outget networkpolicy, Pod thử có labelthiếu egress bên gọi / ingress bên nhận
NXDOMAIN, no servers could be reachednslookup FQDN, Pod CoreDNSsai tên / thiếu allow-dns
Forbiddenkubectl auth can-i --asRBAC thiếu quyền

Các bạn có thể xem thêm về debug Pod và ephemeral container tại đây.

Code đầy đủ của series sau bài này nằm ở tag bai-29 trên GitHub; các thay đổi của riêng bài này: so sánh bai-28...bai-29.

8. Lời kết.

Như vậy mình đã giới thiệu với mọi người về debug ứng dụng trên Kubernetes: quy trình get → describe → events → logs → exec/debug → mạng, các lỗi ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError, Pending, OOMKilled, Service không có endpoint, NetworkPolicy chặn đường, và kubectl debug với ephemeral container trong namespace restricted. Tất cả đều là debug sau khi đã có chuyện, và phải tự đi gõ lệnh. Bài sau mình sẽ giới thiệu về monitoring với Prometheus và Grafana: cài kube-prometheus-stack, thu thập /metrics của TaskFlow, xem dashboard và đặt alert để biết có chuyện trước khi người dùng báo.

Đă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!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha