Yaml
Do Minh Tan
Read Only
SỬA
note.yaml · 14,957 B
0
L ·
0
C
Loading
Note chuẩn bị thi K8s. explore: khám phá carry out: tiến hành impacted: ảnh hưởng reach the ETCD: truy cập vào ETCD realized : nhận ra aware: nhận thức Deployment - dùng build app vì không cần cố định/ Statefulset dùng build database vì cần cố định, PVC cố định. etcd: lưu database của k8s (config, file..v.v.). Nhận thông tin từ Kube Controller, gửi nhận qua API Kube Controller: - health check node - 5s/ check - 40s không nhận phản hồi --> Not Ready - Sau 5 phút, control sẽ đuổi pod khỏi node đó Kube Scheduler: - Filter Nodes: loại bỏ những node không đáp ứng điều kiện của Pod. - Rank Nodes: Ưu tiên resource để cho pod vào node đó Resource/ Taints/ Tolerations..v..v... Kubelet: Là endpoint nhận việc từ trên. Đăng ký node / Tạo pod / Monitor node&pod Labels: Tên nhãn của pod Selector: Bộ lọc filter giúp kết nối pod kubectl expose giúp tạo 1 service gắn vào 1 pod/ deploymet/ replica đã có, gắn qua Labels selector vd: kubectl expose deployment nginx-name --port=80 --target-port=8080 --type=ClusterIP Trong đó service là port 80/ container port 8080 kubectl get pod/ all --selector env=prod ex: lệnh này giúp filter pod có label env là prod kubectl get pod --selector env=prod,bu=finance,tier=frontend ex: filter nhiều labels cùng lúc kubectl taint nodes node01 spray=mortein:NoSchedule ex: tạo taints cho node muốn cho pod chạy vào node01 hãy thêm giấy phép: tolerations: - key: "spray" value: "mortein" operator: "Exists" effect: "NoSchedule" Taints: node-role.kubernetes.io/control-plane:NoSchedule ex: Như này là không cho pod chạy vào node này kubectl label nodes node01 color=blue ex: gắn label cho node, sau đó muốn pod chỉ chạy trong node01 thì sửa yaml (sửa trong nodeAffinity) trong deployment/ statefulset. Lưu ý khi copy nodeAffinity vào file yaml. Tạo deployment ra file yaml, sau đó thêm Affinity ở spec thứ 2/ thằng hàng containers. Nếu đề bài có value thì operator: In, nếu không có value chỉ có key thì operator: Exists Taint/Toleration = kiểm soát “được phép vào hay không” Affinity = chọn “muốn chạy ở đâu” ex: apiVersion: apps/v1 kind: Deployment metadata: labels: app: red name: red spec: replicas: 2 selector: matchLabels: app: red strategy: {} template: metadata: labels: app: red spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: node-role.kubernetes.io/control-plane operator: Exists # values: # - ssd containers: - image: nginx name: nginx resources: {} status: {} Trang này để quick command: https://kubernetes.io/docs/reference/kubectl/quick-reference/#kubectl-autocomplete Replicaset/ Demonset/ Deployment khi tạo cấu trúc sẽ là: - Nếu node có labels --> selector phải match, không thì không tạo được pod - Nếu node có taint thì phải match tolerations. match labels --> match taint DaemonSet dùng để mỗi node sẽ tạo 1 pod trên đó với điều kiện node đó không có labels hoặc taint. Nếu có phải tuân thủ theo node thì mới tạo được. Ứng dụng tạo pod: Network/ Log/ Monitoring..v..v.. Static Pod là tạo pod thủ công dựa trên file manifest, không thông qua API, tạo trực tiếp trên node, tạo trực tiếp bởi kubelet Note: Vì kubelet là thằng trực tiếp tạo manifest yaml, nên muốn xoá cần check path gốc file đó đang được ở đâu. 1. Dùng kubectl get pod -o wide (check đang nằm ở node nào) 2. Tiếp dùng kubectl get node -o wide (check IP internal node đó) 3. Tiến hành ssh vào. Check source gốc file manifest: /var/lib/kubelet/config.yaml (staticPodPath) --> tìm ra source gốc file manifest --> xoá. Quay lại controlpanel delete lại pod. Namespace-scoped: Pod Deployment Service ConfigMap Secret Cluster-scoped (cấp toàn cluster) Node Namespace PersistentVolume (PV) Storage cấp cluster PriorityClass Định nghĩa priority dùng chung ClusterRole / ClusterRoleBinding RBAC cấp cluster CustomResourceDefinition (CRD) Định nghĩa resource mới Preemption Policy: Pod priority cao đuổi Pod priority thấp ra khỏi node để lấy tài nguyên. Trừ khi preempt namespace-scoped: Nerver. Pod độ ưu tiên cao hơn sẽ phải chờ. Set ở ns-scoped: priorityClassName: high-priority preemptionPolicy: Never Thêm Priority trong 1 pod. kubectl get pod {name_pod} -o yaml > {name_pod}.yaml delete pod cũ sửa file yaml, thêm Priority, nếu có value thì ẩn đi, rồi create lại. Định nghĩa về Custom Scheduler: Custom scheduler dùng chung binary kube-scheduler Command gần giống nhau, khác ở --config và schedulerName (thằng này sau khai báo trong pod và sau spec, cùng hàng container). Mỗi custom scheduler chạy như một Pod riêng Pod chọn scheduler qua spec.schedulerName Các scheduler không tranh nhau Pod Có thể chạy nhiều instance và dùng leader election để HA --> Scheduler xử lý nhiều Pod là chuyện bình thường — vấn đề chỉ xảy ra khi có nhiều scheduler cùng lúc. Kubernetes Scheduler workflow: Queue: Pod vào hàng đợi, sắp xếp theo priority. Filter: Loại node không phù hợp (thiếu tài nguyên, sai label, taint…). Score: Chấm điểm các node còn lại (tài nguyên, affinity, image…). Select: Chọn node có điểm cao nhất. Bind: Gán pod vào node (DefaultBinder). → Kết quả: Pod được chạy trên node phù hợp nhất. spec.containers[*].image spec.initContainers[*].image spec.activeDeadlineSeconds spec.tolerations Resource: Request: Cần nói bao nhiêu Mục đích để scheduler (thởi điểm tạo pod scheduler sẽ lấy nhiều tài nguyên nhất có thể) có thể gọi ở mức nào cho phép: Tránh OMM kill nếu vượt memory limit Limits: Giới hạn bao nhiêu Mục đích để resource tối đa được dùng --> Dùng cả 2 thì pod sẽ được scheduler sắp xếp chính xác hơn. RBAC (Authorization) chỉ kiểm tra bạn có quyền thực hiện action (tạo/sửa/xoá) hay không, không quan tâm nội dung YAML. Sau đó, Admission Controller (Policy) là bước kiểm tra cuối, sẽ validate (từ chối) hoặc mutate (chỉnh sửa) resource để đảm bảo cấu hình đúng rule trước khi được tạo. Bật/ tắt Admission Controllers trong kube-apiserver **Khi thêm plugin trong kube-apiserver, set url trong config file (set đường dẫn thư mục yaml), sau đó phải set volume và mountVolume. (Tuỳ vào plugin mà cấu hình phù hợp) kubectl get configmaps -A - hostPath: path: /etc/kubernetes/imgvalidation/ type: DirectoryOrCreate name: imgvalidation kubectl apply → API Server → (Authentication → Authorization) → Admission Controllers → etcd Workflow: Request → Mutating (sửa request) → Validating (xác thực lại) → etcd kubectl get pod {pod} -o yaml sẽ lấy trực tiếp etcd. MutatingWebhookConfiguration cho phép webhook chỉnh sửa resource (như Pod) trước khi được tạo trong Kubernetes. Webhook có thể thêm hoặc ghi đè field, không có rule mặc định ưu tiên cấu hình từ Pod. Chỉ bị từ chối nếu webhook trả lỗi hoặc object sau khi mutate không hợp lệ/policy fail. **Cách tạo: Bạn deploy một service (Deployment + Service) expose API HTTPS. Trong MutatingWebhookConfiguration, bạn khai báo endpoint tới service đó. Khi có request tạo/sửa resource, Kubernetes sẽ gọi HTTP(S) vào service này để lấy quyết định (mutate/allow/reject). kubectl top pods/ node -A để check tài nguyên Kubectl edit deployment frontend Nếu thay đổi: Recreate → KHÔNG có rollingUpdate (dưới strategy:) - tạo lại toàn bộ pod RollingUpdate → CÓ rollingUpdate (dưới strategy:) - tạo lại 1 pod kubectl rollout history deployment frontend (check version update) kubectl rollout undo deployment --to-revision=1 (roll back lai version 1) Kube command: command = chương trình chính bạn muốn chạy args = tham số truyền vào chương trình đó kubectl create configmap webapp-config-map --from-literal=APP_COLOR=darkblue --from-literal=APP_OTHER=disregard khi kubectl get pod -o yaml > pod.yaml để sửa file, hãy thêm ở - sau spec.containers: kubectl create secret generic (tạo secret) tương tự configmap **Cần load Env dùng envFrom - secretRef, còn load configmap dùng: envFrom - configMapRef Multi-container Pod dùng khi cần chia sẻ tài nguyên, network nhanh, thường dùng lưu log, monitor, proxy..v..v.. Khi tạo mutil-container pod thì thêm lệnh command: ["sleep","1000"] vào container thứ 2 kubectl exec -it app -- /bin/sh để truy cập vào container trong pod Container side-car (initContainers) là container phụ, chuyên để hỗ trợ container chính (app). Trong file yaml khi tạo thì dùng initContainers, bằng containers. Thằng này thường chạy xong app hoặc command khi create pod, chạy xong sẽ dừng. Nếu không có file manifest, hãy dùng kubectl get pod red -o yaml > red.yaml, sửa file yaml thêm initContainers (ngay trên status, ngang containers) Skooner - công cụ monitor Ingress = lớp định tuyến web (HTTP/HTTPS) vào Kubernetes cluster kubectl scale deployment nginx-deployment --replicas=3 kubectl autoscale deployment nginx-deployment --max=3 --cpu=80% Ưu điểm của HPA là scale theo resource hoặc metric nếu có metrics-server là máy chủ đo lường toàn bộ resource hệ thống, HPA chỉ là quyết định scale. kubectl events hpa nginx-deployment | check event hpa, thay cho check log VPA CRDs = định nghĩa resource tùy chỉnh giúp Kubernetes hiểu và chạy được cơ chế autoscaling theo chiều dọc (tăng/giảm CPU, RAM) cho Pod. kubectl get crds = xem danh sách tất cả “resource custom” đã được cài thêm vào Kubernetes cluster. (Extension cài ngoài như: VPA, ArgoCD, Prometheus…) kubectl get vpa để check target CPU kubectl drain --ignore-daemonsets xoá toàn bộ pod ra khỏi 1 node bao gồm daemonsets (Lưu ý không dùng lệnh này cho Pod standalone/ staticpod vì xoá là mất sạch luôn, nên dùng deployment, statefulset) kubectl cordon node01 (SchedulingDisabled- không nhận pod mới) kubectl uncordon node01 (Bật lại scheduling, có thể nhận pod mới) ### UPGRADE Chỉ update 1 version 1 lần, không nhảy bậc được Update từng node 1, vd như controlplane đầu tiên: Update controlplane từ v1.34 -> v1.35: Đổi version /etc/apt/sources.list.d/kubernetes.list Lấy key 1.35: curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.35/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg apt-cache madison kubeadm (để hiện ra version đã tải về) *update kubeadm: sudo apt-mark unhold kubeadm && \ sudo apt-get update && sudo apt-get install -y kubeadm='1.35.0-1.1' && \ sudo apt-mark hold kubeadm kubeadm upgrade apply v1.35.0-1.1 *update kubelet: sudo apt-mark unhold kubelet kubectl && \ sudo apt-get update && sudo apt-get install -y kubelet='1.35.0-1.1' kubectl='1.35.0-1.1' && \ sudo apt-mark hold kubelet kubectl Update sang node khác, phải ssh vào node đó r cấu hình tương tự, vd: ssh node01 #Backup etcdctl --endpoints https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key snapshot save /tmp/snapshot-pre-boot.db #Restore Step 1: Stop the kube-apiserver move kube-apiserver.yaml ra tmp mkdir dir backup, ex: /var/lib/etcd-bkup (vứt tạm ra đây sau đó mount vào etcd) etcdutl snapshot restore /opt/snapshot-pre-boot.db --data-dir /var/lib/etcd-bkup Sửa file: /etc/kubernetes/manifests/etcd.yaml Chỉnh path etcd-certs ở data-dir trên. Restart kube-controller-manager & kube-scheduler & kubelet Cứ di chuyển ra ngoài xong lại di chuyển vào là xong trong /etc/kubernetes/manifests/ systemctl restart kubelet Check: kubectl get deployments,services -A openssl x509 -in /etc/kubernetes/pki/apiserver.crt -text | grep api (để check CN) 127.0.0.1:2379 là tới pod của etcd tls: failed to verify certificate: x509: cert --> cert sai #CSR: Key seach: Encode CSR convert sang base64, thay vào code mã hóa request trong CertificateSigningRequest --> apply --> kubectl get csr --> kubectl certificate approve akshay kubectl get csr agent-smith -o yaml để check chi tiết cert kubectl certificate deny agent-smith để deny cert request tới kubectl delete csr agent-smith để xóa cert kubectl config set-context dev-context --cluster=test-cluster-1 --user=dev-user #Tạo context cho user mới my-kube-config file as the default kubeconfig file --> export KUBECONFIG=/root/my-kube-config kubectl auth can-i list pod --as dev-user: Check dev-user có quyền list pod không # Tạo role + rolebinding Role: Được phép làm gì/ Rolebinding: Được phép làm ở đâu, resource hay user nào. Tạo role: kubectl create role developer --verb=create --verb=list --verb=delete --resource=pods --namespace=default --dry-run=client -o yaml > role-developer.yaml (--resource-name=anotherpod --verb=get) thêm 2 field này để check detail 1 pod. Gắn role: kubectl create rolebinding --namespace=default dev-user-binding --role=developer --user=dev-user --dry-run=client -o yaml > role-binding-dev-user.yaml Kiểm tra các tài nguyên không thuộc namespace: kubectl api-resources --namespaced=false #Cluster role: Tương tự role: kubectl create clusterrole storage-admin --verb=get,list,watch --resource=persistentvolumes,storageclasses --dry-run=client -o yaml > roles-2.yaml kubectl create clusterrolebinding michelle --clusterrole=storage-admin --user=michelle --dry-run=client -o yaml > cluster-roles-2.yaml Tóm tắt chính: ServiceAccount: tạo tài khoản Role: Tạo role (list/get/delete/watch..v..v..) và resource cấp phép RoleBinding: Để gắn Role và ServiceAccount #ServiceAccount Tách quyền truy cập API khỏi ServiceAccount mặc định: kubectl edit sa dashboard-sa -n default --> thêm: automountServiceAccountToken: false Thêm ServiceAccount vào deployment: kube edit deployment --> spec.template.spec.serviceAccountName
Nhập mật khẩu
LƯU THAY ĐỔI
HỦY