發表文章

04 - Commands and Arguments

圖片
CMD vs ENTRYPOINT 差異比較 CMD 是什麼? CMD 用來指定 預設要執行的命令或參數 。 如果你在執行容器時提供了命令或參數,那麼 CMD 的內容會被 覆蓋掉 。 通常搭配 ENTRYPOINT 使用,用來提供預設參數。 範例: ``` CMD ["echo", "Hello from CMD"] ``` 執行: ``` docker run myimage # 輸出:Hello from CMD docker run myimage echo "我自訂的訊息" # 輸出:我自訂的訊息(CMD 被覆蓋) ``` ENTRYPOINT 是什麼? ENTRYPOINT 用來定義容器啟動時 一定會執行的主命令 。 不會被 docker run 的參數覆蓋 (除非你用 --entrypoint 明確指定)。 適合讓容器專注執行某個固定的程式或腳本。 範例: ``` ENTRYPOINT ["echo"] ``` 執行: ``` docker run myimage "來自 ENTRYPOINT" # 輸出:來自 ENTRYPOINT ``` CMD + ENTRYPOINT 一起使用 當你同時使用這兩個指令時: ENTRYPOINT 是 主命令 (command) CMD 是 預設參數 (arguments) 範例: ``` ENTRYPOINT ["echo"] CMD ["Hello from CMD"] ``` 執行: ``` docker run myimage # 輸出:Hello from CMD docker run myimage "嗨!" # 輸出:嗨!(CMD 被自訂參數取代) ``` 總結比較表

04 - Rolling Updates and Rollbacks

圖片
Q: Inspect the deployment and identify the number of PODs deployed by it Ans: 4 $ kubectl get deploy                                               $ kubectl describe deployment | grep -i Desired         Replicas:  4 desired | 4 updated | 4 total | 4 available | 0 unavailable Q: Inspect the deployment and identify the current strategy $ kubectl describe deployment frontend | grep -i StrategyType              Ans: StrategyType: RollingUpdate Q: If you were to upgrade the application now what would happen? Ans: PODs are upgraded few at a time Q: Let us try that. Upgrade the application by setting the image on the deployment to `kodekloud/webapp-color:v2`.  Do not delete and re-create the deployment. Only set the new image name for the existing deployment. Deployment Name: frontend D...

03 - Managing Application Logs

圖片
Q: A user - USER5 - has expressed concerns accessing the application. Identify the cause of the issue. Inspect the logs of the POD $ kubectl logs webapp-1              Q: A user is reporting issues while trying to purchase an item. Identify the user and the cause of the issue. Inspect the logs of the webapp in the POD $ kubectl logs webapp-2 -c simple-webapp              說明: webapp-2:目標 Pod 的名稱。 -c simple-webapp: 指定要查看的容器名稱 (如果 Pod 中有多個容器時必須指定)。 預設會印出該容器目前的 stdout/stderr log。

03 - Monitor Cluster Components

圖片
🏆 最常見的監控解法總覽 如:Metrics Server、Prometheus、Elastic Stack、Datadog、Dynatrace Metrics Server 📈 metrics-server 是什麼? metrics-server 是 K8s 中用來提供資源用量資訊(非歷史紀錄),例如: $ kubectl top node           $ kubectl top pod            HPA(Horizontal Pod Autoscaler)的依據 Cluster Autoscaler 的依據(間接) 📌 注意:它不是用來做長期監控或歷史查詢(那是 Prometheus 的角色)。 🚀 安裝 metrics-server 建議方式(官方部署,預設會在 kube-system namespace 中建立 Deployment) $ kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml             

02 - Validating and Mutating Admission Controllers

圖片
Validating and Mutating Admission Controllers 🔧 Mutating Admission Controller(變更型) ✅ 功能: 修改用戶提交的資源物件 常用於補上預設值、標籤、或注入 Sidecar 📌 實際用途: 自動加入監控 sidecar(如 Istio、Datadog) 補上預設 labels 或 annotations 加入預設的資源限制(CPU/記憶體) 加上 Tolerations、Node Affinity 等 🧩 常見元件: MutatingAdmissionWebhook MutatingAdmissionPolicy(Kubernetes 1.28+ GA) 🔍 Validating Admission Controller(驗證型) ✅ 功能: 驗證資源是否合法,若不符合條件則拒絕執行 無法修改資源,只能判斷通過或拒絕 📌 實際用途: 拒絕使用 latest image tag 禁止容器使用 root 權限 限制只能使用特定的 StorageClass 確保所有物件都有必要的 label 🧩 常見元件: ValidatingAdmissionWebhook ValidatingAdmissionPolicy(Kubernetes 1.28+ GA) 執行順序(流程圖) 1️⃣ 使用者發送 API 請求      ↓ 2️⃣ 驗證身份與權限(Authentication / Authorization)      ↓ 3️⃣ Mutating Admission Controller(如需修改)      ↓ 4️⃣ Validating Admission Controller(檢查是否合法)      ↓ 5️⃣ 通過後寫入 etcd,開始執行 Q: Which of the below combination is correct for Mutating and validating admission controllers ? Ans: NamespaceAutoProvision - Mutating, NamespaceExists - Va...

