Sau bài này bạn làm được: dùng kubectl debug pod nhanh mà không tra doc liên tục; chuyển context giữa nhiều cluster/namespace không nhầm; tra cứu field YAML bằng kubectl explain thay vì Google.


kubectl là gì

kubectl là CLI client nói chuyện với kube-apiserver qua HTTPS. Mọi thao tác (tạo, đọc, sửa, xoá resource) đều là HTTP request tới API server.

kubectl get pods
GET https://api-server:6443/api/v1/namespaces/default/pods
kube-apiserver → authenticate → authorize → return JSON
kubectl format → table/yaml/json output

Kubeconfig và context

File kubeconfig

Mặc định: ~/.kube/config. Chứa ba phần:

clusters:       # Danh sách cluster (API server URL + CA cert)
users:          # Credentials (token, client cert, exec plugin…)
contexts:       # Ghép cluster + user + namespace mặc định
current-context: dev-cluster
# Xem context hiện tại
kubectl config current-context

# Liệt kê tất cả context
kubectl config get-contexts

# Chuyển context
kubectl config use-context prod-cluster

# Đổi namespace mặc định cho context hiện tại
kubectl config set-context --current --namespace=staging

Nhiều kubeconfig

# Merge nhiều file
export KUBECONFIG=~/.kube/config:~/.kube/staging.yaml
kubectl config get-contexts

# Hoặc chỉ định tạm
kubectl --kubeconfig=/path/to/other.yaml get pods

Cảnh báo: luôn kiểm tra current-context trước khi chạy lệnh destructive (delete, scale 0). Nhầm context = sự cố production.


Các pattern thao tác chính

get — liệt kê resource

# Pod trong namespace hiện tại
kubectl get pods

# Tất cả namespace
kubectl get pods -A

# Output rộng hơn (node, IP)
kubectl get pods -o wide

# YAML đầy đủ
kubectl get pod my-app -o yaml

# JSON + jq filter
kubectl get pods -o json | jq '.items[].metadata.name'

# Lọc theo label
kubectl get pods -l app=my-api

# Lọc theo field
kubectl get pods --field-selector=status.phase=Running

# Nhiều resource cùng lúc
kubectl get pods,svc,deploy

describe — chi tiết + events

kubectl describe pod my-app
# Output bao gồm:
# - Spec: image, ports, resources, volumes
# - Status: conditions, container states
# - Events: scheduled, pulled, created, started, warning...

Events là nơi đầu tiên kiểm tra khi pod có vấn đề. Xem FailedScheduling, ImagePullBackOff, Unhealthy, OOMKilled

logs — đọc stdout/stderr của container

# Log container chính
kubectl logs my-app

# Follow (tail -f)
kubectl logs -f my-app

# Container trước (sau restart)
kubectl logs my-app --previous

# Pod multi-container: chỉ định container
kubectl logs my-app -c sidecar

# Tất cả container trong pod
kubectl logs my-app --all-containers

# Lọc theo label (nhiều pod)
kubectl logs -l app=my-api --max-log-requests=10

# Giới hạn dòng / thời gian
kubectl logs my-app --tail=100
kubectl logs my-app --since=1h

exec — chạy lệnh trong container

# Shell vào container
kubectl exec -it my-app -- /bin/sh

# Chạy lệnh đơn
kubectl exec my-app -- env
kubectl exec my-app -- cat /etc/resolv.conf

# Multi-container: chỉ định
kubectl exec -it my-app -c debug -- /bin/bash

Lưu ý: container production thường dùng distroless image — không có shell. Dùng kubectl debug (bài 15) thay thế.

port-forward — tunnel tạm từ local

# Forward port local 8080 → pod port 80
kubectl port-forward pod/my-app 8080:80

# Forward qua service
kubectl port-forward svc/my-api 8080:80

# Bind tất cả interface (chia sẻ với máy khác)
kubectl port-forward --address 0.0.0.0 svc/my-api 8080:80

Dùng để test nhanh mà không cần Ingress/LoadBalancer. Không dùng cho production traffic.


Resource short names

