Ở bài trước chúng ta mới chạy thử image nginx có sẵn trên Docker Hub. Trước khi viết Pod đầu tiên cho TaskFlow API, bài này mình sẽ cùng các bạn chuẩn bị image TaskFlow cho Kubernetes: build image với tag theo version, nạp vào cụm kind, hiểu imagePullPolicy và kéo image từ registry private.
1. Image của TaskFlow API.
TaskFlow API là ứng dụng mẫu của series Golang (github.com/toidicode/taskflow, tag bai-53). Dockerfile multi-stage có sẵn trong repo chép hai binary /api và /notifier vào image distroless/static-debian13:nonroot (không shell, chạy bằng user nonroot). API lắng nghe port 8080, có hai endpoint /health và /ready. Dockerfile này đã được giải thích trong bài đóng gói TaskFlow API thành Docker image, ở đây mình chỉ build và dùng.
Điểm khác với Docker: container do containerd trong từng node khởi động, và mỗi node tự đi lấy image. Image nằm trong docker image ls của máy các bạn thì node không thấy. Có hai đường đưa image tới node:
docker build
máy của bạn ─────────────► taskflow-api:0.53.0 (Docker)
│ │
kind load │ │ docker push
▼ ▼
containerd của từng node ◄────── registry (GHCR, Docker Hub)
kubelet pull
kind load docker-image: chép thẳng image từ Docker vào các node, chỉ có ở kind (phần 3).- Registry: đẩy image lên GHCR hoặc Docker Hub, kubelet tự pull về, cách của mọi cụm thật (phần 6).
2. Build image với tag theo version.
Lấy mã nguồn TaskFlow đúng tag bai-53 rồi build, truyền version vào binary qua --build-arg:
git clone --branch bai-53 https://github.com/toidicode/taskflow.git
cd taskflow
docker build --build-arg VERSION=0.53.0 -t taskflow-api:0.53.0 .
# ...
# #12 [build 6/6] RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 go build ...
# #12 DONE 77.6s
# ...
# #15 naming to docker.io/library/taskflow-api:0.53.0 done
docker image inspect taskflow-api:0.53.0 --format '{{.Os}}/{{.Architecture}} user={{.Config.User}} entrypoint={{json .Config.Entrypoint}}'
# linux/arm64 user=nonroot:nonroot entrypoint=["/api"]
Image khoảng 57 MB, lần đầu build mất khoảng 2 phút, các lần sau lấy từ cache. Tag là 0.53.0 chứ không phải latest, và cả series giữ quy tắc này cho mọi image đem đi deploy: nhìn manifest là biết đang chạy bản nào (latest hôm nay và tuần sau có thể là hai image khác nhau), rollback ở Bài 10 chỉ là đổi về tag cũ, và Kubernetes đối xử với latest khác hẳn các tag còn lại (phần 4). Chiến lược đặt tag (semver, commit SHA) có trong bài đẩy image lên registry.
Lưu ý: docker build tạo image cho kiến trúc của máy đang build (ở đây arm64), trùng với các node kind trên máy đó. Nếu shell có đặt biến DOCKER_DEFAULT_PLATFORM thì bỏ đi trước khi build. Đưa lên server amd64 thì build đa nền tảng với Buildx.
3. Nạp image vào cụm kind.
Thử chạy image vừa build bằng một Pod tạm (Pod học kỹ ở Bài 6):
kubectl run taskflow-test --image=taskflow-api:0.53.0
# pod/taskflow-test created
kubectl get pod taskflow-test
# NAME READY STATUS RESTARTS AGE
# taskflow-test 0/1 ImagePullBackOff 0 20s
kubectl describe pod taskflow-test
# ...
# Warning Failed 5s (x2 over 18s) kubelet spec.containers{taskflow-test}: Failed to pull image "taskflow-api:0.53.0": failed to pull and unpack image "docker.io/library/taskflow-api:0.53.0": ... pull access denied, repository does not exist or may require authorization ...
kubectl delete pod taskflow-test
Node không có image nên kubelet đi pull. Tên không ghi registry thì mặc định là Docker Hub, nên taskflow-api:0.53.0 thành docker.io/library/taskflow-api:0.53.0, một repository không tồn tại. ImagePullBackOff nghĩa là kubelet đang chờ lâu dần giữa các lần pull lại.
Với kind, các bạn nạp image vào node bằng kind load docker-image IMAGE... --name CLUSTER. Bỏ --name thì kind hiểu là cụm tên kind, nên với cụm taskflow phải ghi rõ:
kind load docker-image taskflow-api:0.53.0 --name taskflow
# Image: "taskflow-api:0.53.0" with ID "sha256:167e936b436529b3c1e0506d3d92fb3f9b6069d8d55ee9cb909225d2d10eb01e" not yet present on node "taskflow-control-plane", loading...
# ...
kind xuất image ra file tar rồi import vào containerd của cả 3 node. Kiểm tra bằng crictl, công cụ dòng lệnh của container runtime có sẵn trong node:
docker exec taskflow-worker crictl images | grep taskflow
# docker.io/library/taskflow-api 0.53.0 167e936b43652 58.1MB
kind load docker-image taskflow-api:0.53.0 --name taskflow
# Image: "taskflow-api:0.53.0" with ID "sha256:167e936b...b01e" found to be already present on all nodes.
Image ID 167e936b4365... trùng với ID bên Docker, đúng là image vừa build, và image đã có thì kind bỏ qua. Mỗi lần build lại phải kind load lại, xóa cụm thì image trong node mất theo.
Build rồi nạp sẽ lặp lại ở các bài sau (Bài 10 build bản mới để rolling update), nên mình gom thành script trong repo taskflow-k8s:
#!/usr/bin/env bash
# Build image TaskFlow API từ mã nguồn rồi nạp vào các node của cụm kind (Bài 5).
# Dùng: scripts/load-image.sh <thư-mục-mã-nguồn-taskflow> [version]
set -euo pipefail
SRC=${1:?cần đường dẫn tới mã nguồn TaskFlow}
VERSION=${2:-0.53.0}
CLUSTER=${KIND_CLUSTER:-taskflow}
IMAGE="taskflow-api:${VERSION}"
docker build --build-arg VERSION="${VERSION}" -t "${IMAGE}" "${SRC}"
kind load docker-image "${IMAGE}" --name "${CLUSTER}"
# kiểm tra: image đã có trong containerd của từng node
for node in $(kind get nodes --name "${CLUSTER}"); do
echo "${node}: $(docker exec "${node}" crictl images | grep -c "taskflow-api *${VERSION} ") image"
done
Chạy scripts/load-image.sh ../taskflow 0.53.0, cuối output sẽ có một dòng taskflow-worker: 1 image cho mỗi node.
4. imagePullPolicy trong Kubernetes.
Field imagePullPolicy của mỗi container quyết định kubelet có pull image trước khi chạy hay không:
IfNotPresent: node đã có image thì dùng luôn, chưa có mới pull.Always: lần nào khởi động container cũng hỏi registry (digest trùng bản đã có thì không tải lại), registry không trả lời được là lỗi.Never: không bao giờ pull, node không có image thì báo lỗi.
Không ghi field này thì apiserver tự điền theo tag: tag latest hoặc không có tag thì là Always, còn lại là IfNotPresent. Ghim digest không đổi quy tắc này vì apiserver chỉ xét tag: taskflow-api@sha256:... hay taskflow-api:0.53.0@sha256:... là IfNotPresent, nhưng taskflow-api:latest@sha256:... vẫn là Always. Pod ở phần 3 nhận IfNotPresent.
Đây chính là cái bẫy của latest. VD: Mình gắn thêm tag latest cho image, nạp vào cụm, rồi chạy:
docker tag taskflow-api:0.53.0 taskflow-api:latest
kind load docker-image taskflow-api:latest --name taskflow
kubectl run latest-test --image=taskflow-api:latest
kubectl get pod latest-test
# NAME READY STATUS RESTARTS AGE
# latest-test 0/1 ImagePullBackOff 0 15s
kubectl delete pod latest-test
Image nằm sẵn trên node (crictl images thấy cả tag latest) nhưng policy là Always, kubelet vẫn hỏi Docker Hub và nhận đúng lỗi pull access denied như phần 3. Trên cụm thật thì latest vẫn chạy, nhưng mỗi Pod mới có thể kéo về một bản khác nhau.
Còn Never với một image chưa nạp (VD taskflow-api:0.54.0) thì Pod báo ErrImageNeverPull ngay, không thử pull. Với cụm kind, cứ dùng tag version với mặc định IfNotPresent, hoặc ghi rõ Never khi muốn chắc chắn image đã được kind load. IfNotPresent dùng image đang có trên node, nên build lại cùng tag 0.53.0 thì node vẫn giữ bản cũ nếu quên kind load: có thay đổi thì tăng version.
5. Chạy thử TaskFlow API trên cụm.
Kiểm tra nhanh image đã nạp có chạy được không bằng một Pod tạm với --image-pull-policy=Never. TaskFlow bắt buộc có biến TASKFLOW_JWT_SECRET nên mình truyền một giá trị mẫu qua --env (Bài 6 sẽ giải thích vì sao, Bài 14 đưa secret đúng cách):
kubectl run taskflow-test --image=taskflow-api:0.53.0 --image-pull-policy=Never \
--env="TASKFLOW_JWT_SECRET=doi-chuoi-bi-mat-nay-dai-it-nhat-32-byte"
kubectl wait --for=condition=Ready pod/taskflow-test --timeout=60s
# pod/taskflow-test condition met
kubectl logs taskflow-test | grep lắng
# time=2026-11-24T06:38:02.765Z level=INFO msg="TaskFlow API lắng nghe" addr=:8080 version=0.53.0
kubectl port-forward pod/taskflow-test 8081:8080 &
curl localhost:8081/health
# ok
kill %1
kubectl delete pod taskflow-test
Pod lên Running, version=0.53.0 trong log chính là giá trị --build-arg lúc build, và /health trả ok: image đã sẵn sàng. Log, port-forward, /ready và vòng đời Pod mình sẽ đi kỹ ở Bài 6.
6. Pull image từ registry và imagePullSecrets.
Trên cụm thật, image phải nằm trên registry và tên image ghi đủ registry. Image của series sẽ là ghcr.io/toidicode/taskflow-api trên GitHub Container Registry (GHCR), nhưng lúc viết bài nó chưa được publish (Bài 32 viết workflow GitHub Actions để đẩy image lên). Thử pull bây giờ:
kubectl run ghcr-test --image=ghcr.io/toidicode/taskflow-api:0.53.0
kubectl describe pod ghcr-test
# ...
# Warning Failed 11s kubelet spec.containers{ghcr-test}: Failed to pull image "ghcr.io/toidicode/taskflow-api:0.53.0": ... failed to authorize: failed to fetch anonymous token: unexpected status from GET request to https://ghcr.io/token?scope=repository%3Atoidicode%2Ftaskflow-api%3Apull&service=ghcr.io: 403 Forbidden
kubectl delete pod ghcr-test
Khi pull ẩn danh (anonymous token), GHCR trả 403 cho cả image chưa tồn tại lẫn image private, nên gặp lỗi này thì kiểm tra tên image trước, rồi tới quyền truy cập.
Tạo Secret cho registry private
Image private cần thông tin đăng nhập, Kubernetes lưu nó trong một Secret kiểu kubernetes.io/dockerconfigjson:
kubectl create secret docker-registry ghcr-cred \
--docker-server=ghcr.io \
--docker-username=toidicode \
--docker-password=doi-token-nay \
[email protected]
# secret/ghcr-cred created
kubectl get secret ghcr-cred
# NAME TYPE DATA AGE
# ghcr-cred kubernetes.io/dockerconfigjson 1 0s
Trong đó:
--docker-serverlà địa chỉ registry, bỏ trống là Docker Hub.--docker-username,--docker-password: với GHCR là tên tài khoản GitHub và một token chỉ có quyềnread:packages.--docker-emailkhông bắt buộc.
Bên trong Secret chỉ là nội dung file ~/.docker/config.json mã hóa base64, ai đọc được Secret là có token:
kubectl get secret ghcr-cred -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d
# {"auths":{"ghcr.io":{"username":"toidicode","password":"doi-token-nay","email":"[email protected]","auth":"dG9pZGljb2RlOmRvaS10b2tlbi1uYXk="}}}
base64 không phải mã hóa bảo mật (Bài 14). Token ở đây là giả, các bạn thay bằng token thật và đừng commit lệnh có token vào Git.
Dùng imagePullSecrets trong Pod
Pod chỉ ra Secret dùng để pull qua field imagePullSecrets (Secret phải cùng namespace với Pod):
- taskflow-ghcr-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: taskflow-ghcr
labels:
app.kubernetes.io/name: taskflow-api
app.kubernetes.io/part-of: taskflow
spec:
imagePullSecrets:
- name: ghcr-cred
containers:
- name: api
image: ghcr.io/toidicode/taskflow-api:0.53.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
kubectl apply -f taskflow-ghcr-pod.yaml
# pod/taskflow-ghcr created
kubectl describe pod taskflow-ghcr
# ...
# Warning Failed 11s kubelet spec.containers{api}: Failed to pull image "ghcr.io/toidicode/taskflow-api:0.53.0": ... failed to authorize: failed to fetch oauth token: unexpected status from GET request to https://ghcr.io/token?... 403 Forbidden
kubectl delete -f taskflow-ghcr-pod.yaml
Vẫn lỗi vì token giả và image chưa có, nhưng thông báo đã đổi từ anonymous token sang oauth token: kubelet đã dùng thông tin đăng nhập trong Secret. Token thật và image có trên registry thì Pod pull được bình thường.
Không muốn ghi imagePullSecrets vào từng Pod thì gắn Secret vào ServiceAccount (Bài 27), mọi Pod dùng ServiceAccount đó được tự thêm: kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "ghcr-cred"}]}'.
Ghim image bằng digest
Tag như 0.53.0 vẫn có thể bị đẩy đè bằng image khác. Muốn chắc chắn tuyệt đối thì ghim bằng digest (image và registry), dạng tên:tag@sha256:.... Image local chưa có digest trên registry nào, nên mình minh họa bằng nginx:1.31-alpine:
docker buildx imagetools inspect nginx:1.31-alpine
# Name: docker.io/library/nginx:1.31-alpine
# MediaType: application/vnd.oci.image.index.v1+json
# Digest: sha256:b50897d5c7b1aa08067c3d90c5e8b3e47ec4e3c91c91446f67820228f7b41e34
# ...
kubectl run digest-test --image=nginx:1.31-alpine@sha256:b50897d5c7b1aa08067c3d90c5e8b3e47ec4e3c91c91446f67820228f7b41e34
kubectl get pod digest-test -o jsonpath='{.status.containerStatuses[0].imageID}'
# docker.io/library/nginx@sha256:b50897d5c7b1aa08067c3d90c5e8b3e47ec4e3c91c91446f67820228f7b41e34
Có digest thì kubelet pull theo digest và bỏ qua tag, tag chỉ để người đọc dễ hiểu. Image TaskFlow trên GHCR sau này ghim theo mẫu ghcr.io/toidicode/taskflow-api:0.53.0@sha256:..., hợp với production và GitOps (Bài 32). Học trên kind thì tag version là đủ.
Dọn những gì vừa tạo ở phần này:
kubectl delete pod digest-test
# nếu đã gắn Secret vào ServiceAccount
kubectl patch serviceaccount default --type=json -p '[{"op":"remove","path":"/imagePullSecrets"}]'
kubectl delete secret ghcr-cred
docker rmi taskflow-api:latest
Code đầy đủ của series sau bài này nằm ở tag bai-05 trên GitHub; các thay đổi của riêng bài này: so sánh bai-04...bai-05.
7. Lời kết.
Như vậy mình đã cùng các bạn chuẩn bị image TaskFlow cho Kubernetes: build taskflow-api:0.53.0, nạp vào cụm bằng kind load, ba giá trị của imagePullPolicy và cái bẫy của latest, chạy thử API, kéo image private với imagePullSecrets và ghim bằng digest. Các bạn giữ lại cụm cùng image trên node, bài sau chúng ta sẽ viết Pod đầu tiên cho TaskFlow API bằng file manifest và tìm hiểu kỹ về Pod.
Đă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