02 - Admission Controllers

圖片
Admission Controllers 🌐 Admission Controllers 是什麼? Admission Controllers 是 Kubernetes API Server 中的一個 請求攔截點(intercept point),當使用者送出請求(例如 `kubectl apply -f xxx.yaml`)時,在這個請求被持久化到 etcd 前,Admission Controller 會進行額外的驗證、修改或拒絕。 Admission Controllers 位於 API Server 處理流程中的 驗證(Authentication)與授權(Authorization)之後,物件寫入 etcd 之前。 Note: the `Namespace Auto Provision` and `Namespace Exists` at admission controllers are deprecated and is now replaced by the `Namespace Lifecycle` Admission Controller. The `namespace lifecycle` admission controller will make sure that requests to a non-existent namespace is rejected and that the default namespace, such as default kube-system and kube-public cannot be deleted . ✨ 分類:Mutating vs Validating 🔧 常見內建 Admission Controllers NamespaceLifecycle 禁止在 Terminating 的 Namespace 中創建新資源 LimitRanger 根據 Namespace 設定限制 Pod 的資源使用 ServiceAccount 自動注入預設的 ServiceAccount 到 Pod ResourceQuota 強制資源配額 NodeRestriction 限制 kubelet 操作非自身的 Node 資源 🌐 Webhook 型 Admission C...

02 - Multiple Schedulers