kubectl api-resources    # Liệt kê tất cả resource + short name

# Thường dùng:
# po  = pods
# svc = services
# deploy = deployments
# rs  = replicasets
# ds  = daemonsets
# sts = statefulsets
# cm  = configmaps
# ns  = namespaces
# no  = nodes
# ing = ingresses
# pvc = persistentvolumeclaims
# sa  = serviceaccounts

kubectl get po           # = kubectl get pods
kubectl get svc          # = kubectl get services
kubectl get deploy       # = kubectl get deployments

kubectl explain — tra cứu field tại chỗ

Thay vì Google “Kubernetes pod spec fields”:

# Top-level fields
kubectl explain pod
kubectl explain pod.spec

# Đệ quy tất cả
kubectl explain pod.spec --recursive

# Field cụ thể
kubectl explain pod.spec.containers.resources
kubectl explain pod.spec.containers.livenessProbe

# API version khác
kubectl explain deployment.spec.strategy --api-version=apps/v1

explain lấy schema trực tiếp từ API server — luôn đúng với version cluster đang chạy.


apply, create, delete

# Declarative (recommended)
kubectl apply -f deploy.yaml
kubectl apply -f ./k8s/          # Cả thư mục

# Imperative (nhanh, nhưng không có source of truth)
kubectl create deployment my-app --image=nginx
kubectl delete pod my-app

# Dry-run (kiểm tra trước khi apply)
kubectl apply -f deploy.yaml --dry-run=client
kubectl apply -f deploy.yaml --dry-run=server   # Qua admission webhook

# Diff (xem thay đổi sẽ apply)
kubectl diff -f deploy.yaml

Best practice: dùng apply (declarative) + file YAML trong Git. create/run chỉ cho lab/test nhanh.


Label và annotation thao tác

# Thêm label
kubectl label pod my-app team=backend

# Xoá label
kubectl label pod my-app team-

# Overwrite
kubectl label pod my-app version=v2 --overwrite

# Annotate
kubectl annotate pod my-app description="main API server"

# Filter
kubectl get pods -l 'app=my-api,version in (v1,v2)'
kubectl get pods -l 'app!=debug'

Thao tác nhanh hữu ích

# Xem tất cả resource trong namespace
kubectl get all -n staging

# Xem resource consumption
kubectl top pods              # Cần metrics-server
kubectl top nodes

# Watch real-time
kubectl get pods -w

# Scale nhanh
kubectl scale deploy my-app --replicas=5

# Rollout status
kubectl rollout status deploy/my-app

# Xem YAML mẫu (không tạo thật)
kubectl run tmp --image=nginx --dry-run=client -o yaml

Tóm tắt

  • kubectl nói chuyện với API server qua kubeconfig (context = cluster + user + namespace).
  • Luôn kiểm tra context trước lệnh destructive.
  • Pattern debug: getdescribe (events!) → logsexec / port-forward.
  • explain thay Google cho field reference — luôn đúng version.
  • apply (declarative) cho production; create/run cho lab nhanh.

Câu hỏi hay gặp

kubectl get all có thực sự trả về tất cả resource không?

Trả lời: Không. get all chỉ trả pod, service, deployment, replicaset, statefulset, daemonset, job, cronjob. Không bao gồm ConfigMap, Secret, Ingress, PVC, NetworkPolicy… Dùng kubectl api-resources + kubectl get <resource> cụ thể.

Làm sao biết mình đang ở namespace nào?

Trả lời: kubectl config view --minify -o jsonpath='{..namespace}'. Nếu trống, mặc định là default. Cài tool như kubens (kubectx package) để chuyển namespace nhanh và hiển thị rõ.

kubectl chậm, mất vài giây mỗi lệnh — nguyên nhân?

Trả lời: Thường do API server xa (latency mạng), kubeconfig dùng exec plugin chậm (cloud IAM token), hoặc cluster có nhiều webhook admission chạy lâu. Thử kubectl get pods -v=6 để xem timing từng HTTP request.


Bài tiếp theo (Giai đoạn II): Pod, container và lifecycle — vòng đời pod từ Pending đến Terminated.