圖片
Kubernetes Multiple Schedulers 📌 為什麼需要多個 Scheduler? Kubernetes 預設使用 kube-scheduler 處理所有 Pod 的排程任務。 但某些場景下,我們可能需要: 使用不同策略排程不同類型的工作負載(ex: ML Job、批次任務) 為特定隊列、優先級、資源需求定制排程邏輯 測試自定義排程演算法(研究用) ⚙️ 如何實作 Multiple Schedulers? 在 cluster 中「同時部署多個 scheduler」,然後讓特定 Pod 使用你指定的 scheduler 名稱進行排程。 1️⃣ 設計你的排程架構 假設你要: 使用原生 default-scheduler 處理一般 workload 使用 custom-scheduler 處理 ML/批次任務 未來可能擴充更多 scheduler 你可以這樣規劃: 2️⃣ 撰寫或部署自定義 Scheduler 可以是: Fork 官方 kube-scheduler 修改排程邏輯(進階) 用 Go/Python 等語言實作一個簡單的排程邏輯 或使用現成的開源方案(如 Volcano、YuniKorn) 建立自定義 Scheduler 後,打包為 Docker Image。 3️⃣ 部署到 Kubernetes 以一個最簡單的 custom scheduler 為例(custom-scheduler-deploy.yaml): ``` apiVersion: apps/v1 kind: Deployment metadata:   name: custom-scheduler spec:   replicas: 1   selector:     matchLabels:       component: custom-scheduler   template:     metadata:       labels:         component: custom-scheduler     spec:      ...

02 - Static PODs

圖片
Static Pod Static Pods 是 Kubernetes 內部機制,用來在特定節點上直接執行 Pod。 Static Pods 由 Kubelet 直接管理,不經 API Server。 適用於: Kubernetes 控制面節點 (Control Plane) 的核心元件 (如 kube-apiserver, kube-controller-manager, kube-scheduler, etcd) 在特定節點上執行的系統服務 ,不受 Deployment 或 DaemonSet 控制 不依賴 Kubernetes API 來管理 Pod Static Pod 的特點 ✅ 不經過 API Server ,而是由 Kubelet 直接監控和管理   ( 修改或刪除 Pod,直接編輯或刪除 YAML 檔案即可 ) ✅ 只會在特定節點上運行 ,不會自動調度到其他節點 ✅ 沒有 ReplicaSet、Deployment 或 DaemonSet 控制 ✅ YAML 檔案 存放於節點的 staticPodPath 目錄 =  /etc/kubernetes/manifests/ ✅ Pod 會自動重啟 ,但 不會自動恢復或遷移 到其他節點 查看 Static Pods $ kubectl get pods --all-namespaces                 $ kubectl get pods -o wide                                注意: Static Pod 只會在該節點上執行 ,且不會顯示在 kubectl get deployments 或 kubectl get daemonsets 裡。 刪除 Static Pod Static Pods 無法透過 `kubectl delete pod` 刪除,因為它們由 Kubelet 自動管理。 $ sudo rm /etc/kubernetes/manifests/static...

02 - DaemonSets

圖片
DaemonSet DaemonSet 是 Kubernetes 中的一種資源類型,用來 確保每個節點 (Node) 都執行「一個」特定的 Pod 。這通常用於執行節點級別的系統服務,例如: 日誌收集 (如 Fluentd、Filebeat) 監控代理 (如 Prometheus Node Exporter) 網路代理 (如 Cilium, Calico, Istio) DaemonSet 的特性 ✅ 確保所有 符合條件的節點 都會 執行一個 Pod ✅ 當有新節點加入 (或移除) 叢集時,自動新增 (或刪除) Pod ✅ 支援節點選擇器 (Node Selector)、親和性 (Affinity) 及 污點與容忍度 (Taints & Tolerations), 可精細控制 Pod 的調度策略 ✅ 不需要手動擴展副本數 (replicas) ,它會 根據節點數量自動調整 摘要:DaemonSet vs Deployment 何時使用 DaemonSet? ✅ 確保每個節點(Node)都需要運行一個同樣的 Pod (如 監控、日誌收集、網路代理) ✅ 當 Pod 需要存取主機資源 (如 hostPath 掛載 /var/log) ✅ 當 Pod 必須與節點一起運行,不受負載均衡影響 如果你的應用是 水平擴展 (Scaling out) 的服務,應該 選擇 使用 Deployment 。 如果你要在  每個節點上運行一個 Pod ,那就選擇 DaemonSet !

02 - Resource Requirements and Limits

圖片
參考資源 [K8s] Manage Memory, CPU, and API Resources [K8s] Limit Ranges [K8s] Configure Default CPU Requests and Limits for a Namespace [K8s] Configure Default Memory Requests and Limits for a Namespace [Udemy] 第66、67堂課:Resource Requirements and Limits

02 - Node Affinity

圖片
Node Affinity(節點親和性) Node Affinity 是 Kubernetes 調度 Pod 到特定節點 (Node) 的機制。 它比 nodeSelector 更靈活,允許你設定多種匹配條件。 [K8s] Node Affinity Node Affinity 主要有 三種模式: required DuringScheduling Ignored DuringExecution Required 強制規則 , Pod 只會調度到符合條件的節點 ,否則調度失敗。 preferred DuringScheduling Ignored DuringExecution Preferred 軟性規則 ,Kubernetes 會嘗試將 Pod 調度到符合條件的節點,但 如果沒有符合的節點,也會允許調度到其他節點 。 required DuringScheduling Required DuringExecution 這種模式在 調度時和執行時 都強制應用。 常見 operator: In:允許特定值,例如 color=blue NotIn:禁止特定值,例如 color != blue Exists:只要該 key 存在即可,不管值是什麼 DoesNotExist:只允許該 key 不存在的節點 Required(強制規則) Pod 只能調度到 color=blue 的節點。 🚫 如果沒有符合的節點,Pod 會卡住 (Pending),不會被調度! ``` apiVersion: apps/v1 kind: Deployment metadata:   name: blue-app spec:   replicas: 3   selector:     matchLabels:       app: nginx   template:     metadata:       labels:         app: nginx     spec:       affinity:         ...

02 - Taints and Tolerations

圖片
摘要 Taints  與 Tolerations  是 Kubernetes 中用來 控制 Pod 調度到哪些節點 的機制。 [K8s] Taints and Tolerations ✅ Taints 設定在 節點 上,防止 Pod 調度到該節點 ✅ Tolerations 設定在 Pod 上,使其能夠忽略某些 Taints ✅ 透過 NoSchedule、PreferNoSchedule、NoExecute 來 控制 Pod 的行為 ✅ 控制特定 Pod 運行在特定節點, 提升調度靈活性 這個機制在 Kubernetes 多節點部署 、 資源隔離 、 避免影響關鍵應用 時非常有用 🚀 Taints(污點) Taint 是設定在  節點 (Node) 上的屬性,它告訴 Kubernetes 不要在該節點上調度沒有相應 Toleration(容忍度)的 Pod。 $ kubectl taint node <node-name> <key>=<value>:<effect>    <node-name> → 要添加 taint 的節點名稱 <effect> → taint 的影響方式 NoSchedule → 禁止 沒有匹配 Toleration 的 Pod 被調度到該節點 PreferNoSchedule → 盡量避免 調度,但不是強制的 NoExecute → 不僅 禁止 調度,還會 驅逐 已經在該節點上的不符合 Toleration 的 Pod Tolerations(容忍度) Toleration 設定在 Pod 上,允許 Pod 忽略某些 Taint(污點),從而能夠被調度到相應的節點。 在 Pod 規範 (pod.yaml) 中添加 tolerations: ``` apiVersion: v1 kind: Pod metadata:   name: my-pod spec:   tolerations:     - key: "dedicated"       operator: "Equal"       value: "...

02 - Labels and Selectors

圖片
Q: How many PODs exist in the dev environment (env)? ※ Use selectors to filter the output $ kubectl get pods --selector env=dev                                       $ kubectl get pods --selector bu=finance --no-headers | wc -l    $ kubectl get pods --show-labels=true                                       Q: How many objects are in the prod environment including PODs, ReplicaSets and any other objects ? $ kubectl get all --selector env=prod                                         $ kubectl get all --selector env=prod --no-headers | wc -l          Q: Identify the POD which is part of the prod environment, the finance BU and of frontend tier? $ kubec...

02 - Manual Scheduling

Q: Manually schedule the pod on "node01"   kubectl replace --force    =  kubectl delete  +  kubectl create Method 1: kubectl replace $ vim nginx.yaml                                   $ kubectl replace --force -f nginx.yaml       --- apiVersion: v1 kind: Pod metadata: name: nginx spec: nodeName: node01 containers: - image: nginx name: nginx Method 2: kubectl delete + kubectl create Delete the existing pod first. $ kubectl delete po nginx To list and know the names of available nodes on the cluster: $ kubectl get nodes Add the "nodeName" field under the spec section in the nginx.yaml file with " node01 "  as the value: --- apiVersion: v1 kind: Pod metadata: name: nginx spec: nodeName: node01 containers: - image: nginx name: nginx Create a pod from the definition...

01 - Core Concepts - Imperative Commands

Imperative Commands $ kubectl run --help                                    $ kubectl create service --help                     $ kubectl create service clusterip --help        $ kubectl expose --help                               [Doc] kubectl expose kubectl expose 主要用來將 Kubernetes Pod、Deployment、ReplicaSet 或 Service 暴露成一個新的 Kubernetes Service,允許內部存取(ClusterIP)或外部存取(NodePort, LoadBalancer)。 $ kubectl run custom-nginx --image=nginx --port=8080            $ kubectl create deployment  < deployment -name>  --image= < image -name>  --replicas=2 -n  <namespace-name>        

01 - Core Concepts - Services

圖片
Services $ kubectl get service        $ kubectl get svc             That is a default service created by Kubernetes at launch. $ kubectl describe service                        $ kubectl describe svc <service-name>      Day 09 -【Basic Concept】:Service

01 - Core Concepts - Namespaces

圖片
Namespaces $ kubectl get namespaces                     $ kubectl get ns                                   $ kubectl get ns --no-headers | wc -l    Look for existing Namespaces. $ kubectl get pods --all-namespaces            $ kubectl get pods -A                                  $ kubectl get pods -o wide -A                                   $ kubectl get pods -o wide -A | grep  <xxx-name>        Q: How many pods exist in the research namespace? $ kubectl get pods --namespace= <namespace-name>                        $ kubectl get pod...

01 - Core Concepts - Deployments

圖片
Deployments $ kubectl get deployments          $ kubectl get deploy                  Get the current Deployments deployed. $ kubectl describe deploy <deployment-name>         Get detailed information about Deployment. $ kubectl explain deploy                             $ kubectl explain deploy | head -n3             Get the documentation of the resource and its fields. $ kubectl api-resources | grep deploy           

01 - Core Concepts - ReplicaSets

ReplicaSets $ kubectl get replicaset        $ kubectl get rs                   Get the current ReplicaSets deployed. $ kubectl describe rs  <replicaset-name>           Get detailed information about ReplicaSet. $ kubectl delete pod <pod-name1>  <pod-name2>   <pod-name3>      $ kubectl delete rs  <replicaset-name>                                           $ kubectl delete -f <file-name>.yaml                                             Delete pods/ReplicaSet. Q: Why are there still 4 PODs, even after you deleted one? A: ReplicaSet ensures that desired number of PODs always run Fix...

01 - Core Concepts - Pods

圖片
學習目標 Pods ReplicaSets Deployments Namespaces Services Imperative Commands Pods $ kubectl get pods                         $ kubectl get pod  <pod-name>       Look for existing Pods. $ kubectl get pods                        NAME       READY       STATUS               RESTARTS    AGE newpod     1  / 1           Running                0                  10m webapp     1  / 2          ImagePullBackOff   0                  2m49s READY   ➜  Running Containers in Pod  / Total Containers in Pod $ kubectl ge...