<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Container - 東東 GCP 教學 - GCP 實戰講師</title>
	<atom:link href="https://dongdonggcp.com/tag/container/feed/" rel="self" type="application/rss+xml" />
	<link>https://dongdonggcp.com</link>
	<description>助你考取證照，轉職成功</description>
	<lastBuildDate>Sat, 21 Nov 2026 10:47:55 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://dongdonggcp.com/wp-content/uploads/2025/04/cropped-340838097_121391010914395_5443948698124160121_n-32x32.jpg</url>
	<title>Container - 東東 GCP 教學 - GCP 實戰講師</title>
	<link>https://dongdonggcp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</title>
		<link>https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=cloud-run-vs-gke-vs-compute-engine</link>
					<comments>https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:35:09 +0000</pubDate>
				<category><![CDATA[雲端架構]]></category>
		<category><![CDATA[Cloud Run]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[GKE]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[Serverless]]></category>
		<category><![CDATA[容器]]></category>
		<category><![CDATA[無伺服器]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13544</guid>

					<description><![CDATA[<p>Cloud Run vs GKE 怎麼選？加上 Compute Engine 一張表比較控制權、計費、冷啟動、GPU，再用台灣 asia-east1 單價算小網站、背景工作、GPU 推論一個月各多少錢。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/">Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Cloud Run vs GKE 怎麼選？只交容器選 Cloud Run，要用 K8s 選 GKE，要管機器選 Compute Engine。</strong></p>



<p class="wp-block-paragraph">第 19～26 篇把同一個容器先後放上 Artifact Registry、Cloud Run、Cloud Build、GKE。做到這裡，最常被問的問題變成：「我的東西到底該放哪裡？」這篇不動手做，改用前面幾篇<strong>實際量到的數字</strong>，把 Google Cloud 三個最常見的運算服務放在同一張表上比。</p>



<p class="wp-block-paragraph">這篇會做三件事：一張比較表（控制權、計費、縮到零、冷啟動、維運負擔、狀態、GPU、適合誰）、一個照順序問自己的判斷流程，還有三個常見情境（小網站、24 小時背景工作、GPU 推論服務）用三種服務<strong>各算一次一個月要多少錢</strong>。</p>



<p class="wp-block-paragraph">這是「容器系列」第 27 篇。單價是 2026 年 11 月查官方定價頁和 Cloud Billing Catalog API 的台灣 <code>asia-east1</code> 牌價，實測數字來自本系列第 20～24 篇（2026 年 11 月在 Cloud Shell 跑的），以後可能調整。</p>



<figure class="wp-block-image aligncenter size-full"><img fetchpriority="high" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-01-compare.png" alt="Cloud Run vs GKE vs Compute Engine 比較：Cloud Run 交出一個容器映像檔，Google 全包，有請求才計費，沒人用縮到 0 台；GKE 交出 K8s 的 YAML，控制平面 Google 管，收叢集管理費加 Pod 或節點費用；Compute Engine 交出整台虛擬機器，作業系統自己管，機器開著就收錢" class="wp-image-13541" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-01-compare.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-01-compare-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-01-compare-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-01-compare-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>選錯服務，帳單可以差 5 倍以上</strong>：同一個每月 300 萬次請求的小網站，這篇算出來 Cloud Run 約 10.48 美元、GKE 約 59.42 美元、Compute Engine 約 60.47 美元</li>

<li><strong>「Cloud Run 一定最便宜」不是真的</strong>：24 小時一直在跑的背景工作，Compute Engine 反而最便宜；GPU 一天用超過約 15 小時，虛擬機器也比 Cloud Run 划算</li>

<li><strong>網路上的比較文很多過時了</strong>：計費方式這兩年改了好幾次（Cloud Run 多了以執行個體計費和 worker pools，GKE Autopilot 改成照 Pod 計費），舊的「Cloud Run 照請求、GKE 照機器」分法已經不準</li>

<li><strong>證照最愛考這題</strong>：ACE、PCA 的情境題常常就是「這個需求該放 Cloud Run、GKE 還是 Compute Engine」，看關鍵字就能判斷</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">三個選項是什麼：從「長租一台車」到「叫計程車」</h2>



<p class="wp-block-paragraph">這三個服務都能跑你的程式，差別在<strong>你要顧多少東西</strong>。先用交通工具比喻一次：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>比喻</th><th>你要顧的</th><th>Google 幫你顧的</th></tr></thead><tbody><tr><td><strong>Compute Engine</strong></td><td>長租一台車</td><td>作業系統、軟體安裝、更新、擴充</td><td>機房、實體機器、網路</td></tr><tr><td><strong>GKE</strong></td><td>經營一個車隊，有調度中心</td><td>Kubernetes 的設定、Pod、（Standard 還要顧節點）</td><td>控制平面，Autopilot 連節點也顧</td></tr><tr><td><strong>Cloud Run</strong></td><td>叫計程車</td><td>你的容器映像檔</td><td>機器、擴展、HTTPS 網址，全部</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">越往下，你要顧的越少，能調的也越少。</p>



<h3 class="wp-block-heading">Compute Engine：整台虛擬機器給你</h3>



<p class="wp-block-paragraph"><strong>Compute Engine 是 Google Cloud 出租虛擬機器（VM）的服務：你選 CPU、記憶體、磁碟、作業系統，拿到一台完整的電腦，裡面要裝什麼、怎麼設定都自己決定。</strong></p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：長租一台車。要開去哪、加什麼油、多久保養都你決定；車停在車庫沒開，租金照付</li>

<li><strong>來龍去脈</strong>：這是雲端最早的形式（基礎架構即服務，IaaS），把「買伺服器放機房」換成「線上租一台」。很多公司第一步上雲，就是把原本的伺服器原封不動搬過來（官方叫 lift and shift，直接搬遷）</li>

<li><strong>為什麼要學</strong>：Cloud Run、GKE 的底層其實也是這些虛擬機器。懂 VM 的計費和限制，才看得懂另外兩個服務幫你省了什麼、又多收了什麼</li>
</ul>



<p class="wp-block-paragraph"><strong>虛擬機器</strong>（VM，Virtual Machine）是用軟體切出來的一台電腦，有自己的作業系統，跟實體電腦用起來幾乎一樣。<strong>作業系統</strong>是管理電腦硬體、讓程式能跑的基礎軟體，例如 Linux、Windows。站上有一篇<a href="https://dongdonggcp.com/2024/10/23/what-is-google-vm-compute-engine-introduction/">Compute Engine 是什麼</a>的介紹。</p>



<h3 class="wp-block-heading">GKE：Google 代管的 Kubernetes</h3>



<p class="wp-block-paragraph"><strong>GKE（Google Kubernetes Engine）是 Google Cloud 代管的 Kubernetes 服務：控制平面 Google 顧，你用 <code>kubectl</code> 和 YAML 管理一群容器。</strong>第 24 篇實際建過叢集，有 Autopilot（Google 管節點、照 Pod 計費）和 Standard（自己管節點、照 VM 計費）兩種模式。</p>



<p class="wp-block-paragraph">比喻是經營車隊：Kubernetes 是調度中心，決定哪台車去載哪位客人、車壞了派哪台補上。Standard 是車隊自己買車；Autopilot 是跟車行說「我要 3 個座位」，車行派車，你照座位付錢。</p>



<h3 class="wp-block-heading">Cloud Run：只交容器，其他全包</h3>



<p class="wp-block-paragraph"><strong>Cloud Run 是 Google Cloud 的全代管容器平台：你交出一個容器映像檔，它給你 HTTPS 網址、自動擴展，沒人用時縮到 0 台。</strong>第 20 篇實測從部署到拿到網址只要 11.7 秒，第 23 篇看過它還有 Jobs（跑完就結束）、functions（只寫一段函式）、worker pools（一直在背景做事）幾種跑法。</p>



<p class="wp-block-paragraph">比喻是叫計程車：有乘客才跳錶，沒人搭不用付錢；但車子怎麼開、走哪條路你管不到。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">一張表比較：Cloud Run、GKE、Compute Engine</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Cloud Run</th><th>GKE（以 Autopilot 為主）</th><th>Compute Engine</th></tr></thead><tbody><tr><td><strong>控制權</strong></td><td>只能設 CPU、記憶體、並行數、環境變數，底層不能改</td><td>完整 Kubernetes：網路政策、StatefulSet、DaemonSet、外掛；Standard 還能選機型</td><td>整台機器：作業系統、核心、任何軟體</td></tr><tr><td><strong>計費方式</strong></td><td>預設以請求計費，100 毫秒一格；也可選以執行個體計費</td><td>每個叢集每小時 0.10 美元管理費（每月 74.40 美元免費額度抵一個）＋ Pod 的資源要求</td><td>機器開著就收，以秒計（最少 1 分鐘）</td></tr><tr><td><strong>沒人用時</strong></td><td>縮到 0 台，不收 CPU、記憶體費</td><td>Pod 還在就照收；要縮到 0 得另外設定</td><td>沒關機就照收</td></tr><tr><td><strong>擴展</strong></td><td>自動，依請求數增加執行個體</td><td>HPA 依 CPU 等指標增加 Pod，Autopilot 自動開節點</td><td>要自己設代管執行個體群組（MIG）才會自動擴展</td></tr><tr><td><strong>冷啟動</strong></td><td>第 22 篇實測縮到零後第一個請求 0.947 秒（熱請求約 0.04 秒）</td><td>第 24 篇實測 Autopilot 第一次部署約 1 分鐘（等開節點）</td><td>開機才算，這個系列沒實測</td></tr><tr><td><strong>上線速度</strong></td><td>第 20 篇實測部署 11.7 秒拿到網址</td><td>第 24 篇實測建叢集 6 分 31 秒，LoadBalancer 57 秒拿到 IP</td><td>建 VM 後還要裝軟體、設網頁伺服器</td></tr><tr><td><strong>維運負擔</strong></td><td>最低：不用管作業系統、憑證、擴展</td><td>中：要懂 Kubernetes，叢集升級 Google 自動做</td><td>最高：作業系統更新、安全修補、備份都自己來</td></tr><tr><td><strong>狀態與長連線</strong></td><td>檔案系統在記憶體裡，執行個體關掉就不見；一個請求最多 60 分鐘</td><td>可以掛永久磁碟（第 16 篇的 PV、PVC），連線不限時</td><td>磁碟、連線都自己決定</td></tr><tr><td><strong>GPU</strong></td><td>有 L4，但台灣 asia-east1 沒有，亞洲最近是新加坡</td><td>台灣 asia-east1 有 L4（G2 機型），照整台節點計費</td><td>台灣 asia-east1 有 L4（g2-standard 系列）</td></tr><tr><td><strong>適合誰</strong></td><td>網站、API、Webhook、排程批次、偶爾用的 GPU 推論</td><td>很多服務互相呼叫、有狀態服務、已經在用 Kubernetes 的團隊</td><td>舊系統直接搬、指定作業系統或 Windows、要改核心</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/gke-and-cloud-run">官方 GKE 與 Cloud Run 比較</a>、<a href="https://cloud.google.com/run/pricing">Cloud Run 定價</a>、<a href="https://cloud.google.com/kubernetes-engine/pricing">GKE 定價</a>、<a href="https://cloud.google.com/run/quotas">Cloud Run 上限</a>、<a href="https://cloud.google.com/run/docs/configuring/services/gpu">Cloud Run GPU</a>、<a href="https://cloud.google.com/compute/docs/gpus/gpu-regions-zones">GPU 區域</a>）</p>



<p class="wp-block-paragraph"><strong>代管執行個體群組</strong>（MIG，Managed Instance Group）是一群規格相同的 VM，可以依 CPU 用量自動加減台數，是 Compute Engine 版本的自動擴展。<strong>HPA</strong> 是第 17 篇的水平自動擴展，依指標增加 Pod。</p>



<h3 class="wp-block-heading">控制權：越能調，越要自己顧</h3>



<p class="wp-block-paragraph">官方文件把差別寫得很直接：GKE 讓你「完整控制 Kubernetes 叢集」，可以自訂節點設定、網路政策、安全設定和外掛；Cloud Run 只讓你設環境變數、並行數、網路連線這類東西，<strong>不能改底層的基礎架構</strong>（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/gke-and-cloud-run">官方比較頁</a>）。</p>



<p class="wp-block-paragraph">Compute Engine 又再往下一層：連作業系統都是你的。要跑 Windows 伺服器、要裝特定版本的資料庫、要改 Linux 核心參數，只有它做得到。</p>



<h3 class="wp-block-heading">規格上限：Cloud Run 單台最大 8 vCPU、32 GiB</h3>



<p class="wp-block-paragraph">Cloud Run 一台執行個體最多 8 vCPU、32 GiB 記憶體，一台最多同時處理 1,000 個請求，一個請求最長 60 分鐘（2026 年 11 月查<a href="https://cloud.google.com/run/quotas">官方上限</a>和<a href="https://cloud.google.com/run/docs/configuring/services/memory-limits">記憶體設定</a>）。網站和 API 很少碰到這些上限；需要更大的單機、或連線要掛好幾個小時（例如長時間的串流），就要考慮 GKE 或 Compute Engine。</p>



<p class="wp-block-paragraph"><strong>vCPU</strong> 是雲端切給你的一份 CPU 運算能力，<strong>GiB</strong> 是記憶體單位（1 GiB = 1,024 MiB）。</p>



<h3 class="wp-block-heading">狀態：Cloud Run 的檔案寫在記憶體裡</h3>



<p class="wp-block-paragraph"><strong>有狀態</strong>（Stateful）是程式需要記住之前的資料才能運作，例如資料庫；<strong>無狀態</strong>（Stateless）是每個請求都能獨立處理，例如查天氣的 API。</p>



<p class="wp-block-paragraph">Cloud Run 容器裡的檔案系統是<strong>記憶體檔案系統</strong>：寫進去的檔案佔用執行個體的記憶體，執行個體關掉就消失，寫太多還會把執行個體撐爆（2026 年 11 月查<a href="https://cloud.google.com/run/docs/container-contract">官方容器規範</a>）。要保存的資料放 Cloud SQL、Cloud Storage 這類外部服務；要掛共用的檔案系統，要用 Cloud Run 內建的磁碟區掛載（volume mounts）功能，不能在容器裡自己 <code>mount</code>。</p>



<p class="wp-block-paragraph">GKE 可以用第 16 篇的 PersistentVolume 掛永久磁碟，再搭配 StatefulSet 跑資料庫；Compute Engine 的磁碟本來就跟著 VM。這也是官方範例裡「庫存管理這種有狀態服務放 GKE、網站和批次工作放 Cloud Run」的原因。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">算一次：三個情境，三種服務各要多少錢</h2>



<p class="wp-block-paragraph">用台灣 <code>asia-east1</code> 的牌價（2026 年 11 月查官方定價頁，並用 Cloud Billing Catalog API 逐項確認），一個月算 30 天（720 小時、259.2 萬秒）。網路流量費三種都有、算法相近，這裡不算。</p>



<p class="wp-block-paragraph">先把會用到的單價列一次：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>服務</th><th>項目</th><th>單價（asia-east1）</th></tr></thead><tbody><tr><td>Cloud Run 服務（以請求計費）</td><td>CPU／記憶體／請求</td><td>每 vCPU 秒 0.000024、每 GiB 秒 0.0000025、每 100 萬次 0.40 美元</td></tr><tr><td>Cloud Run 服務（以執行個體計費）</td><td>CPU／記憶體</td><td>每 vCPU 秒 0.000018、每 GiB 秒 0.000002 美元</td></tr><tr><td>Cloud Run worker pools</td><td>CPU／記憶體</td><td>每 vCPU 秒 0.000011244、每 GiB 秒 0.000001235 美元</td></tr><tr><td>GKE Autopilot</td><td>Pod 的 CPU／記憶體／暫存空間</td><td>每 vCPU 小時 0.0515、每 GiB 小時 0.0056998、每 GiB 小時 0.0001608 美元</td></tr><tr><td>GKE</td><td>叢集管理費</td><td>每個叢集每小時 0.10 美元（每月 74.40 美元免費額度）</td></tr><tr><td>Compute Engine E2</td><td>CPU／記憶體</td><td>每 vCPU 小時 0.02525538、每 GiB 小時 0.00338514 美元</td></tr><tr><td>Compute Engine</td><td>平衡型永久磁碟、外部 IPv4</td><td>每 GiB 月 0.1 美元、每小時 0.005 美元</td></tr><tr><td>負載平衡器</td><td>轉送規則</td><td>每小時 0.025 美元（前 5 條）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>e2-standard-2</strong> 是 Compute Engine 的一種機型：2 vCPU、8 GB 記憶體，每小時 2 × 0.02525538 ＋ 8 × 0.00338514 = <strong>0.07759188 美元</strong>。E2 系列<strong>沒有持續使用折扣</strong>（開滿一個月自動打折那種），官方列的適用機型是 N1、N2、N2D、C2、M1、M2（2026 年 11 月查<a href="https://cloud.google.com/compute/docs/sustained-use-discounts">官方說明</a>）。</p>



<h3 class="wp-block-heading">情境一：小網站，一個月 300 萬次請求</h3>



<p class="wp-block-paragraph"><strong>假設</strong>：跟第 22 篇一樣，每次請求處理 0.2 秒、規格 1 vCPU、512 MiB，請求平均分散在一個月裡。</p>



<p class="wp-block-paragraph"><strong>Cloud Run（以請求計費，第 22 篇算過）</strong>：</p>


<ul class="wp-block-list">
<li>CPU：300 萬 × 0.2 秒 = 60 萬 vCPU 秒，扣掉免費 18 萬 = 42 萬 × 0.000024 = <strong>10.08 美元</strong></li>

<li>記憶體：60 萬 × 0.5 = 30 萬 GiB 秒，還在免費的 36 萬以內 = <strong>0 美元</strong></li>

<li>請求：300 萬扣掉免費 200 萬 = 100 萬次 × 0.40 = <strong>0.40 美元</strong></li>

<li>合計 <strong>約 10.48 美元</strong></li>
</ul>



<p class="wp-block-paragraph"><strong>GKE Autopilot</strong>：開 2 個 Pod（一個掛了另一個還在），每個 500m CPU、512Mi 記憶體，加起來跟 Cloud Run 一樣 1 vCPU；Autopilot 會再補 1 GiB 暫存空間（第 24 篇實測過）：</p>


<ul class="wp-block-list">
<li>每個 Pod 每小時：0.5 × 0.0515 ＋ 0.5 × 0.0056998 ＋ 1 × 0.0001608 = <strong>0.0287607 美元</strong></li>

<li>2 個 Pod 一個月：0.0287607 × 2 × 720 = <strong>41.42 美元</strong></li>

<li>對外的負載平衡器（把流量分給 2 個 Pod，第 24 篇建過），轉送規則：0.025 × 720 = <strong>18.00 美元</strong></li>

<li>叢集管理費 72 美元被每月 74.40 美元免費額度抵掉（這個帳單帳戶只有這一個叢集的話）</li>

<li>合計 <strong>約 59.42 美元</strong></li>
</ul>



<p class="wp-block-paragraph"><strong>Compute Engine</strong>：開 1 台 e2-standard-2 一直開著：</p>


<ul class="wp-block-list">
<li>機器：0.07759188 × 720 = <strong>55.87 美元</strong></li>

<li>10 GB 開機磁碟：10 × 0.1 = <strong>1.00 美元</strong></li>

<li>外部 IPv4：0.005 × 720 = <strong>3.60 美元</strong>（2026 年 11 月查<a href="https://cloud.google.com/vpc/network-pricing#ipaddress">官方 IP 定價</a>）</li>

<li>合計 <strong>約 60.47 美元</strong></li>
</ul>



<p class="wp-block-paragraph">e2-standard-2 對這個流量其實太大了。更小的共用核心機型 e2-small（2 個 vCPU 合計只能用 50% 的 CPU 時間、2 GB 記憶體）官方另外列套裝價，台灣的價格這次<strong>未查證</strong>，所以不拿來算。</p>



<p class="wp-block-paragraph"><strong>這三個數字代表什麼</strong>：</p>


<ul class="wp-block-list">
<li><strong>Cloud Run 便宜，是因為這個網站 77% 的時間沒人用</strong>：60 萬秒只佔一個月 259.2 萬秒的 23%，Cloud Run 只收有請求的那段；GKE 和 VM 是 24 小時開著等客人</li>

<li><strong>流量變大，Cloud Run 會跟著貴</strong>：請求變 10 倍，Cloud Run 的帳單大約跟著變多（同時處理的請求只算一份時間，所以不會剛好 10 倍）；e2-standard-2 的 2 顆 vCPU 還有空間，帳單不變。第 22 篇算過，執行個體超過約 75% 的時間在忙，就該改「以執行個體計費」</li>

<li><strong>帳單沒寫的成本</strong>：VM 的作業系統更新、HTTPS 憑證、主機掛了誰處理，都是你的；GKE 要有人懂 Kubernetes。Cloud Run 這些都包了</li>
</ul>



<h3 class="wp-block-heading">情境二：24 小時不停的背景工作</h3>



<p class="wp-block-paragraph"><strong>假設</strong>：一支程式 24 小時從訊息佇列（例如 Pub/Sub）拉工作出來處理，不需要對外網址，規格 2 vCPU、8 GiB，一個月不停。</p>



<p class="wp-block-paragraph"><strong>Cloud Run worker pools</strong>（第 23 篇介紹過，專門給這種一直在背景做事的程式）：</p>


<ul class="wp-block-list">
<li>每秒：2 × 0.000011244 ＋ 8 × 0.000001235 = 0.000032368 美元</li>

<li>一個月：0.000032368 × 259.2 萬秒 = <strong>約 83.90 美元</strong>（沒扣免費額度）</li>

<li>對照：用 Cloud Run 服務開「以執行個體計費＋最小執行個體 1」，同樣規格每秒 0.000052 美元，一個月約 134.78 美元（沒扣免費額度），worker pools 便宜約 38%</li>
</ul>



<p class="wp-block-paragraph"><strong>GKE Autopilot</strong>：1 個 Pod，2 vCPU、8Gi，加補上的 1 GiB 暫存空間：</p>


<ul class="wp-block-list">
<li>每小時：2 × 0.0515 ＋ 8 × 0.0056998 ＋ 1 × 0.0001608 = <strong>0.1487592 美元</strong></li>

<li>一個月：0.1487592 × 720 = <strong>約 107.11 美元</strong>（不用負載平衡器，管理費被免費額度抵掉）</li>
</ul>



<p class="wp-block-paragraph"><strong>Compute Engine</strong>：1 台 e2-standard-2，算法跟情境一一樣，<strong>約 60.47 美元</strong>。不需要對外 IP 的話可以省掉其中 3.60 美元，但要另外設定讓 VM 連得到 Google 的服務。</p>



<p class="wp-block-paragraph"><strong>這三個數字代表什麼</strong>：</p>


<ul class="wp-block-list">
<li><strong>一直在跑的工作，VM 最便宜</strong>：Cloud Run 和 GKE Autopilot 的單價裡包含了「機器 Google 幫你管」的費用，工作量 24 小時不停時，這份管理費就很明顯</li>

<li><strong>可以被中斷的工作，還能更便宜</strong>：<strong>Spot VM</strong> 是 Google 拿閒置機器出租的折扣方案，最多比原價便宜 91%，但 Google 隨時可能把機器收回（2026 年 11 月查<a href="https://cloud.google.com/compute/docs/instances/spot">官方 Spot VM 說明</a>）。台灣的 Spot e2-standard-2 一個月約 31.36 美元，加磁碟和 Spot 的 IP 約 34.16 美元；GKE Autopilot 的 Spot Pod 同規格約 32.17 美元（不含暫存空間）。Spot 價格會浮動：Compute Engine 官方寫最多每天調整一次，GKE 定價頁寫最多每 30 天調整一次</li>

<li><strong>選 worker pools 的理由不是價格</strong>：是不用管作業系統、不用懂 Kubernetes，程式丟上去就跑</li>
</ul>



<h3 class="wp-block-heading">情境三：GPU 推論服務</h3>



<p class="wp-block-paragraph"><strong>GPU</strong>（圖形處理器）是很擅長同時做大量計算的晶片，現在主要拿來跑 AI 模型。<strong>推論</strong>（Inference）是用訓練好的模型回答問題，例如把語音轉成文字、生成圖片。</p>



<p class="wp-block-paragraph"><strong>假設</strong>：一個語音轉文字的 API，用 1 張 NVIDIA L4 GPU、4 vCPU、16 GiB 記憶體。L4 是 Google Cloud 上常見的推論用 GPU。</p>



<p class="wp-block-paragraph"><strong>Cloud Run</strong>：查官方文件時發現，<strong>Cloud Run 的 L4 GPU 支援的區域沒有台灣 asia-east1</strong>，亞洲是新加坡 <code>asia-southeast1</code> 和孟買 <code>asia-south1</code>（孟買要申請）。另外 GPU 一定要用以執行個體計費、L4 最少要 4 CPU 和 16 GiB，第一次在一個區域用，專案會自動拿到 3 張 L4 的配額（2026 年 11 月查<a href="https://cloud.google.com/run/docs/configuring/services/gpu">官方 GPU 說明</a>）。新加坡的單價（不跨區域備援）：</p>


<ul class="wp-block-list">
<li>每秒：4 × 0.0000216 ＋ 16 × 0.0000024 ＋ GPU 0.00022404 = 0.00034884 美元，等於每小時 <strong>1.255824 美元</strong></li>

<li><strong>假設一天只有 4 小時有人用</strong>，其他時間縮到 0：1.255824 × 120 小時 = <strong>約 150.70 美元</strong></li>

<li>如果 24 小時都開著：1.255824 × 720 = 約 904.19 美元</li>
</ul>



<p class="wp-block-paragraph"><strong>Compute Engine</strong>：台灣 asia-east1 的 a、b 區域有 L4（G2 機型）。<strong>g2-standard-4</strong> 是 4 vCPU、16 GB、1 張 L4 的機型（2026 年 11 月查<a href="https://cloud.google.com/compute/docs/accelerator-optimized-machines">官方機型說明</a>和<a href="https://cloud.google.com/compute/docs/gpus/gpu-regions-zones">GPU 區域</a>）：</p>


<ul class="wp-block-list">
<li>每小時：4 × 0.02893385 ＋ 16 × 0.003389693 ＋ L4 0.6484706 = <strong>0.81844109 美元</strong></li>

<li>24 小時開著：0.81844109 × 720 = <strong>約 589.28 美元</strong>（不含磁碟；加速器最佳化機型的 GPU 沒有持續使用折扣）</li>
</ul>



<p class="wp-block-paragraph"><strong>GKE Autopilot</strong>：Pod 指定要 GPU 時，Autopilot 改成<strong>照整台節點計費</strong>：付底層 VM 的錢，再加一筆 Autopilot 管理加價（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/pricing">官方定價頁</a>）。假設它開的是 g2-standard-4：</p>


<ul class="wp-block-list">
<li>加價每小時：4 × 0.003473 ＋ 16 × 0.000405 ＋ L4 0.077579 = 0.097951 美元</li>

<li>每小時合計：0.81844109 ＋ 0.097951 = 0.91639209 美元</li>

<li>24 小時開著：0.91639209 × 720 = <strong>約 659.80 美元</strong>（不含磁碟）</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-03-cost.png" alt="三個情境三種服務各算一次一個月費用：小網站 300 萬次請求 Cloud Run 約 10.48 美元、GKE Autopilot 約 59.42 美元、Compute Engine 約 60.47 美元；24 小時背景工作 2 vCPU 8 GiB，Cloud Run worker pools 約 83.90 美元、GKE Autopilot 約 107.11 美元、Compute Engine 約 60.47 美元；GPU 推論 1 張 L4，Cloud Run 一天開 4 小時約 150.70 美元、GKE Autopilot 24 小時約 659.80 美元、Compute Engine 24 小時約 589.28 美元" class="wp-image-13542" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-03-cost.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-03-cost-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-03-cost-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-03-cost-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph"><strong>這三個數字代表什麼</strong>：</p>


<ul class="wp-block-list">
<li><strong>分界大約是一天 15.6 小時</strong>：Compute Engine 開滿一個月 589.28 美元，除以 Cloud Run 每小時 1.255824 美元，等於 469.2 小時，平均一天 15.6 小時。GPU 一天開不到這麼久，Cloud Run 自動縮到 0 比較划算；超過就換 VM 或 GKE</li>

<li><strong>VM 也可以自己關機</strong>：用的時候才開 g2-standard-4，一天 4 小時是 0.81844109 × 120 = 約 98.21 美元，比 Cloud Run 還便宜。代價是要自己寫開關機的流程，熱門 GPU 在尖峰時段也可能開不起來；Cloud Run 官方寫 GPU 執行個體約 5 秒就能啟動（載入模型的時間另計）</li>

<li><strong>跨國的距離</strong>：Cloud Run 的 GPU 放新加坡，台灣的使用者連過去會比連彰化的機房遠。對延遲很敏感的服務，要自己量一次再決定</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">判斷流程：照順序問自己 5 個問題</h2>



<p class="wp-block-paragraph">選 Cloud Run、GKE 還是 Compute Engine，可以從最「特殊」的需求問起，問到第一個「是」就停：</p>


<ol class="wp-block-list">
<li><strong>要指定作業系統、跑 Windows、改核心、裝綁硬體的授權軟體嗎？</strong> 是 → <strong>Compute Engine</strong></li>

<li><strong>已經有一堆 Kubernetes YAML、很多服務互相呼叫、想在不同雲之間搬嗎？</strong> 是 → <strong>GKE</strong></li>

<li><strong>要自己架資料庫、需要永久磁碟、連線要掛很多個小時嗎？</strong> 是 → <strong>GKE 或 Compute Engine</strong></li>

<li><strong>要 GPU，而且一天用超過約 15 小時嗎？</strong> 是 → <strong>GKE 或 Compute Engine</strong>（偶爾用的話 Cloud Run，注意區域）</li>

<li><strong>以上都不是</strong>：網站、API、Webhook、排程批次 → <strong>Cloud Run</strong>（做完就結束的用 Jobs，一直在背景拉訊息的用 worker pools）</li>
</ol>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-02-decision.png" alt="Cloud Run、GKE、Compute Engine 判斷流程：要指定作業系統、Windows、改核心選 Compute Engine；已經有一堆 K8s YAML、多個服務互相呼叫選 GKE；要掛磁碟長期存資料選 GKE 或 Compute Engine；要 GPU 而且一天用超過約 15 小時選 GKE 或 Compute Engine；以上都不是的網站、API、排程工作選 Cloud Run" class="wp-image-13543" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-02-decision.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-02-decision-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-02-decision-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct27-cards-02-decision-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph"><strong>為什麼 Cloud Run 放最後、卻是預設選擇</strong>：前 4 題都是「Cloud Run 做不到或不划算」的情況，大部分新專案一題都不會中。從 Cloud Run 開始，碰到限制再搬，因為同一個容器映像檔在 GKE 也能直接用（官方文件寫明兩邊都用標準容器映像檔，不用改；2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/gke-and-cloud-run">官方比較頁</a>）。</p>



<p class="wp-block-paragraph"><strong>團隊大小也是一個訊號</strong>：官方部落格的整理是，小團隊想把時間花在寫程式，選 Cloud Run 這類無伺服器服務；大團隊有自己的部署流程、安全規範和維運人力，Compute Engine 或 GKE 比較合適（<a href="https://cloud.google.com/blog/topics/developers-practitioners/where-should-i-run-my-stuff-choosing-google-cloud-compute-option">Google Cloud 部落格</a>，2021 年）。</p>



<h3 class="wp-block-heading">常常不是三選一，而是混搭</h3>



<p class="wp-block-paragraph">官方舉的電商例子是這樣分的（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/gke-and-cloud-run">官方比較頁</a>）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元件</th><th>放哪</th><th>原因</th></tr></thead><tbody><tr><td>網站和手機 App 後端</td><td>Cloud Run</td><td>無狀態、流量起伏大、照用量付費</td></tr><tr><td>定期更新商品目錄、分析使用者行為</td><td>Cloud Run（Jobs）</td><td>跑完就結束</td></tr><tr><td>商品庫存管理</td><td>GKE</td><td>有狀態，要掛磁碟保存資料</td></tr><tr><td>推薦引擎</td><td>GKE</td><td>很多元件互相依賴，要細部控制資源</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">兩邊都能用同一個 Artifact Registry 裡的映像檔（第 19 篇）、同一套 Cloud Build 流程（第 21 篇），日誌也都進 Cloud Logging。所以選錯了不用重寫程式，搬的成本主要在設定和網路。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">查證時發現：跟網路上舊說法不一樣的地方</h2>



<p class="wp-block-paragraph">寫這篇時把常見的說法逐一對照 2026 年 11 月的官方文件，這 5 點跟網路上的舊文章不一樣：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊說法</th><th>現在（2026 年 11 月查官方文件）</th></tr></thead><tbody><tr><td>Cloud Run 照請求收費，GKE、VM 照機器收費</td><td>Cloud Run 有以請求計費、以執行個體計費兩種，還有 worker pools；GKE Autopilot 一般 Pod 照 Pod 的資源要求收費</td></tr><tr><td>GKE Autopilot 的 GPU 也照 Pod 要多少收</td><td>指定 GPU 這類特定硬體時，改成照整台節點收，再加 Autopilot 管理加價</td></tr><tr><td>Cloud Run GPU 部署到 asia-east1</td><td>L4 支援的區域沒有台灣，亞洲是新加坡、孟買（孟買要申請）</td></tr><tr><td>Cloud Functions</td><td>改名 Cloud Run functions，用 <code>gcloud run deploy --function</code> 部署（第 23 篇）</td></tr><tr><td>VM 開滿一個月會自動打折</td><td>持續使用折扣只適用 N1、N2、N2D、C2、M1、M2 等機型；E2 沒有，G2 這類加速器最佳化機型的 GPU 也沒有</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">這些變動大多發生在最近兩年，看比較文時先看發布日期，數字和名稱以官方文件為準。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪：這篇沒有建資源，但這張清單幫你檢查</h2>



<p class="wp-block-paragraph">這篇只有比較和計算，沒有建任何雲端資源。不過跟著第 19～26 篇做過的話，這 5 種資源<strong>最容易忘了刪、又會一直收錢</strong>，建議到 Console 逐頁看一次：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>去哪看（Console）</th><th>找什麼</th><th>不刪會怎樣（asia-east1，2026 年 11 月查）</th></tr></thead><tbody><tr><td>Kubernetes Engine → 叢集</td><td>第 24～26 篇的 GKE 叢集</td><td>第二個以上的叢集每小時 0.10 美元管理費，加上 Pod 費用</td></tr><tr><td>網路服務 → 負載平衡</td><td>GKE 的 LoadBalancer、Gateway 留下的負載平衡器</td><td>每條轉送規則每小時 0.025 美元，一個月約 18 美元</td></tr><tr><td>Cloud Run</td><td>設了最小執行個體的服務</td><td>1 vCPU、512 MiB 留一台一個月約 9.72 美元閒置費（第 22 篇）</td></tr><tr><td>Compute Engine → 磁碟</td><td>刪叢集後留下的永久磁碟</td><td>每 GiB 每月 0.1 美元</td></tr><tr><td>Artifact Registry</td><td>練習用的映像檔</td><td>超過每月免費的 0.5 GiB 後，每 GiB 每月約 0.10 美元（第 19 篇）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">怎麼設預算提醒，可以看<a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「Cloud Run 和 GKE 怎麼選？」</strong>：先問工作負載是不是無狀態、是不是 HTTP 或事件觸發、團隊懂不懂 Kubernetes。無狀態、想照用量付費、不想維運叢集選 Cloud Run；多服務互相依賴、有狀態、需要 Kubernetes 的功能或細部控制選 GKE</li>

<li><strong>「什麼時候該用 Compute Engine？」</strong>：要指定作業系統或 Windows、舊系統直接搬遷、軟體授權綁硬體、要改核心參數；代價是作業系統更新和安全修補要自己做</li>

<li><strong>「Cloud Run 一定比較便宜嗎？」</strong>：不一定。它省在「沒人用不收錢」，流量 24 小時都很穩、執行個體一直在忙時，VM 或以執行個體計費比較划算；可以用這篇的三個情境當例子</li>

<li><strong>「選錯了怎麼辦？」</strong>：GKE 和 Cloud Run 都用標準容器映像檔，同一個映像檔可以直接搬；搬遷主要改的是部署設定、網路和服務帳戶權限</li>
</ul>



<h3 class="wp-block-heading">Google Cloud 證照（ACE、PCA）</h3>



<p class="wp-block-paragraph">Associate Cloud Engineer（ACE）是 2 小時、50～60 題單選和複選，報名費 125 美元、效期 3 年；Professional Cloud Architect（PCA）是 2 小時、50～60 題，報名費 200 美元、效期 2 年，考試語言只有英文和日文，其中 20～30% 是兩個案例情境的題目（2026 年 11 月查<a href="https://cloud.google.com/learn/certification/cloud-engineer">官方 ACE 考試頁</a>和<a href="https://cloud.google.com/learn/certification/cloud-architect">PCA 考試頁</a>）。兩個都是情境選擇題，不是上機考。</p>



<p class="wp-block-paragraph">這題在 ACE 常以「用哪個服務部署最省事」出現，在 PCA 常在案例裡要你替不同元件挑平台。準備方式可以看<a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照怎麼準備</a>。</p>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「無狀態」「HTTP」「沒流量時不想付錢」「最少維運」</td><td>Cloud Run</td></tr><tr><td>「定時批次」「跑完就結束」「平行處理很多檔案」</td><td>Cloud Run Jobs（第 23 篇）</td></tr><tr><td>「一直從 Pub/Sub 拉訊息處理」「不需要網址」</td><td>Cloud Run worker pools</td></tr><tr><td>「已有 Kubernetes 工作負載」「多雲、混合雲」「可攜性」</td><td>GKE</td></tr><tr><td>「有狀態」「StatefulSet」「DaemonSet」「服務網格」</td><td>GKE</td></tr><tr><td>「不想管節點」「照 Pod 用量付費」</td><td>GKE Autopilot（第 24 篇）</td></tr><tr><td>「指定作業系統」「Windows」「授權綁硬體」「改核心」「直接搬遷」</td><td>Compute Engine</td></tr><tr><td>「可以被中斷」「最便宜」「批次運算」</td><td>Spot VM、Autopilot Spot Pod</td></tr><tr><td>「GPU 推論」「偶爾用」「縮到零」</td><td>Cloud Run GPU（注意支援區域）</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Cloud Run vs GKE 怎麼選？</h3>



<p class="wp-block-paragraph">看工作負載和團隊。無狀態的網站、API、批次工作，希望沒人用時不付運算費、不想維運叢集，選 Cloud Run；很多服務互相呼叫、需要永久磁碟或 StatefulSet、團隊已經在用 Kubernetes、需要細部控制網路和節點，選 GKE。兩邊都用標準容器映像檔，可以先從 Cloud Run 開始，碰到限制再搬。</p>



<h3 class="wp-block-heading">Cloud Run 一定比 GKE、Compute Engine 便宜嗎？</h3>



<p class="wp-block-paragraph">不一定。這篇用台灣 asia-east1 的牌價（2026 年 11 月）算：每月 300 萬次請求的小網站，Cloud Run 約 10.48 美元，GKE Autopilot 約 59.42 美元，Compute Engine e2-standard-2 約 60.47 美元；但 24 小時不停的 2 vCPU、8 GiB 背景工作，Compute Engine 約 60.47 美元反而最便宜，Cloud Run worker pools 約 83.90 美元、GKE Autopilot 約 107.11 美元。</p>



<h3 class="wp-block-heading">Compute Engine 什麼時候比 Cloud Run 划算？</h3>



<p class="wp-block-paragraph">工作量 24 小時都很滿的時候。Cloud Run 便宜在「沒人用不收錢」，機器一直在忙就沒有這個優勢；GPU 的例子裡，Compute Engine g2-standard-4 開滿一個月約 589.28 美元，等於 Cloud Run GPU 一天開 15.6 小時的費用，用得比這個久就是 VM 划算。另外要指定作業系統、跑 Windows 的，只能用 Compute Engine。</p>



<h3 class="wp-block-heading">Cloud Run 可以用 GPU 嗎？台灣可以嗎？</h3>



<p class="wp-block-paragraph">可以用 NVIDIA L4 和 RTX PRO 6000，但 2026 年 11 月查官方文件，L4 支援的區域沒有台灣 asia-east1，亞洲是新加坡 asia-southeast1 和孟買 asia-south1（孟買要申請）。GPU 服務一定要用以執行個體計費，L4 最少 4 CPU、16 GiB，沒人用時一樣可以縮到 0。台灣 asia-east1 要用 L4，可以選 GKE 或 Compute Engine 的 G2 機型。</p>



<h3 class="wp-block-heading">GKE Autopilot 和 Cloud Run 都不用管機器，差在哪？</h3>



<p class="wp-block-paragraph">差在你管什麼、怎麼收錢。Autopilot 還是 Kubernetes：你寫 Deployment、Service 這些 YAML，Pod 開著就照資源要求收錢，沒人用也收；Cloud Run 只要交容器映像檔，有請求才收 CPU 和記憶體的錢，沒人用時縮到 0。Autopilot 能用 StatefulSet、永久磁碟、DaemonSet 這些 Kubernetes 功能，Cloud Run 不行。</p>



<h3 class="wp-block-heading">選錯了可以搬嗎？</h3>



<p class="wp-block-paragraph">可以，成本主要在設定。GKE 和 Cloud Run 都用標準容器映像檔，同一個放在 Artifact Registry 的映像檔兩邊都能部署，Cloud Build 的流程也能共用；官方文件還說明了可以用負載平衡器把同一個服務的流量分給兩個平台，慢慢搬過去。從 Compute Engine 搬出來比較麻煩，要先把程式包成容器。</p>



<h3 class="wp-block-heading">Cloud Run 可以跑資料庫這種有狀態的程式嗎？</h3>



<p class="wp-block-paragraph">不適合。Cloud Run 容器裡的檔案系統在記憶體裡，執行個體關掉資料就不見，寫太多還會把執行個體撐爆。資料要放 Cloud SQL、Cloud Storage 這類外部服務；一定要自己架資料庫，放 GKE（用永久磁碟加 StatefulSet）或 Compute Engine。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>差在你要顧多少</strong>：Compute Engine 給你整台機器（作業系統也是你的），GKE 給你代管的 Kubernetes，Cloud Run 只要交容器映像檔</li>

<li><strong>計費差最多</strong>：Cloud Run 預設有請求才收錢、沒人用縮到 0；GKE 收叢集管理費（每月 74.40 美元免費額度抵一個）加 Pod 或節點；Compute Engine 開著就收，E2 沒有持續使用折扣</li>

<li><strong>三個情境算一次（台灣 asia-east1，2026 年 11 月）</strong>：小網站 Cloud Run 約 10.48 美元最便宜；24 小時背景工作 Compute Engine 約 60.47 美元最便宜；GPU 一天用超過約 15.6 小時，VM 比 Cloud Run 划算</li>

<li><strong>Cloud Run 的 L4 GPU 台灣沒有</strong>，亞洲最近是新加坡；台灣要用 L4 選 GKE 或 Compute Engine</li>

<li><strong>預設從 Cloud Run 開始</strong>：指定作業系統選 Compute Engine，多服務、有狀態、已在用 K8s 選 GKE，同一個容器映像檔隨時可以搬</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">Docker 入門教學：不用安裝，用 Cloud Shell 跑出第一個容器</a></li>

<li>第 16 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">健康檢查與自動擴展：Probe、資源限制、HPA</a></li>

<li>第 19 篇：<a href="https://dongdonggcp.com/2025/07/20/artifact-registry-tutorials/">Artifact Registry 是什麼？把 Docker 映像檔推上 GCP 教學</a></li>

<li>第 20 篇：<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a></li>

<li>第 21 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">Cloud Build 是什麼？用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run</a></li>

<li>第 22 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-run-pricing-cold-start-min-instances/">Cloud Run 收費怎麼算？Cloud Run pricing、冷啟動、最小執行個體一次看懂</a></li>

<li>第 23 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-run-jobs-vs-services-functions/">Cloud Run Jobs 是什麼？服務、Jobs、functions 差在哪、怎麼選</a></li>

<li>第 24 篇：<a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li>第 25 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a></li>

<li>上一篇：第 26 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務</a></li>

<li>下一篇：第 28 篇：<a href="https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/">Docker、Kubernetes 教學地圖：從容器到 Cloud Run、GKE 全系列整理</a></li>
</ul>



<p class="wp-block-paragraph"><strong>運算服務相關</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/10/23/what-is-google-vm-compute-engine-introduction/">Compute Engine 是什麼？Google 的 VM 平台</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器（Container）技術是什麼？從零開始看懂 Docker 與容器化應用</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/cloud-run-functions-tutorials/">Cloud Run Functions 簡介</a></li>

<li><a href="https://dongdonggcp.com/2026/10/25/model-deployment-online-vs-batch-prediction-traffic-split/">模型部署怎麼選？線上預測 vs 批次預測、流量分割</a></li>

<li><a href="https://dongdonggcp.com/2026/10/25/vertex-ai-custom-training-containers-distributed-gpu-tpu/">Vertex AI 自訂訓練：容器、分散式訓練、GPU 與 TPU</a></li>

<li><a href="https://dongdonggcp.com/2026/03/26/spotify-case-gcp-cloud-migration-decisions/">Spotify 成功案例：如何將服務搬上 GCP？7 大關鍵技術決策完整解析</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照（PCA）怎麼準備</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析：雲端工程師、架構師、SRE、DevOps、資料工程師差在哪？</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">三個服務怎麼選有了答案，最後一篇把整個系列 27 篇整理成一張學習地圖，從 Docker 一路走到 Cloud Run、GKE。可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Cloud Run vs GKE 怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "看工作負載和團隊。無狀態的網站、API、批次工作，希望沒人用時不付運算費、不想維運叢集，選 Cloud Run；很多服務互相呼叫、需要永久磁碟或 StatefulSet、團隊已經在用 Kubernetes、需要細部控制網路和節點，選 GKE。兩邊都用標準容器映像檔，可以先從 Cloud Run 開始，碰到限制再搬。"
      }
    },
    {
      "@type": "Question",
      "name": "Cloud Run 一定比 GKE、Compute Engine 便宜嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定。這篇用台灣 asia-east1 的牌價（2026 年 11 月）算：每月 300 萬次請求的小網站，Cloud Run 約 10.48 美元，GKE Autopilot 約 59.42 美元，Compute Engine e2-standard-2 約 60.47 美元；但 24 小時不停的 2 vCPU、8 GiB 背景工作，Compute Engine 約 60.47 美元反而最便宜，Cloud Run worker pools 約 83.90 美元、GKE Autopilot 約 107.11 美元。"
      }
    },
    {
      "@type": "Question",
      "name": "Compute Engine 什麼時候比 Cloud Run 划算？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "工作量 24 小時都很滿的時候。Cloud Run 便宜在「沒人用不收錢」，機器一直在忙就沒有這個優勢；GPU 的例子裡，Compute Engine g2-standard-4 開滿一個月約 589.28 美元，等於 Cloud Run GPU 一天開 15.6 小時的費用，用得比這個久就是 VM 划算。另外要指定作業系統、跑 Windows 的，只能用 Compute Engine。"
      }
    },
    {
      "@type": "Question",
      "name": "Cloud Run 可以用 GPU 嗎？台灣可以嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以用 NVIDIA L4 和 RTX PRO 6000，但 2026 年 11 月查官方文件，L4 支援的區域沒有台灣 asia-east1，亞洲是新加坡 asia-southeast1 和孟買 asia-south1（孟買要申請）。GPU 服務一定要用以執行個體計費，L4 最少 4 CPU、16 GiB，沒人用時一樣可以縮到 0。台灣 asia-east1 要用 L4，可以選 GKE 或 Compute Engine 的 G2 機型。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE Autopilot 和 Cloud Run 都不用管機器，差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "差在你管什麼、怎麼收錢。Autopilot 還是 Kubernetes：你寫 Deployment、Service 這些 YAML，Pod 開著就照資源要求收錢，沒人用也收；Cloud Run 只要交容器映像檔，有請求才收 CPU 和記憶體的錢，沒人用時縮到 0。Autopilot 能用 StatefulSet、永久磁碟、DaemonSet 這些 Kubernetes 功能，Cloud Run 不行。"
      }
    },
    {
      "@type": "Question",
      "name": "選錯了可以搬嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以，成本主要在設定。GKE 和 Cloud Run 都用標準容器映像檔，同一個放在 Artifact Registry 的映像檔兩邊都能部署，Cloud Build 的流程也能共用；官方文件還說明了可以用負載平衡器把同一個服務的流量分給兩個平台，慢慢搬過去。從 Compute Engine 搬出來比較麻煩，要先把程式包成容器。"
      }
    },
    {
      "@type": "Question",
      "name": "Cloud Run 可以跑資料庫這種有狀態的程式嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不適合。Cloud Run 容器裡的檔案系統在記憶體裡，執行個體關掉資料就不見，寫太多還會把執行個體撐爆。資料要放 Cloud SQL、Cloud Storage 這類外部服務；一定要自己架資料庫，放 GKE（用永久磁碟加 StatefulSet）或 Compute Engine。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/">Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-configmap-secret</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:35:05 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13325</guid>

					<description><![CDATA[<p>ConfigMap 和 Secret 怎麼用？Cloud Shell 實測用環境變數和檔案交給 Pod：改設定後檔案約 85 秒更新、環境變數要重開；base64 一行還原密碼，Secret 不是加密。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>ConfigMap 和 Secret：前者放一般設定、後者放密碼，讓同一個映像檔換環境換設定；但 Secret 預設沒加密。</strong></p>



<p class="wp-block-paragraph">同一個網站，測試環境連測試資料庫、正式環境連正式資料庫，密碼也不一樣。如果把設定和密碼寫進映像檔，每換一個環境就要重新打包一次，而且拿到映像檔的人就拿到密碼（<a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">第 8 篇</a>示範過 <code>.env</code> 被打包進去）。Kubernetes 的解法是把設定拿出來，放進 <strong>ConfigMap</strong> 和 <strong>Secret</strong>。</p>



<p class="wp-block-paragraph">這篇在 Cloud Shell 實際做給你看：用兩種方式把 ConfigMap 交給 Pod（環境變數、檔案），改了設定之後<strong>檔案約 85 秒自動更新、環境變數完全不會變</strong>；再用一行 <code>base64 -d</code> 證明 <strong>Secret 不是加密</strong>。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 15 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。Deployment 的寫法請先看第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-01-why.png" alt="同一個映像檔不同環境換設定：nginx:1.31 映像檔只做一次，測試環境用 APP_ENV=staging、正式環境用 production；ConfigMap 放一般設定、Secret 放密碼金鑰" class="wp-image-13310" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-01-why.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-01-why-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-01-why-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-01-why-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>一個映像檔走遍所有環境</strong>：測試、預備、正式用同一個映像檔，只換設定，才能確保「測試過的就是上線的那一份」</li>

<li><strong>密碼不能進映像檔、也不能進 Git</strong>：映像檔會被推到倉庫、程式碼會被很多人看到，密碼放在裡面等於公開</li>

<li><strong>很多人以為 Secret 有加密</strong>：網路上不少文章說 Secret「用 base64 保護資料」，這是錯的。不知道這點，權限一開放，密碼就外洩了</li>

<li><strong>改設定要不要重開，影響上線流程</strong>：設定用環境變數給，改了要重開 Pod；用檔案給，會自動更新但要等。實測兩者差很多</li>

<li><strong>證照必考</strong>：CKAD 幾乎一定會考「建 ConfigMap、Secret，再用環境變數或 Volume 給 Pod」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">ConfigMap 是什麼</h2>



<p class="wp-block-paragraph"><strong>ConfigMap 是 Kubernetes 裡存放「一般設定」的地方</strong>，內容是一組「名字＝值」，或整個設定檔（<a href="https://kubernetes.io/docs/concepts/configuration/configmap/">Kubernetes 官方說明：ConfigMaps</a>）。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：連鎖餐廳每間分店的「店務設定表」：營業時間、今日特餐、招牌顏色。廚房設備（映像檔）每間店都一樣，設定表各店自己填</li>

<li><strong>來龍去脈</strong>：config 是 configuration（設定）、map 是「對照表」。Docker 時代用 <code>-e</code> 環境變數或掛設定檔（<a href="https://dongdonggcp.com/2026/11/18/docker-volume-vs-bind-mount/">第 5 篇</a>的 Bind Mount），Kubernetes 把這些設定變成叢集裡的一個物件，可以用 YAML 管理</li>

<li><strong>為什麼要學</strong>：環境名稱、功能開關、外部服務網址、log 等級這些「不是秘密、但每個環境不一樣」的值，都放 ConfigMap</li>
</ul>



<p class="wp-block-paragraph"><strong>環境變數是程式執行時，作業系統交給它的一組「名字＝值」</strong>，程式用名字就能讀到值，例如 Python 的 <code>os.environ.get("APP_ENV")</code>（第 4 篇的 Flask 範例就是這樣讀 <code>APP_ENV</code>）。</p>



<h2 class="wp-block-heading">Secret 是什麼</h2>



<p class="wp-block-paragraph"><strong>Secret 是 Kubernetes 裡存放「敏感資料」的地方</strong>，例如密碼、API 金鑰、憑證（<a href="https://kubernetes.io/docs/concepts/configuration/secret/">Kubernetes 官方說明：Secrets</a>）。用法跟 ConfigMap 幾乎一樣，差別是 Kubernetes 會用比較小心的方式處理它。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：店長辦公室抽屜裡的保險箱密碼。它跟店務設定表一樣是「各店不同的設定」，但只有少數人該看到</li>

<li><strong>來龍去脈</strong>：Secret 的資料用 <strong>base64</strong> 寫法存放。base64 是一種「把任何資料轉成英文字母和數字」的寫法，原本是為了讓二進位檔（例如憑證）能放進純文字的 YAML，<strong>不是加密</strong></li>

<li><strong>為什麼要學</strong>：要知道它能做什麼、不能做什麼。官方文件寫明 <strong>Secret 預設以未加密的方式存在 etcd</strong>（<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">第 9 篇</a>講過的叢集資料庫），能讀 Secret 的人就能看到內容</li>
</ul>



<h3 class="wp-block-heading">ConfigMap 和 Secret 比一比</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>ConfigMap</th><th>Secret</th></tr></thead><tbody><tr><td>放什麼</td><td>一般設定</td><td>密碼、金鑰、憑證</td></tr><tr><td>YAML 裡的值</td><td>直接寫原文</td><td>base64 寫法（也可以用 <code>stringData</code> 寫原文）</td></tr><tr><td>加密</td><td>沒有</td><td><strong>預設也沒有</strong>，要另外設定 etcd 加密</td></tr><tr><td>大小上限</td><td>1MiB</td><td>1MiB</td></tr><tr><td>給 Pod 的方式</td><td>環境變數、檔案</td><td>環境變數、檔案</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">1MiB 約 105 萬個位元組，放設定綽綽有餘；官方設這個上限，是怕太大的物件吃光 API 伺服器和 kubelet 的記憶體（2026 年 11 月查官方文件）。大檔案請放 Volume（第 16 篇）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">兩種給 Pod 的方式，更新行為不一樣</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>方式</th><th>YAML 寫法</th><th>改了 ConfigMap 之後</th></tr></thead><tbody><tr><td>環境變數</td><td><code>envFrom</code>、<code>env.valueFrom</code></td><td><strong>Pod 不會看到新值</strong>，要重開 Pod</td></tr><tr><td>檔案（Volume）</td><td><code>volumes.configMap</code>＋<code>volumeMounts</code></td><td><strong>自動更新</strong>，但要等一段時間</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">官方文件說，檔案的更新要等「kubelet 的同步週期＋快取」，可能要一分鐘以上。實測是 <strong>約 85 秒</strong>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-02-update.png" alt="實測改了 ConfigMap 之後：掛成檔案的約 85 秒自動從 color=blue 變成 green；環境變數等了 85 秒還是 staging，要 rollout restart 才換成 production" class="wp-image-13311" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-02-update.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-02-update-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-02-update-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-02-update-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">怎麼選：</p>


<ul class="wp-block-list">
<li>程式只在啟動時讀一次設定 → 用環境變數，改設定時順便 <code>kubectl rollout restart</code> 重開（第 12 篇的滾動更新，不停機）</li>

<li>程式會自己重新讀設定檔（例如 nginx 可以 reload）→ 用檔案，改了不用重開</li>

<li>想確保設定不會被誤改 → 設 <code>immutable: true</code>（不可修改），要改就建一份新的</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：ConfigMap、Secret 交給 Pod，再改一次看看</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，跳出「授權 Cloud Shell」按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<h3 class="wp-block-heading">步驟 1：開叢集</h3>



<pre class="wp-block-code"><code>mkdir -p ~/k8s-cfg &amp;&amp; cd ~/k8s-cfg; minikube start --cni=kindnet | tail -1</code></pre>



<pre class="wp-block-code"><code>（前面省略：版本提醒和硬碟空間警告）
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="342" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start.png" alt="建立 k8s-cfg 資料夾，用 --cni=kindnet 啟動 minikube" class="wp-image-13312" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start-300x64.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start-1024x219.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start-768x164.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-01-start-1536x328.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>--cni=kindnet</code> 的原因請看<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">第 13 篇</a>的「實測時的意外」，在 Cloud Shell 開 Minikube 建議都加上。</p>



<h3 class="wp-block-heading">步驟 2：用指令建一個 ConfigMap</h3>



<pre class="wp-block-code"><code>kubectl create configmap app-config --from-literal=APP_ENV=staging --from-literal=WELCOME='hello v1'; kubectl get configmap app-config -o yaml | grep -B1 -A3 '^data'</code></pre>



<pre class="wp-block-code"><code>configmap/app-config created
apiVersion: v1
data:
  APP_ENV: staging
  WELCOME: hello v1
kind: ConfigMap</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="228" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal.png" alt="kubectl create configmap app-config 建立兩個值：APP_ENV=staging、WELCOME=hello v1，YAML 的 data 欄位直接是原文" class="wp-image-13313" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal-300x43.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal-1024x146.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal-768x109.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-02-cm-literal-1536x219.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--from-literal=名字=值</code>：直接在指令裡給值（literal 是「字面上的值」），可以給好幾個</li>

<li>YAML 的 <code>data:</code> 底下就是這兩個值，<strong>直接是原文</strong></li>
</ul>



<p class="wp-block-paragraph"><code>grep -B1 -A3 '^data'</code> 是只看 <code>data</code> 那行的前 1 行和後 3 行，YAML 其他部分先跳過。</p>



<h3 class="wp-block-heading">步驟 3：用檔案建 ConfigMap</h3>



<p class="wp-block-paragraph">很多程式的設定是一整個檔案。先寫一個設定檔，再把整個檔案放進 ConfigMap：</p>



<pre class="wp-block-code"><code>cat &gt; app.properties &lt;&lt;'EOF'
color=blue
max_items=20
EOF
kubectl create configmap app-file --from-file=app.properties; kubectl describe configmap app-file | sed -n '1,12p'</code></pre>



<pre class="wp-block-code"><code>configmap/app-file created
Name:         app-file
Namespace:    default
Labels:       &lt;none&gt;
Annotations:  &lt;none&gt;

Data
====
app.properties:
----
color=blue
max_items=20</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="542" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file.png" alt="用 --from-file 把 app.properties 整個檔案放進 ConfigMap app-file，describe 顯示檔名和內容" class="wp-image-13314" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file-300x102.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file-1024x347.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file-768x260.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-03-cm-file-1536x520.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>--from-file=檔名</code>：<strong>檔名變成 key、檔案內容變成值</strong>。等一下掛進 Pod，就會出現一個叫 <code>app.properties</code> 的檔案。</p>



<h3 class="wp-block-heading">步驟 4：建一個 Secret</h3>



<pre class="wp-block-code"><code>kubectl create secret generic db-secret --from-literal=DB_USER=admin --from-literal=DB_PASSWORD='S3cr3t!'; kubectl get secret db-secret -o yaml | grep -A3 '^data'</code></pre>



<pre class="wp-block-code"><code>secret/db-secret created
data:
  DB_PASSWORD: UzNjcjN0IQ==
  DB_USER: YWRtaW4=
kind: Secret</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="206" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret.png" alt="kubectl create secret generic db-secret 建立帳號密碼，YAML 裡的值變成 base64 寫法：UzNjcjN0IQ== 和 YWRtaW4=" class="wp-image-13315" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret-300x39.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret-1024x132.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret-768x99.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-04-secret-1536x198.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>generic</code> 是最常用的一般型 Secret（另外還有放 HTTPS 憑證的 <code>tls</code>、放映像檔倉庫登入資料的 <code>docker-registry</code>）</li>

<li>密碼 <code>S3cr3t!</code> 外面加單引號，是因為 <code>!</code> 在 bash 裡有特殊意義</li>

<li>YAML 裡的值變成 <code>UzNjcjN0IQ==</code>、<code>YWRtaW4=</code>，<strong>看起來像加密，其實不是</strong></li>
</ul>



<h3 class="wp-block-heading">步驟 5：一行指令還原密碼</h3>



<pre class="wp-block-code"><code>kubectl get secret db-secret -o jsonpath='{.data.DB_PASSWORD}'; echo; kubectl get secret db-secret -o jsonpath='{.data.DB_PASSWORD}' | base64 -d; echo</code></pre>



<pre class="wp-block-code"><code>UzNjcjN0IQ==
S3cr3t!</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="141" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode.png" alt="用 jsonpath 取出 DB_PASSWORD 是 UzNjcjN0IQ==，接 base64 -d 就還原成 S3cr3t!" class="wp-image-13316" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode-300x26.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode-1024x90.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode-768x68.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-05-base64-decode-1536x135.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>base64 -d</code>（decode，解碼）一下就變回 <code>S3cr3t!</code>，不需要任何鑰匙。<strong>所以能讀 Secret 的人，就能看到密碼</strong>。保護 Secret 靠的是：限制誰能讀（<a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">第 26 篇</a>會碰到的權限設定）、開啟 etcd 加密，或改用雲端的密碼管理服務。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-03-base64.png" alt="Secret 不是加密：DB_PASSWORD 的 UzNjcjN0IQ== 經過 base64 -d 一行就還原成 S3cr3t!；預設存在 etcd 沒有加密，正式環境要限制權限、開加密或用 Secret Manager" class="wp-image-13317" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-03-base64.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-03-base64-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-03-base64-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-cards-03-base64-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">步驟 6：寫一個用到 ConfigMap 和 Secret 的 Deployment</h3>



<p class="wp-block-paragraph">這份 YAML 用三種方式把設定交給 nginx 容器：</p>



<pre class="wp-block-code"><code>cat &gt; deploy.yaml &lt;&lt;'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cfg-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: cfg-demo
  template:
    metadata:
      labels:
        app: cfg-demo
    spec:
      containers:
      - name: web
        image: nginx:1.31
        envFrom:
        - configMapRef:
            name: app-config
        env:
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: DB_USER
        volumeMounts:
        - name: config-volume
          mountPath: /etc/app
        - name: secret-volume
          mountPath: /etc/secret
          readOnly: true
      volumes:
      - name: config-volume
        configMap:
          name: app-file
      - name: secret-volume
        secret:
          secretName: db-secret
EOF
kubectl apply -f deploy.yaml; kubectl rollout status deployment cfg-demo; P=$(kubectl get pods -l app=cfg-demo -o name); echo $P</code></pre>



<pre class="wp-block-code"><code>deployment.apps/cfg-demo created
Waiting for deployment "cfg-demo" rollout to finish: 0 of 1 updated replicas are available...
deployment "cfg-demo" successfully rolled out
pod/cfg-demo-5d9d9dcf8f-9tnsw</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="876" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy.png" alt="建立 cfg-demo Deployment，用 envFrom 讀 ConfigMap、secretKeyRef 讀 Secret、volumes 掛檔案，rollout 完成" class="wp-image-13318" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy-300x164.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy-1024x561.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy-768x420.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-06-deploy-1536x841.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">三種方式：</p>


<ol class="wp-block-list">
<li><strong><code>envFrom.configMapRef</code></strong>：把 <code>app-config</code> 裡<strong>每一個</strong>值都變成環境變數（<code>APP_ENV</code>、<code>WELCOME</code>）</li>

<li><strong><code>env.valueFrom.secretKeyRef</code></strong>：只挑 <code>db-secret</code> 裡的 <code>DB_USER</code> 這<strong>一個</strong>值，變成環境變數</li>

<li><strong><code>volumes</code>＋<code>volumeMounts</code></strong>：把 <code>app-file</code> 掛成 <code>/etc/app</code> 資料夾裡的檔案；把 <code>db-secret</code> 掛成 <code>/etc/secret</code>，<code>readOnly: true</code> 是唯讀</li>
</ol>



<p class="wp-block-paragraph"><code>volumes</code> 是「這個 Pod 有哪些儲存空間」，<code>volumeMounts</code> 是「掛到容器的哪個路徑」，兩邊用 <code>name</code> 對上。Volume 第 16 篇會細講。最後把 Pod 名字存進變數 <code>P</code>，後面幾步都會用。</p>



<h3 class="wp-block-heading">步驟 7：進 Pod 看設定有沒有到</h3>



<pre class="wp-block-code"><code>kubectl exec $P -- env | grep -E 'APP_ENV|WELCOME|DB_' | sort; kubectl exec $P -- cat /etc/app/app.properties; kubectl exec $P -- ls /etc/secret</code></pre>



<pre class="wp-block-code"><code>APP_ENV=staging
DB_USER=admin
WELCOME=hello v1
color=blue
max_items=20
DB_PASSWORD
DB_USER</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="249" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod.png" alt="Pod 裡的環境變數有 APP_ENV=staging、DB_USER=admin、WELCOME=hello v1；/etc/app/app.properties 是 color=blue；/etc/secret 底下有 DB_PASSWORD 和 DB_USER 兩個檔案" class="wp-image-13319" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod-300x47.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod-1024x159.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod-768x120.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-07-inside-pod-1536x239.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>環境變數：<code>APP_ENV</code>、<code>WELCOME</code> 來自 ConfigMap，<code>DB_USER</code> 來自 Secret，<strong>而且是解碼後的 <code>admin</code></strong>，程式不用自己處理 base64</li>

<li><code>/etc/app/app.properties</code>：就是步驟 3 那個檔案</li>

<li><code>/etc/secret</code> 底下每個 key 變成一個檔案，<code>DB_PASSWORD</code> 檔案的內容就是密碼原文</li>
</ul>



<p class="wp-block-paragraph"><strong>密碼用檔案給比用環境變數安全一點</strong>：環境變數有時會被程式印進日誌、錯誤訊息裡；檔案比較不容易被不小心印出來。</p>



<h3 class="wp-block-heading">步驟 8：改 ConfigMap，計時等檔案更新</h3>



<p class="wp-block-paragraph">把設定檔改成 <code>color=green</code>，同時把 <code>app-config</code> 改成正式環境的值；然後每 5 秒檢查一次 Pod 裡的檔案變了沒：</p>



<pre class="wp-block-code"><code>cat &gt; app.properties &lt;&lt;'EOF'
color=green
max_items=50
EOF
kubectl create configmap app-file --from-file=app.properties --dry-run=client -o yaml | kubectl apply -f -
kubectl create configmap app-config --from-literal=APP_ENV=production --from-literal=WELCOME='hello v2' --dry-run=client -o yaml | kubectl apply -f -
date +%T; for i in $(seq 1 30); do kubectl exec $P -- cat /etc/app/app.properties | grep -q green &amp;&amp; echo "file updated after about $((i*5)) seconds" &amp;&amp; break; sleep 5; done; date +%T</code></pre>



<pre class="wp-block-code"><code>Warning: resource configmaps/app-file is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
configmap/app-file configured
Warning: resource configmaps/app-config is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
configmap/app-config configured
16:00:46
file updated after about 85 seconds
16:02:08</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="488" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait.png" alt="更新兩個 ConfigMap 後每 5 秒檢查一次，檔案在約 85 秒後變成 color=green，時間從 16:00:46 到 16:02:08" class="wp-image-13320" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait-300x92.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait-1024x312.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait-768x234.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-08-update-wait-1536x468.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>kubectl create ... --dry-run=client -o yaml | kubectl apply -f -</code>：用 create 產生新的 YAML，再交給 apply 更新。這是「用指令改 ConfigMap」的常用寫法，<code>-f -</code> 的 <code>-</code> 代表「從前一個指令接過來」</li>

<li>兩行 <code>Warning</code> 的原因在「實測時的意外」第 2 點，不影響結果</li>

<li>迴圈每 5 秒檢查一次，<strong>約 85 秒後</strong>檔案變成 <code>green</code>。<code>date +%T</code> 印出的時間（UTC，台灣要加 8 小時）從 16:00:46 到 16:02:08，差 82 秒，對得上</li>
</ul>



<h3 class="wp-block-heading">步驟 9：檔案變了，環境變數沒變</h3>



<pre class="wp-block-code"><code>kubectl exec $P -- cat /etc/app/app.properties; kubectl exec $P -- env | grep APP_ENV</code></pre>



<pre class="wp-block-code"><code>color=green
max_items=50
APP_ENV=staging</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="202" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated.png" alt="檔案已經是 color=green、max_items=50，但環境變數 APP_ENV 還是 staging" class="wp-image-13321" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated-300x38.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated-1024x129.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated-768x97.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-09-env-not-updated-1536x194.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">同一個 Pod：檔案是新的（<code>green</code>、<code>50</code>），<strong>環境變數還是舊的 <code>staging</code></strong>。環境變數是容器啟動那一刻決定的，之後不會再變。</p>



<h3 class="wp-block-heading">步驟 10：重開 Pod，環境變數才換</h3>



<pre class="wp-block-code"><code>kubectl rollout restart deployment cfg-demo; kubectl rollout status deployment cfg-demo; P=$(kubectl get pods -l app=cfg-demo -o name | tail -1); kubectl exec $P -- env | grep -E 'APP_ENV|WELCOME' | sort</code></pre>



<pre class="wp-block-code"><code>deployment.apps/cfg-demo restarted
Waiting for deployment "cfg-demo" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "cfg-demo" rollout to finish: 1 old replicas are pending termination...
deployment "cfg-demo" successfully rolled out
APP_ENV=production
WELCOME=hello v2</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="228" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env.png" alt="kubectl rollout restart 重開 Deployment 之後，新 Pod 的環境變數變成 APP_ENV=production、WELCOME=hello v2" class="wp-image-13322" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env-300x43.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env-1024x146.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env-768x109.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-10-restart-env-1536x219.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong><code>kubectl rollout restart</code> 是「設定都不改，照滾動更新的方式把 Pod 全部換新」</strong>。新的 Pod 啟動時讀到新的 ConfigMap，環境變數就是 <code>production</code>、<code>hello v2</code> 了。</p>



<h3 class="wp-block-heading">步驟 11：設成不可修改的 ConfigMap</h3>



<pre class="wp-block-code"><code>cat &gt; frozen.yaml &lt;&lt;'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: frozen
immutable: true
data:
  LEVEL: "1"
EOF
kubectl apply -f frozen.yaml; kubectl patch configmap frozen -p '{"data":{"LEVEL":"2"}}'</code></pre>



<pre class="wp-block-code"><code>configmap/frozen created
The ConfigMap "frozen" is invalid: data: Forbidden: field is immutable when `immutable` is set</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="461" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable.png" alt="建立 immutable: true 的 ConfigMap frozen，用 kubectl patch 改 LEVEL 被拒絕：Forbidden field is immutable" class="wp-image-13323" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable-300x86.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable-1024x295.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable-768x221.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-11-immutable-1536x443.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>immutable: true</code>：建好之後內容不能改</li>

<li><code>kubectl patch</code> 是「只改其中幾個欄位」的指令，這裡想把 <code>LEVEL</code> 改成 2，被 <code>Forbidden</code> 擋下</li>

<li><code>LEVEL: "1"</code> 的 1 要加引號：ConfigMap 的值一定要是文字，不加引號 YAML 會當成數字而報錯</li>
</ul>



<p class="wp-block-paragraph">官方文件列出 immutable 的兩個好處：避免誤改造成服務中斷；kubelet 不用一直盯著它有沒有變，叢集裡 ConfigMap 很多時可以減輕 API 伺服器的負擔。設了之後<strong>不能改回來</strong>，要改就刪掉重建，或建一個新名字（例如 <code>app-config-v2</code>）再讓 Deployment 指過去。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. 檔案更新要等 85 秒</h3>



<p class="wp-block-paragraph">很多人改完 ConfigMap 馬上去看 Pod，發現沒變，以為設定失敗。實測掛成檔案的要約 85 秒才同步；官方文件說延遲是 kubelet 同步週期加上快取時間。改完要馬上生效，就直接 <code>kubectl rollout restart</code>。</p>



<p class="wp-block-paragraph">另外，<strong>用 <code>subPath</code> 只掛單一檔案的，官方文件說不會自動更新</strong>，跟環境變數一樣要重開。</p>



<h3 class="wp-block-heading">2. 用 create 建、用 apply 改，會跳警告</h3>



<p class="wp-block-paragraph">步驟 8 出現 <code>missing the kubectl.kubernetes.io/last-applied-configuration annotation</code> 警告。原因是 <code>kubectl apply</code> 會在物件上留一份「上次 apply 的內容」，用來比對這次改了什麼；用 <code>kubectl create</code> 建的物件沒有這份紀錄。kubectl 會自動補上，所以結果正確。想避免，從一開始就用 YAML 檔＋<code>kubectl apply</code> 建，或 create 時加 <code>--save-config</code>。</p>



<h3 class="wp-block-heading">3. Secret 給環境變數時已經解碼</h3>



<p class="wp-block-paragraph">YAML 裡看到的是 <code>YWRtaW4=</code>，但 Pod 裡的環境變數 <code>DB_USER</code> 是 <code>admin</code>，<code>/etc/secret/DB_USER</code> 檔案內容也是 <code>admin</code>。Kubernetes 會自動解碼，程式直接讀就好，<strong>不要在程式裡再 base64 解一次</strong>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<pre class="wp-block-code"><code>kubectl delete -f deploy.yaml -f frozen.yaml; kubectl delete configmap app-config app-file; kubectl delete secret db-secret; minikube delete | tail -1</code></pre>



<pre class="wp-block-code"><code>deployment.apps "cfg-demo" deleted from default namespace
configmap "frozen" deleted from default namespace
configmap "app-config" deleted from default namespace
configmap "app-file" deleted from default namespace
secret "db-secret" deleted from default namespace
💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="227" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup.png" alt="刪掉 Deployment、三個 ConfigMap 和 Secret，最後 minikube delete" class="wp-image-13324" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup-300x43.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup-1024x145.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup-768x109.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct15-shots-12-cleanup-1536x218.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Cloud Shell 和 Minikube 都不收費。<code>~/k8s-cfg</code> 資料夾裡的 YAML 和 <code>app.properties</code> 會留著；這篇的 <code>S3cr3t!</code> 只是示範用的假密碼，<strong>真的密碼不要寫進任何檔案或 Git</strong>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>


<ul class="wp-block-list">
<li><strong>GKE</strong>：ConfigMap、Secret 用法一樣。差別是 GKE 的控制平面由 Google 管，etcd 預設會用 Google 的加密機制存放；需要更嚴格時可以開「應用程式層 Secret 加密」，用你自己在 Cloud KMS 管理的金鑰再加一層</li>

<li><strong>Secret Manager</strong>：Google Cloud 的密碼管理服務，有版本、權限、存取紀錄。正式環境常見的做法是密碼放 Secret Manager，GKE 透過 Secret Manager 外掛把它掛進 Pod，不用存在 Kubernetes 的 Secret 裡</li>

<li><strong>Cloud Run</strong>：沒有 ConfigMap 和 Secret 物件，環境變數直接設在服務上，密碼從 Secret Manager 讀，站上有一篇 <a href="https://dongdonggcp.com/2024/06/22/cloud-run-read-secret-manager/">Cloud Run 讀取 Secret Manager</a></li>
</ul>



<p class="wp-block-paragraph">讓 GKE 的 Pod 有權限讀 Secret Manager，要用第 26 篇〈Workload Identity 是什麼〉的做法。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「ConfigMap 和 Secret 差在哪？」</strong>：ConfigMap 放一般設定、Secret 放敏感資料；Secret 用 base64 存放、可以分開設定權限，但 base64 不是加密，預設 etcd 也沒加密</li>

<li><strong>「改了 ConfigMap，Pod 會自動拿到新值嗎？」</strong>：掛成檔案的會（實測約 85 秒），環境變數不會，要重開 Pod；用 subPath 掛的也不會</li>

<li><strong>「Secret 怎麼保護？」</strong>：RBAC 限制誰能讀、開 etcd 加密（在 GKE 用應用程式層 Secret 加密）、或用外部密碼管理服務（Secret Manager、Vault）</li>

<li><strong>「密碼用環境變數還是檔案給比較好？」</strong>：檔案比較不容易被印進日誌；環境變數比較簡單</li>

<li><strong>「為什麼不把設定寫進映像檔？」</strong>：同一個映像檔要能在不同環境用；密碼進映像檔等於公開</li>
</ul>



<p class="wp-block-paragraph">RBAC（Role-Based Access Control，角色權限控管）是「依照角色決定誰能對什麼資源做什麼事」的機制，第 26 篇會用到。</p>



<h3 class="wp-block-heading">Kubernetes 證照（CKAD、CKA）</h3>



<p class="wp-block-paragraph">上機實作考（445 美元、2 小時，2026 年 11 月查 Linux Foundation 官方頁）。ConfigMap、Secret 常見題型：</p>


<ul class="wp-block-list">
<li>用 <code>--from-literal</code> 或 <code>--from-file</code> 建 ConfigMap、Secret</li>

<li>把某個 key 用 <code>env.valueFrom</code> 變成指定名稱的環境變數</li>

<li>把整個 ConfigMap 用 <code>envFrom</code> 給容器</li>

<li>把 Secret 掛成 Volume 到指定路徑</li>

<li>把 Secret 解碼查內容（<code>base64 -d</code>）</li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「非機密設定」「環境變數」</td><td>ConfigMap</td></tr><tr><td>「密碼」「API key」「憑證」</td><td>Secret</td></tr><tr><td>「base64」</td><td>Secret 的存放寫法，不是加密</td></tr><tr><td>「改設定不用重開」</td><td>掛成 Volume（不能用 subPath）</td></tr><tr><td>「設定不能被改」</td><td><code>immutable: true</code></td></tr><tr><td>「GCP 上的密碼管理」</td><td>Secret Manager</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">ConfigMap 和 Secret 有什麼不同？</h3>



<p class="wp-block-paragraph">ConfigMap 放一般設定，值直接是原文；Secret 放密碼、金鑰、憑證，值用 base64 寫法存放，可以單獨控管誰能讀。兩者給 Pod 的方式一樣（環境變數或檔案），大小上限都是 1MiB。最大的誤解是以為 Secret 有加密，其實預設沒有。</p>



<h3 class="wp-block-heading">Secret 是加密的嗎？</h3>



<p class="wp-block-paragraph">不是。Secret 的值只是用 base64 寫法存放，實測 <code>UzNjcjN0IQ==</code> 接 <code>base64 -d</code> 一行就還原成 <code>S3cr3t!</code>。官方文件寫明 Secret 預設以未加密的方式存在 etcd。保護方式是限制讀取權限、開啟 etcd 加密，或改用 Secret Manager 這類外部服務。</p>



<h3 class="wp-block-heading">改了 ConfigMap，為什麼 Pod 沒有變？</h3>



<p class="wp-block-paragraph">要看 ConfigMap 怎麼給 Pod。用環境變數給的，容器啟動後就不會再變，要 <code>kubectl rollout restart</code> 重開；掛成檔案的會自動更新，但要等一段時間，實測約 85 秒；用 subPath 掛單一檔案的不會自動更新。</p>



<h3 class="wp-block-heading">密碼應該用環境變數還是檔案給 Pod？</h3>



<p class="wp-block-paragraph">兩種都可以，檔案稍微安全一點，因為環境變數比較容易被程式印進日誌或錯誤訊息。實測掛成檔案時，<code>/etc/secret</code> 底下每個 key 是一個檔案，內容已經解碼成原文，程式直接讀就好。</p>



<h3 class="wp-block-heading">ConfigMap 可以放多大的檔案？</h3>



<p class="wp-block-paragraph">單一 ConfigMap 和 Secret 的上限都是 1MiB（約 105 萬位元組），官方設這個限制是怕太大的物件吃光 API 伺服器和 kubelet 的記憶體。設定檔通常只有幾 KB，夠用；大檔案或資料請用 Volume（第 16 篇）。</p>



<h3 class="wp-block-heading">immutable 的 ConfigMap 要怎麼改？</h3>



<p class="wp-block-paragraph">不能改，也不能把 immutable 改回 false。實測用 <code>kubectl patch</code> 修改，回應 <code>Forbidden: field is immutable</code>。要改就刪掉重建，或建一個新名字的 ConfigMap，再把 Deployment 改成指向新的，順便觸發滾動更新。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>設定和密碼拿出映像檔</strong>：一般設定放 ConfigMap、敏感資料放 Secret，同一個映像檔走遍所有環境</li>

<li><strong>兩種給法</strong>：環境變數（<code>envFrom</code>、<code>env.valueFrom</code>）和檔案（<code>volumes</code>）；Secret 給到 Pod 時已經解碼</li>

<li><strong>更新行為不同</strong>：檔案約 85 秒自動更新，環境變數要 <code>kubectl rollout restart</code></li>

<li><strong>Secret 不是加密</strong>：base64 一行還原，預設 etcd 也不加密；正式環境要限權限、開加密或用 Secret Manager</li>

<li><strong><code>immutable: true</code></strong> 防止誤改，設了就改不回來；兩者上限都是 1MiB</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 4 篇：<a href="https://dongdonggcp.com/2026/11/18/dockerfile-tutorial-build-first-image/">Dockerfile 怎麼寫？從零打包你的第一個網頁映像檔</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">映像檔太肥怎麼辦？Docker 多階段建置與 .dockerignore</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>

<li>上一篇：第 14 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">Ingress 是什麼？用網址路徑把流量分給不同服務（含 Gateway API）</a></li>

<li>下一篇：第 16 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/06/22/cloud-run-read-secret-manager/">Cloud Run 讀取 Secret Manager</a></li>

<li><a href="https://dongdonggcp.com/2024/12/10/what-is-gcp-cloud-iam-role-and-permission-introduction/">Cloud IAM 角色與權限</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/tips-when-developing-with-gcp-service-account/">Service Account 開發小技巧</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">設定和密碼搞定之後，下一步是讓資料在 Pod 重建後還留得住。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "ConfigMap 和 Secret 有什麼不同？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "ConfigMap 放一般設定，值直接是原文；Secret 放密碼、金鑰、憑證，值用 base64 寫法存放，可以單獨控管誰能讀。兩者給 Pod 的方式一樣（環境變數或檔案），大小上限都是 1MiB。最大的誤解是以為 Secret 有加密，其實預設沒有。"
      }
    },
    {
      "@type": "Question",
      "name": "Secret 是加密的嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不是。Secret 的值只是用 base64 寫法存放，實測 `UzNjcjN0IQ==` 接 `base64 -d` 一行就還原成 `S3cr3t!`。官方文件寫明 Secret 預設以未加密的方式存在 etcd。保護方式是限制讀取權限、開啟 etcd 加密，或改用 Secret Manager 這類外部服務。"
      }
    },
    {
      "@type": "Question",
      "name": "改了 ConfigMap，為什麼 Pod 沒有變？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "要看 ConfigMap 怎麼給 Pod。用環境變數給的，容器啟動後就不會再變，要 `kubectl rollout restart` 重開；掛成檔案的會自動更新，但要等一段時間，實測約 85 秒；用 subPath 掛單一檔案的不會自動更新。"
      }
    },
    {
      "@type": "Question",
      "name": "密碼應該用環境變數還是檔案給 Pod？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "兩種都可以，檔案稍微安全一點，因為環境變數比較容易被程式印進日誌或錯誤訊息。實測掛成檔案時，`/etc/secret` 底下每個 key 是一個檔案，內容已經解碼成原文，程式直接讀就好。"
      }
    },
    {
      "@type": "Question",
      "name": "ConfigMap 可以放多大的檔案？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "單一 ConfigMap 和 Secret 的上限都是 1MiB（約 105 萬位元組），官方設這個限制是怕太大的物件吃光 API 伺服器和 kubelet 的記憶體。設定檔通常只有幾 KB，夠用；大檔案或資料請用 Volume（第 16 篇）。"
      }
    },
    {
      "@type": "Question",
      "name": "immutable 的 ConfigMap 要怎麼改？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不能改，也不能把 immutable 改回 false。實測用 `kubectl patch` 修改，回應 `Forbidden: field is immutable`。要改就刪掉重建，或建一個新名字的 ConfigMap，再把 Deployment 改成指向新的，順便觸發滾動更新。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Deployment 教學：自動補位、擴縮、滾動更新與回滾</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-deployment-rolling-update-rollback</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:35:01 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13275</guid>

					<description><![CDATA[<p>K8s Deployment 教學：Cloud Shell 實測刪 Pod 1 秒補回、擴成 5 個、nginx 滾動更新 8.8 秒換完；maxSurge 算一次，換錯版本舊 Pod 照跑，rollout undo 一行回滾。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>K8s Deployment 管一群相同的 Pod：壞了自動補、要幾個就幾個，換版時一個一個換，出事一行回滾。</strong></p>



<p class="wp-block-paragraph">第 11 篇直接建的 Pod 有兩個大問題：刪了不會補、大部分設定改不了。正式環境真正在用的是 <strong>Deployment</strong>。這篇在 Cloud Shell 把 Deployment 的四大能力各做一次：刪 Pod 看它 1 秒補回來、從 3 個擴到 5 個、把 nginx 從 1.30 滾動更新到 1.31（實測 3 個換完 8.8 秒）；最後故意換一個不存在的版本，看舊的 3 個 Pod 怎麼繼續撐住網站，再用一行指令回滾。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 12 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。Pod 和 YAML 的基本寫法請先看第 11 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-01-layers.png" alt="Deployment 管 ReplicaSet、ReplicaSet 管 Pod：實測 web 這個 Deployment 底下的 ReplicaSet web-544b69cccb 保持剛好 3 個 Pod" class="wp-image-13258" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-01-layers.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-01-layers-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-01-layers-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-01-layers-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>正式環境幾乎都用 Deployment</strong>：網站、API 這類「不用記住自己狀態」的程式，在 Kubernetes 上 9 成以上都是用 Deployment 部署的</li>

<li><strong>更新不停機</strong>：一次把舊版全關掉再開新版，中間網站會斷；Deployment 的滾動更新是一個一個換，使用者幾乎感覺不到</li>

<li><strong>出事能馬上退</strong>：新版本有 bug，<code>kubectl rollout undo</code> 一行就回到上一版。這是值班工程師半夜最需要的一招</li>

<li><strong>面試和證照必考</strong>：「滾動更新怎麼運作」「怎麼回滾」是 Kubernetes 面試的經典題；CKAD 上機考會直接要你換版和回滾</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Deployment 是什麼</h2>



<p class="wp-block-paragraph"><strong>Deployment 是一份「我要幾個什麼樣的 Pod」的設定，Kubernetes 會一直幫你維持這個數量，並且負責換版本。</strong></p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳的排班表寫「現場要 3 位廚師」。有人請假，店長馬上叫替補；換新菜單時，不會一次把 3 位都叫去受訓（那餐廳就沒人煮了），而是一位一位輪流去學</li>

<li><strong>來龍去脈</strong>：deployment 是英文的「部署」。早期 Kubernetes 用 ReplicationController 維持 Pod 數量，但換版本要自己手動處理；後來出現 Deployment，把「維持數量」和「換版本」包在一起，現在是官方推薦的做法（<a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Kubernetes 官方說明：Deployments</a>）</li>

<li><strong>為什麼要學</strong>：不用 Deployment，你就得自己盯著每個 Pod、自己一個一個換版本；用了它，這些事都交給控制器</li>
</ul>



<h3 class="wp-block-heading">ReplicaSet 是什麼</h3>



<p class="wp-block-paragraph"><strong>ReplicaSet 是「保持剛好 N 個相同 Pod」的控制器</strong>，Deployment 透過它來管 Pod。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：排班表是 Deployment，ReplicaSet 是「某一版菜單的廚師名單」。換菜單時，店長開一張新名單（新的 ReplicaSet），慢慢把人從舊名單移過去；舊名單先留著，萬一新菜單出問題可以馬上換回去</li>

<li><strong>來龍去脈</strong>：replica 是「複製品、副本」。它取代了舊的 ReplicationController</li>

<li><strong>為什麼要學</strong>：你幾乎不會自己建 ReplicaSet，但排錯時一定會看到它。<strong>每換一次版本，Deployment 就建一個新的 ReplicaSet</strong>，舊的留著當回滾用</li>
</ul>



<p class="wp-block-paragraph">三層關係：<strong>Deployment → ReplicaSet → Pod</strong>。Pod 名字 <code>web-544b69cccb-h5rd2</code> 就是「Deployment 名字－ReplicaSet 代號－隨機 5 個字」。</p>



<h3 class="wp-block-heading">標籤選擇器（selector）：Deployment 怎麼認得自己的 Pod</h3>



<p class="wp-block-paragraph"><strong>選擇器是「用標籤挑東西」的條件。</strong> Deployment 的 YAML 有兩個地方要寫一樣的標籤：</p>


<ul class="wp-block-list">
<li><code>spec.selector.matchLabels</code>：我要管「標籤是 <code>app: web</code>」的 Pod</li>

<li><code>spec.template.metadata.labels</code>：我建出來的 Pod 要貼上 <code>app: web</code></li>
</ul>



<p class="wp-block-paragraph">兩邊對不上，<code>kubectl apply</code> 會直接報錯。可以想成「排班表上寫要管穿藍色制服的人，那你招進來的人就要發藍色制服」。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">滾動更新是什麼</h2>



<p class="wp-block-paragraph"><strong>滾動更新（Rolling Update）是一次只換幾個 Pod，新的好了才關舊的，直到全部換完。</strong> 這是 Deployment 的預設做法。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：3 位廚師輪流去學新菜單，現場一直有人在煮</li>

<li><strong>來龍去脈</strong>：相對的做法叫 <strong>Recreate（全部重建）</strong>：先把舊的全部關掉，再開新的。簡單，但中間一定會斷線。只有「新舊版本不能同時存在」的程式（例如兩版會搶同一個資料庫結構）才用 Recreate</li>

<li><strong>為什麼要學</strong>：滾動更新的速度和安全性，由兩個數字決定，面試很愛問</li>
</ul>



<h3 class="wp-block-heading">maxSurge 和 maxUnavailable 怎麼算</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>設定</th><th>白話</th><th>預設</th><th>小數怎麼處理</th></tr></thead><tbody><tr><td><code>maxSurge</code></td><td>換版時，<strong>最多可以比設定的數量多開幾個</strong></td><td>25%</td><td>無條件<strong>進位</strong></td></tr><tr><td><code>maxUnavailable</code></td><td>換版時，<strong>最多可以有幾個不能用</strong></td><td>25%</td><td>無條件<strong>捨去</strong></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">（<a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment">Kubernetes 官方說明：Rolling Update Deployment</a>，2026 年 11 月查）</p>



<p class="wp-block-paragraph"><strong>算一次，用這篇的 3 個副本</strong>：</p>


<ul class="wp-block-list">
<li>maxSurge：3 × 25%＝0.75 → 進位＝<strong>1</strong>，所以換版時最多有 3＋1＝<strong>4 個</strong> Pod</li>

<li>maxUnavailable：3 × 25%＝0.75 → 捨去＝<strong>0</strong>，所以換版時<strong>至少 3 個</strong>都能用</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-02-rolling.png" alt="滾動更新怎麼算：3 個副本時 maxSurge 0.75 進位成 1、maxUnavailable 0.75 捨去成 0，所以最多 4 個、至少 3 個能用；先多開 1 個新的、新的好了再關 1 個舊的" class="wp-image-13259" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-02-rolling.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-02-rolling-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-02-rolling-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-02-rolling-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">意思是：先多開 1 個新的，新的好了才關 1 個舊的，一直保持 3 個可用。實作的步驟 10 會看到 Kubernetes 印出 <code>4 total | 3 available</code>，跟算出來的一模一樣。</p>



<p class="wp-block-paragraph"><strong>數字變大會怎樣</strong>：如果副本是 10 個，maxSurge＝2.5 進位成 3、maxUnavailable＝2.5 捨去成 2，換版時最多 13 個、至少 8 個能用，一次可以換比較多個，速度比較快，但同時要多準備 3 個 Pod 的資源。maxSurge 越大越快、越吃資源；maxUnavailable 越大越快、但服務能力降得越多。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：Deployment 的補位、擴縮、更新、回滾</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，跳出「授權 Cloud Shell」按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<h3 class="wp-block-heading">步驟 1：開資料夾和叢集</h3>



<pre class="wp-block-code"><code>mkdir -p ~/k8s-deploy &amp;&amp; cd ~/k8s-deploy; minikube start | tail -1</code></pre>



<pre class="wp-block-code"><code>（前面省略：版本提醒和硬碟空間警告）
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="342" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start.png" alt="建立 k8s-deploy 資料夾並啟動 minikube，最後一行顯示 Done" class="wp-image-13260" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start-300x64.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start-1024x219.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start-768x164.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-01-start-1536x328.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 2：寫 Deployment 的 YAML 並建立</h3>



<pre class="wp-block-code"><code>cat &gt; deployment.yaml &lt;&lt;'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        image: nginx:1.30
        ports:
        - containerPort: 80
EOF
kubectl apply -f deployment.yaml; sleep 20; kubectl get deployment,replicaset,pod</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web created
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/web   3/3     3            3           20s

NAME                             DESIRED   CURRENT   READY   AGE
replicaset.apps/web-544b69cccb   3         3         3       20s

NAME                       READY   STATUS    RESTARTS   AGE
pod/web-544b69cccb-h5rd2   1/1     Running   0          20s
pod/web-544b69cccb-rd679   1/1     Running   0          20s
pod/web-544b69cccb-td5pn   1/1     Running   0          20s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1306" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply.png" alt="kubectl apply 建立 Deployment web，底下一個 ReplicaSet web-544b69cccb 和 3 個 Running 的 Pod" class="wp-image-13261" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply-300x245.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply-1024x836.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply-768x627.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-02-apply-1536x1254.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">跟第 11 篇 Pod 的 YAML 比，差在這幾行：</p>


<ul class="wp-block-list">
<li><code>apiVersion: apps/v1</code>：Deployment 屬於 <code>apps</code> 這組 API，不是 Pod 用的 <code>v1</code></li>

<li><code>replicas: 3</code>：要 3 個</li>

<li><code>selector.matchLabels</code>：我管標籤 <code>app: web</code> 的 Pod</li>

<li><code>template:</code> 底下：<strong>Pod 的範本</strong>，內容就是第 11 篇那份 Pod YAML 的 metadata 和 spec，只是不用寫名字（名字由 Deployment 自動產生）</li>
</ul>



<p class="wp-block-paragraph"><code>READY 3/3</code>、<code>DESIRED 3 / CURRENT 3 / READY 3</code> 都對上了，代表 3 個都健康。</p>



<h3 class="wp-block-heading">步驟 3：刪一個 Pod，看它自動補回來</h3>



<pre class="wp-block-code"><code>kubectl delete $(kubectl get pods -l app=web -o name | head -1); kubectl get pods</code></pre>



<pre class="wp-block-code"><code>pod "web-544b69cccb-h5rd2" deleted from default namespace
NAME                   READY   STATUS    RESTARTS   AGE
web-544b69cccb-84zt7   1/1     Running   0          1s
web-544b69cccb-rd679   1/1     Running   0          28s
web-544b69cccb-td5pn   1/1     Running   0          28s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="268" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal.png" alt="刪掉 web-544b69cccb-h5rd2 之後，立刻出現新的 web-544b69cccb-84zt7，AGE 1 秒、已經 Running" class="wp-image-13262" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal-300x50.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal-1024x172.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal-768x129.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-03-self-heal-1536x257.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>$( … )</code> 是「先跑括號裡的指令，把結果放進來」，這裡是挑出第一個 Pod 的名字。刪掉 <code>h5rd2</code> 後立刻多了一個 <code>84zt7</code>，<code>AGE 1s</code> 就已經 <code>Running</code>（映像檔已經在節點上，不用再下載）。第 11 篇直接建的 Pod 刪了就沒了，這就是差別。</p>



<h3 class="wp-block-heading">步驟 4：擴成 5 個</h3>



<pre class="wp-block-code"><code>kubectl scale deployment web --replicas=5; sleep 5; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web scaled
NAME                   READY   STATUS    RESTARTS   AGE
web-544b69cccb-84zt7   1/1     Running   0          12s
web-544b69cccb-rd679   1/1     Running   0          39s
web-544b69cccb-spftg   1/1     Running   0          5s
web-544b69cccb-td5pn   1/1     Running   0          39s
web-544b69cccb-xc8mm   1/1     Running   0          5s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="382" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5.png" alt="kubectl scale 擴成 5 個，多了 spftg 和 xc8mm 兩個 5 秒前建立的 Pod" class="wp-image-13263" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5-300x72.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5-1024x244.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5-768x183.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-04-scale-5-1536x367.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">5 秒內就多了 2 個。<strong>擴縮（scale）只改數量，不會換版本</strong>，所以新的 Pod 跟舊的屬於同一個 ReplicaSet（<code>544b69cccb</code>）。</p>



<h3 class="wp-block-heading">步驟 5：再 apply 一次檔案，又變回 3 個</h3>



<pre class="wp-block-code"><code>kubectl apply -f deployment.yaml; sleep 5; kubectl get deployment web; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web configured
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    3/3     3            3           50s
NAME                   READY   STATUS    RESTARTS   AGE
web-544b69cccb-84zt7   1/1     Running   0          23s
web-544b69cccb-rd679   1/1     Running   0          50s
web-544b69cccb-td5pn   1/1     Running   0          50s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="311" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3.png" alt="再 apply 一次 deployment.yaml，Deployment 從 5 個縮回檔案裡寫的 3 個" class="wp-image-13264" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3-300x58.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3-1024x199.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3-768x149.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-05-apply-back-3-1536x299.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">檔案裡寫的是 <code>replicas: 3</code>，apply 之後就回到 3 個，步驟 4 用指令擴出來的 2 個被刪掉了。<strong>指令改的和檔案寫的不一樣時，以最後一次送出的為準</strong>。正式環境通常以檔案（放在 Git 裡的 YAML）為準，用指令臨時改的東西，下次有人 apply 就會被蓋掉。</p>



<h3 class="wp-block-heading">步驟 6：滾動更新，把 nginx 從 1.30 換成 1.31</h3>



<p class="wp-block-paragraph">先幫目前這一版寫個備註，再換映像檔，最後用 <code>rollout status</code> 看進度，前面加 <code>time</code> 計時：</p>



<pre class="wp-block-code"><code>kubectl annotate deployment web kubernetes.io/change-cause='nginx 1.30 first release'; kubectl set image deployment/web nginx=nginx:1.31; time kubectl rollout status deployment/web</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web annotated
deployment.apps/web image updated
Waiting for deployment "web" rollout to finish: 1 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
deployment "web" successfully rolled out

real    0m8.796s
user    0m0.082s
sys     0m0.030s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="466" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update.png" alt="kubectl set image 觸發滾動更新，rollout status 顯示 1 out of 3、2 out of 3 逐步更新，8.8 秒後 successfully rolled out" class="wp-image-13265" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update-300x87.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update-1024x298.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update-768x224.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-06-rolling-update-1536x447.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong><code>annotate</code>（註記）是在東西上加一段說明文字</strong>。<code>kubernetes.io/change-cause</code> 這個名字比較特別，<code>rollout history</code> 會把它當成「這一版改了什麼」顯示出來</li>

<li><code>set image deployment/web nginx=nginx:1.31</code>：把 web 裡叫 <code>nginx</code> 的容器，映像檔換成 <code>nginx:1.31</code>。容器名字就是 YAML 裡 <code>- name: nginx</code> 那個</li>

<li><code>rollout status</code> 會一直顯示進度直到完成：<code>1 out of 3</code> → <code>2 out of 3</code> → <code>1 old replicas are pending termination</code>（剩 1 個舊的在收尾）→ 完成</li>
</ul>



<p class="wp-block-paragraph">3 個 Pod 換完一共 <strong>8.8 秒</strong>，過程中一直有 3 個可以用。</p>



<h3 class="wp-block-heading">步驟 7：看新舊兩個 ReplicaSet</h3>



<pre class="wp-block-code"><code>kubectl annotate deployment web kubernetes.io/change-cause='upgrade to nginx 1.31' --overwrite; kubectl get replicaset; kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web annotated
NAME             DESIRED   CURRENT   READY   AGE
web-544b69cccb   0         0         0       69s
web-56649cb68c   3         3         3       14s
NAME                   IMAGE
web-56649cb68c-4crkv   nginx:1.31
web-56649cb68c-8wjzq   nginx:1.31
web-56649cb68c-s69fd   nginx:1.31</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="271" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs.png" alt="滾動更新後有兩個 ReplicaSet：舊的 web-544b69cccb 是 0 個、新的 web-56649cb68c 是 3 個，Pod 映像檔都是 nginx:1.31" class="wp-image-13266" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs-300x51.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs-1024x173.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs-768x130.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-07-new-rs-1536x260.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>新版本的備註用 <code>--overwrite</code> 蓋過去（同一個註記名字要覆蓋，不加會報錯）</li>

<li><strong>舊的 ReplicaSet <code>544b69cccb</code> 沒有被刪，只是變成 0 個</strong>，留著當回滾用；新的 <code>56649cb68c</code> 有 3 個</li>

<li><code>-o custom-columns=欄名:路徑</code> 是自己挑要顯示哪幾欄，這裡看 Pod 名字和映像檔：3 個都是 <code>nginx:1.31</code></li>
</ul>



<p class="wp-block-paragraph">預設會保留最近 10 個舊的 ReplicaSet（<code>revisionHistoryLimit: 10</code>，第 10 篇用 <code>-o yaml</code> 看過這行）。</p>



<h3 class="wp-block-heading">步驟 8：看版本歷史</h3>



<pre class="wp-block-code"><code>kubectl rollout history deployment/web</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web
REVISION  CHANGE-CAUSE
1         nginx 1.30 first release
2         upgrade to nginx 1.31</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1301" height="390" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-08-history.png" alt="kubectl rollout history 顯示兩個版本：1 是 nginx 1.30 first release、2 是 upgrade to nginx 1.31" class="wp-image-13267" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-08-history.png 1301w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-08-history-300x90.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-08-history-1024x307.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-08-history-768x230.png 768w" sizes="(max-width: 1301px) 100vw, 1301px" /></figure>



<p class="wp-block-paragraph"><strong>每一個 REVISION（版本）就是一個 ReplicaSet。</strong> CHANGE-CAUSE 就是步驟 6、7 用 annotate 寫的備註；沒寫的話這欄會是 <code>&lt;none&gt;</code>，半年後回頭看就不知道每一版改了什麼。</p>



<h3 class="wp-block-heading">步驟 9：故意換一個不存在的版本</h3>



<p class="wp-block-paragraph">nginx 沒有 9.99 這個版本，模擬「工程師打錯版本號」：</p>



<pre class="wp-block-code"><code>kubectl set image deployment/web nginx=nginx:9.99; kubectl annotate deployment web kubernetes.io/change-cause='bad tag 9.99' --overwrite; sleep 25; kubectl get pods; kubectl rollout status deployment/web --timeout=5s</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web image updated
deployment.apps/web annotated
NAME                   READY   STATUS             RESTARTS   AGE
web-56649cb68c-4crkv   1/1     Running            0          43s
web-56649cb68c-8wjzq   1/1     Running            0          51s
web-56649cb68c-s69fd   1/1     Running            0          44s
web-c97647d7c-z9sm7    0/1     ImagePullBackOff   0          26s
Waiting for deployment "web" rollout to finish: 1 out of 3 new replicas have been updated...
error: timed out waiting for the condition</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="295" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update.png" alt="換成不存在的 nginx:9.99 後，新的 Pod 卡在 ImagePullBackOff，舊的 3 個 nginx:1.31 Pod 照樣 Running" class="wp-image-13268" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update-300x55.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update-1024x189.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update-768x142.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-09-bad-update-1536x283.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這是滾動更新最有價值的地方：</p>


<ul class="wp-block-list">
<li>新的 Pod（<code>c97647d7c-z9sm7</code>）拉不到映像檔，卡在 <strong><code>ImagePullBackOff</code></strong>（拉映像檔失敗，等一下再試），<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-troubleshooting-crashloopbackoff/">第 18 篇</a>會專門講這個錯誤</li>

<li><strong>舊的 3 個 Pod 完全沒被動</strong>，網站照常服務。因為 maxUnavailable 是 0，新的沒好之前，一個舊的都不會關</li>

<li><code>rollout status --timeout=5s</code> 等 5 秒還沒完成就放棄，印出 <code>timed out</code>。不加 <code>--timeout</code> 的話它會一直等</li>
</ul>



<p class="wp-block-paragraph">如果是 Recreate 策略，舊的 3 個會先全部被關掉，這時網站就整個掛了。</p>



<h3 class="wp-block-heading">步驟 10：看卡住的狀態</h3>



<pre class="wp-block-code"><code>kubectl get replicaset; kubectl describe deployment web | grep -E 'Replicas:|StrategyType|RollingUpdateStrategy'</code></pre>



<pre class="wp-block-code"><code>NAME             DESIRED   CURRENT   READY   AGE
web-544b69cccb   0         0         0       116s
web-56649cb68c   3         3         3       61s
web-c97647d7c    1         1         0       36s
Replicas:               3 desired | 1 updated | 4 total | 3 available | 1 unavailable
StrategyType:           RollingUpdate
RollingUpdateStrategy:  25% max unavailable, 25% max surge</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="251" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck.png" alt="三個 ReplicaSet：1.30 那版 0 個、1.31 那版 3 個、9.99 那版 1 個但 READY 0；describe 顯示 4 total、3 available、1 unavailable" class="wp-image-13269" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck-300x47.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck-1024x161.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck-768x120.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-10-stuck-1536x241.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>Replicas: 3 desired | 1 updated | 4 total | 3 available | 1 unavailable</code>：想要 3 個、1 個已換成新版、<strong>總共 4 個</strong>、<strong>3 個能用</strong>、1 個不能用。跟前面算的「最多 4 個、至少 3 個能用」完全一樣。下面兩行確認策略是 <code>RollingUpdate</code>、兩個參數都是預設的 25%。</p>



<h3 class="wp-block-heading">步驟 11：一行指令回滾</h3>



<pre class="wp-block-code"><code>kubectl rollout undo deployment/web; kubectl rollout status deployment/web; kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image,STATUS:.status.phase</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web rolled back
deployment "web" successfully rolled out
NAME                   IMAGE        STATUS
web-56649cb68c-4crkv   nginx:1.31   Running
web-56649cb68c-8wjzq   nginx:1.31   Running
web-56649cb68c-s69fd   nginx:1.31   Running
web-c97647d7c-z9sm7    nginx:9.99   Pending</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="249" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo.png" alt="kubectl rollout undo 回到上一版，3 個 nginx:1.31 的 Pod Running，壞掉的 9.99 Pod 還在清理中" class="wp-image-13270" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo-300x47.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo-1024x159.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo-768x120.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-11-undo-1536x239.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong><code>rollout undo</code> 是回到上一個版本</strong>。回滾馬上就完成了，因為 1.31 的 3 個 Pod 本來就還在跑，只要把壞掉那個收掉就好。那個 9.99 的 Pod 還出現在清單上（phase 是 <code>Pending</code>，它從來沒成功跑起來過），是正在被清掉，過幾秒就會消失。</p>



<p class="wp-block-paragraph">想回到更早的版本，可以加 <code>--to-revision=版本號</code>，版本號用 <code>rollout history</code> 查。</p>



<h3 class="wp-block-heading">步驟 12：回滾後的版本歷史</h3>



<pre class="wp-block-code"><code>kubectl rollout history deployment/web</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web
REVISION  CHANGE-CAUSE
1         nginx 1.30 first release
3         bad tag 9.99
4         upgrade to nginx 1.31</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1301" height="436" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-12-history-after.png" alt="回滾後 rollout history 剩 1、3、4 三個版本，原本的第 2 版變成第 4 版" class="wp-image-13271" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-12-history-after.png 1301w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-12-history-after-300x101.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-12-history-after-1024x343.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-12-history-after-768x257.png 768w" sizes="(max-width: 1301px) 100vw, 1301px" /></figure>



<p class="wp-block-paragraph">版本 2 不見了，多了一個版本 4，備註是 <code>upgrade to nginx 1.31</code>。<strong>回滾不是「倒退」，而是把舊版本的設定拿出來，當成最新的一版重新發布</strong>，所以它拿到新的號碼 4，原本的 2 就合併進去了。</p>



<h3 class="wp-block-heading">步驟 13：舊教學的 &#8211;record 已經棄用</h3>



<p class="wp-block-paragraph">網路上很多教學用 <code>--record</code> 自動記錄變更原因，實際打一次看看：</p>



<pre class="wp-block-code"><code>kubectl set image deployment/web nginx=nginx:1.31 --record</code></pre>



<pre class="wp-block-code"><code>Flag --record has been deprecated, --record will be removed in the future
deployment.apps/web image updated</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="223" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag.png" alt="kubectl set image 加 --record 跳出 Flag --record has been deprecated 的警告" class="wp-image-13272" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag-1024x143.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag-768x107.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-13-record-flag-1536x214.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>deprecated</code>（已棄用）：還能用，但官方不建議，未來會移除。現在的做法就是步驟 6、7 用的 <code>kubectl annotate ... kubernetes.io/change-cause=...</code>，自己寫備註，內容也比較清楚。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-03-commands.png" alt="Deployment 必學指令：scale 改數量、set image 換映像檔、rollout status 看進度、rollout history 列歷史、rollout undo 回上一版、annotate 寫 change-cause 備註" class="wp-image-13273" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-03-commands.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-03-commands-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-03-commands-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-cards-03-commands-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. 版本號會跳號</h3>



<p class="wp-block-paragraph">回滾之後 <code>rollout history</code> 從 1、2、3 變成 1、3、4，版本 2 消失。很多人以為 undo 會「回到第 2 版」，其實是「複製第 2 版的設定，發布成第 4 版」。所以看歷史時要看 CHANGE-CAUSE 備註，不要只看號碼。</p>



<h3 class="wp-block-heading">2. rollout status 說成功時，壞掉的 Pod 還在</h3>



<p class="wp-block-paragraph">步驟 11 的 <code>rollout status</code> 已經印 <code>successfully rolled out</code>，但清單上還看得到 9.99 那個 Pod。因為 rollout status 看的是「想要的 Pod 都準備好了沒」，壞掉的那個只是還沒清完，過幾秒就不見了。</p>



<h3 class="wp-block-heading">3. 沒加 &#8211;timeout 會一直等</h3>



<p class="wp-block-paragraph"><code>rollout status</code> 預設會一直等到更新完成。Deployment 有一個 <code>progressDeadlineSeconds: 600</code>（第 10 篇 <code>-o yaml</code> 看得到），代表 600 秒（10 分鐘）內沒有進展，Kubernetes 才會把這次更新標成失敗。寫在自動化流程（例如 Cloud Build）裡時，記得自己加 <code>--timeout</code>，不然壞掉的更新會讓流程卡 10 分鐘。</p>



<h3 class="wp-block-heading">4. 指令擴出來的 Pod 被檔案蓋掉</h3>



<p class="wp-block-paragraph">步驟 4 用 <code>kubectl scale</code> 擴成 5 個，步驟 5 一 apply 檔案就變回 3 個。實際工作中最常見的情況是：值班工程師半夜手動擴容撐流量，隔天有人照 Git 裡的 YAML 部署新版，Pod 數量就被打回原形。要長期改數量，就改檔案；要自動依流量調整，用<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">第 17 篇</a>會教的 HPA。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<pre class="wp-block-code"><code>kubectl delete -f deployment.yaml; sleep 3; kubectl get all; minikube delete | tail -1</code></pre>



<pre class="wp-block-code"><code>deployment.apps "web" deleted from default namespace
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    &lt;none&gt;        443/TCP   2m36s
💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="224" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup.png" alt="kubectl delete -f 刪掉 Deployment，get all 只剩內建的 kubernetes Service，minikube delete 刪掉叢集" class="wp-image-13274" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup-1024x143.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup-768x108.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct12-shots-14-cleanup-1536x215.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪 Deployment 會連同底下所有 ReplicaSet 和 Pod 一起刪掉，<code>get all</code> 只剩叢集內建的 <code>service/kubernetes</code>。<code>~/k8s-deploy/deployment.yaml</code> 留在家目錄，第 13 篇講 Service 時可以接著用。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>


<ul class="wp-block-list">
<li><strong>GKE</strong>：這份 <code>deployment.yaml</code> 不用改就能 apply 到 GKE，滾動更新、回滾的指令完全一樣。<a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">第 25 篇</a>〈GKE 部署教學〉會實際搬過去</li>

<li><strong>Cloud Run</strong>：沒有 Deployment 和 ReplicaSet，但概念很像。Cloud Run 每次部署會產生一個不能修改的「修訂版本（revision）」，回滾就是把流量切回舊的修訂版本，還可以「新版 10%、舊版 90%」慢慢切。第 20 篇：<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a>會實際做</li>
</ul>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>概念</th><th>Kubernetes Deployment</th><th>Cloud Run</th></tr></thead><tbody><tr><td>一個版本</td><td>ReplicaSet（REVISION）</td><td>修訂版本（Revision）</td></tr><tr><td>換版</td><td>滾動更新</td><td>部署新修訂版本，流量自動切過去</td></tr><tr><td>回滾</td><td><code>kubectl rollout undo</code></td><td>把流量切回舊的修訂版本</td></tr><tr><td>部分流量測試</td><td>要另外設計（兩個 Deployment 或其他工具）</td><td>內建流量分割</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「Deployment、ReplicaSet、Pod 是什麼關係？」</strong>：Deployment 管 ReplicaSet、ReplicaSet 維持 Pod 數量；每換一次版本，Deployment 建一個新的 ReplicaSet，舊的縮成 0 留著當回滾用</li>

<li><strong>「滾動更新怎麼運作？」</strong>：一次換幾個，由 maxSurge（最多多開幾個，進位）和 maxUnavailable（最多幾個不能用，捨去）決定；預設都是 25%</li>

<li><strong>「新版本有 bug 怎麼辦？」</strong>：<code>kubectl rollout undo</code>；要回到特定版本加 <code>--to-revision</code></li>

<li><strong>「RollingUpdate 和 Recreate 差在哪？」</strong>：RollingUpdate 不停機但新舊版會同時存在；Recreate 先全關再全開，會斷線，適合新舊版不能共存的程式</li>

<li><strong>「換版時打錯映像檔名會怎樣？」</strong>：新 Pod 卡 ImagePullBackOff，舊 Pod 照跑（maxUnavailable 為 0 時一個都不會關），回滾就好</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKAD、CKA）</h3>



<p class="wp-block-paragraph">上機實作考（445 美元、2 小時，2026 年 11 月查 Linux Foundation 官方頁）。Deployment 常見題型：</p>


<ul class="wp-block-list">
<li>建一個 Deployment，指定映像檔和副本數（<code>kubectl create deployment</code> 加 <code>--replicas</code>，或 YAML）</li>

<li>把映像檔換成新版本，並確認滾動更新完成（<code>set image</code>＋<code>rollout status</code>）</li>

<li>回滾到上一版或指定版本（<code>rollout undo</code>、<code>--to-revision</code>）</li>

<li>調整 maxSurge、maxUnavailable 或改成 Recreate 策略（改 YAML 的 <code>spec.strategy</code>）</li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「無狀態應用」「維持固定數量」</td><td>Deployment</td></tr><tr><td>「不停機更新」</td><td>RollingUpdate</td></tr><tr><td>「先全部停掉再更新」</td><td>Recreate</td></tr><tr><td>「回到上一版」</td><td><code>kubectl rollout undo</code></td></tr><tr><td>「換版時最多多開幾個」</td><td>maxSurge</td></tr><tr><td>「換版時最多幾個不能用」</td><td>maxUnavailable</td></tr><tr><td>「記錄每一版改了什麼」</td><td><code>kubernetes.io/change-cause</code> 註記</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Deployment 和 ReplicaSet 有什麼不同？</h3>



<p class="wp-block-paragraph">ReplicaSet 只負責「保持剛好 N 個相同的 Pod」；Deployment 在它上面多了「換版本」和「回滾」。每換一次映像檔，Deployment 建一個新的 ReplicaSet，舊的縮成 0 個保留下來。實測換版後有兩個 ReplicaSet：舊的 <code>544b69cccb</code> 是 0 個、新的 <code>56649cb68c</code> 是 3 個。</p>



<h3 class="wp-block-heading">滾動更新會讓網站斷線嗎？</h3>



<p class="wp-block-paragraph">預設設定下，換版過程一直保持設定的數量可以用。實測 3 個副本換版時，最多 4 個、至少 3 個可用，8.8 秒換完。要做到使用者完全無感，還需要搭配 Service 分流量（第 13 篇）和健康檢查 Probe（第 17 篇），讓流量只送給真的準備好的 Pod。</p>



<h3 class="wp-block-heading">更新到一半失敗怎麼辦？</h3>



<p class="wp-block-paragraph">先看 <code>kubectl get pods</code>，新 Pod 卡在 <code>ImagePullBackOff</code>、<code>CrashLoopBackOff</code> 這類狀態時，舊 Pod 通常還在服務。接著 <code>kubectl rollout undo deployment/名字</code> 回到上一版。實測換成不存在的 nginx:9.99，舊的 3 個 Pod 一直 Running，undo 之後馬上恢復。</p>



<h3 class="wp-block-heading">rollout history 的 CHANGE-CAUSE 是空的怎麼辦？</h3>



<p class="wp-block-paragraph">這欄來自 Deployment 上的 <code>kubernetes.io/change-cause</code> 註記。每次換版後用 <code>kubectl annotate deployment 名字 kubernetes.io/change-cause='這次改了什麼' --overwrite</code> 寫一行說明就好。舊教學用的 <code>--record</code> 實測會跳出 <code>Flag --record has been deprecated</code> 警告，不建議再用。</p>



<h3 class="wp-block-heading">用 kubectl scale 還是改 YAML 檔？</h3>



<p class="wp-block-paragraph">臨時調整可以用 <code>kubectl scale</code>，但下次有人 <code>kubectl apply -f</code> 檔案時，數量會被改回檔案寫的值。實測擴到 5 個後再 apply 檔案，就變回 3 個。要長期改就改檔案；要依流量自動調整，用 HPA。</p>



<h3 class="wp-block-heading">回滾後版本號為什麼跳號？</h3>



<p class="wp-block-paragraph">回滾是把舊版本的設定拿出來，當成最新的一版重新發布，所以會拿到一個新號碼，原本的號碼從歷史中消失。實測回滾前是 1、2、3，回滾後變成 1、3、4，版本 4 的備註就是原本版本 2 的「upgrade to nginx 1.31」。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>Deployment → ReplicaSet → Pod</strong>：Deployment 負責換版和回滾，ReplicaSet 負責維持數量；刪一個 Pod 實測 1 秒補回</li>

<li><strong>滾動更新的兩個數字</strong>：maxSurge（進位）、maxUnavailable（捨去），預設 25%；3 個副本時最多 4 個、至少 3 個可用，實測 <code>4 total | 3 available</code></li>

<li><strong>換錯版本不會掛站</strong>：新 Pod 卡 ImagePullBackOff，舊的 3 個照跑；<code>kubectl rollout undo</code> 一行回滾</li>

<li><strong>用 annotate 寫 change-cause</strong>：<code>--record</code> 已棄用；回滾會產生新的版本號</li>

<li><strong>檔案是最後的依據</strong>：指令臨時擴的數量，apply 檔案後會被蓋掉</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 9 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></li>

<li>上一篇：第 11 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a></li>

<li>下一篇：第 13 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2024/12/02/what-is-gitops-methodolity-what-is-gitops-process/">GitOps 是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2024/12/02/gke-what-is-helm-charts-what-is-oci-charts/">Helm Charts 是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">Deployment 讓 Pod 可以自己補位、自己換版，下一步就是讓使用者連得到這群 Pod。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Deployment 和 ReplicaSet 有什麼不同？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "ReplicaSet 只負責「保持剛好 N 個相同的 Pod」；Deployment 在它上面多了「換版本」和「回滾」。每換一次映像檔，Deployment 建一個新的 ReplicaSet，舊的縮成 0 個保留下來。實測換版後有兩個 ReplicaSet：舊的 `544b69cccb` 是 0 個、新的 `56649cb68c` 是 3 個。"
      }
    },
    {
      "@type": "Question",
      "name": "滾動更新會讓網站斷線嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "預設設定下，換版過程一直保持設定的數量可以用。實測 3 個副本換版時，最多 4 個、至少 3 個可用，8.8 秒換完。要做到使用者完全無感，還需要搭配 Service 分流量（第 13 篇）和健康檢查 Probe（第 17 篇），讓流量只送給真的準備好的 Pod。"
      }
    },
    {
      "@type": "Question",
      "name": "更新到一半失敗怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "先看 `kubectl get pods`，新 Pod 卡在 `ImagePullBackOff`、`CrashLoopBackOff` 這類狀態時，舊 Pod 通常還在服務。接著 `kubectl rollout undo deployment/名字` 回到上一版。實測換成不存在的 nginx:9.99，舊的 3 個 Pod 一直 Running，undo 之後馬上恢復。"
      }
    },
    {
      "@type": "Question",
      "name": "rollout history 的 CHANGE-CAUSE 是空的怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "這欄來自 Deployment 上的 `kubernetes.io/change-cause` 註記。每次換版後用 `kubectl annotate deployment 名字 kubernetes.io/change-cause='這次改了什麼' --overwrite` 寫一行說明就好。舊教學用的 `--record` 實測會跳出 `Flag --record has been deprecated` 警告，不建議再用。"
      }
    },
    {
      "@type": "Question",
      "name": "用 kubectl scale 還是改 YAML 檔？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "臨時調整可以用 `kubectl scale`，但下次有人 `kubectl apply -f` 檔案時，數量會被改回檔案寫的值。實測擴到 5 個後再 apply 檔案，就變回 3 個。要長期改就改檔案；要依流量自動調整，用 HPA。"
      }
    },
    {
      "@type": "Question",
      "name": "回滾後版本號為什麼跳號？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "回滾是把舊版本的設定拿出來，當成最新的一版重新發布，所以會拿到一個新號碼，原本的號碼從歷史中消失。實測回滾前是 1、2、3，回滾後變成 1、3、4，版本 4 的備註就是原本版本 2 的「upgrade to nginx 1.31」。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</title>
		<link>https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=minikube-tutorial-cloud-shell-kubectl-commands</link>
					<comments>https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:34:57 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13238</guid>

					<description><![CDATA[<p>Minikube 教學：不用安裝，在 Cloud Shell 免費開 K8s 叢集，實測 start 34.8 秒、stop 6.1 秒；比較 kind、k3s、GKE，kubectl 必學 10 個指令逐一實作。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Minikube 是在一台電腦開迷你 K8s 叢集的工具，Cloud Shell 已預裝，一行指令約 35 秒就能開始練習。</strong></p>



<p class="wp-block-paragraph">網路上的 Minikube 教學，第一步幾乎都是「先在你的電腦裝 Docker、裝 kubectl、裝 Minikube」，Windows、Mac、Linux 各一套步驟，很多人卡在安裝就放棄了。這篇完全不用安裝：打開瀏覽器裡的 Cloud Shell，三個工具都已經裝好。</p>



<p class="wp-block-paragraph">這篇會帶你做三件事：用 Minikube 開、關、刪一個叢集（實測開機 34.8 秒、關機 6.1 秒）；搞懂它跟 kind、k3s、GKE 差在哪；再用一個 nginx 網站把 <strong>kubectl 最常用的 10 個指令</strong>各跑一次。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 10 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1、kubectl v1.35.9）。叢集裡每個元件在做什麼，請先看第 9 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-01-local-k8s.png" alt="本機練習 K8s 的工具比較：Minikube 預裝在 Cloud Shell、kind 每個節點都是 Docker 容器、k3s 安裝腳本需要 systemd、GKE 是正式環境要付費" class="wp-image-13215" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-01-local-k8s.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-01-local-k8s-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-01-local-k8s-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-01-local-k8s-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>學 Kubernetes 一定要有一個叢集可以玩</strong>：只看文章、不動手，Pod、Service 這些名詞永遠是抽象的。正式的雲端叢集要錢，Minikube 不用</li>

<li><strong>kubectl 是 Kubernetes 的方向盤</strong>：不管叢集在 Minikube、GKE 還是公司機房，操作的指令都是 kubectl。在 Minikube 練熟，換到 GKE 一樣用</li>

<li><strong>證照是上機考</strong>：CKA、CKAD 考試時給你真的叢集，你要在 2 小時內用 kubectl 把題目做完（2026 年 11 月查 Linux Foundation 官方頁）。指令不熟，時間一定不夠</li>

<li><strong>面試會問你在哪裡練</strong>：能講出「我用 Minikube 練過 Deployment 擴展、port-forward 測服務」，比只說「我看過教學」有說服力</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Minikube 是什麼</h2>



<p class="wp-block-paragraph"><strong>Minikube 是一個在單一台電腦上建立 Kubernetes 叢集的工具</strong>，讓你不用準備好幾台伺服器，也能有一個功能完整、可以練習的叢集。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：正式的 Kubernetes 叢集像一間有很多廚房的連鎖餐廳；Minikube 是在你家廚房擺一套「家用版餐廳設備」，一個人就能練習整套點餐、出餐流程</li>

<li><strong>來龍去脈</strong>：名字就是 mini（迷你）＋kube（Kubernetes）。它是 Kubernetes 官方社群底下的專案（<a href="https://minikube.sigs.k8s.io/docs/">Minikube 官方文件</a>），目的是讓開發者在自己電腦上就能試 Kubernetes，不用先搞定一整套機房</li>

<li><strong>為什麼要學</strong>：本系列第 10～18 篇的 Pod、Deployment、Service、Ingress、自動擴展，全部在 Minikube 上做。學會開關叢集，後面每一篇都能自己重來</li>
</ul>



<p class="wp-block-paragraph">Minikube 官方建議的最低需求是 <strong>2 顆 CPU、2GB 可用記憶體、20GB 硬碟空間</strong>（<a href="https://minikube.sigs.k8s.io/docs/start/">Minikube 官方 Get Started</a>，2026 年 11 月查）。這篇實測的 test27 Cloud Shell 是 2 顆 CPU、7.8GiB 記憶體，剛好符合。</p>



<h3 class="wp-block-heading">驅動程式（driver）：Minikube 把節點放在哪裡</h3>



<p class="wp-block-paragraph"><strong>驅動程式是 Minikube 用來「做出一台節點」的方法</strong>。Minikube 本身不是一台機器，它要借用別的技術變出一台：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>驅動程式</th><th>節點長什麼樣</th><th>什麼時候用</th></tr></thead><tbody><tr><td><code>docker</code></td><td>一個 Docker 容器</td><td>電腦上已經有 Docker（Cloud Shell 就是）</td></tr><tr><td>VirtualBox、Hyper-V 等</td><td>一台虛擬機器（用軟體模擬的電腦）</td><td>Windows、Mac 沒有 Docker 時</td></tr><tr><td><code>none</code></td><td>直接裝在這台電腦上</td><td>進階用法，會改動系統，不建議新手</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Cloud Shell 裡跑 <code>minikube start</code> 會自動選 <code>docker</code>，輸出會寫 <code>Automatically selected the docker driver</code>。所以在 Cloud Shell，<strong>Minikube 的節點就是一個 Docker 容器</strong>，你的 Pod 再跑在這個容器裡面。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Minikube、kind、k3s、GKE 差在哪</h2>



<p class="wp-block-paragraph">想在自己電腦練 Kubernetes，常聽到的工具有三個，再加上雲端的 GKE：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>工具</th><th>是什麼</th><th>節點</th><th>適合</th><th>在 Cloud Shell</th></tr></thead><tbody><tr><td><strong>Minikube</strong></td><td>官方社群的本機叢集工具</td><td>一個容器或虛擬機器</td><td>學習、本機開發，外掛多</td><td>預裝，本系列用它</td></tr><tr><td><strong>kind</strong></td><td>Kubernetes IN Docker 的縮寫</td><td>每個節點都是 Docker 容器</td><td>測試 Kubernetes 本身、CI 自動化測試</td><td>test27 這台有（<code>/google/gopath/bin/kind</code>）</td></tr><tr><td><strong>k3s</strong></td><td>精簡版 Kubernetes，整包是一個執行檔</td><td>真的機器或虛擬機器</td><td>邊緣設備、小主機、樹莓派</td><td>安裝腳本要 systemd，Cloud Shell 沒有</td></tr><tr><td><strong>GKE</strong></td><td>Google Cloud 代管的 Kubernetes</td><td>雲端的虛擬機器</td><td>正式環境</td><td>要 GCP 專案、要付費</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">幾個名詞順手解釋：</p>


<ul class="wp-block-list">
<li><strong>CI（Continuous Integration，持續整合）</strong>：程式一改就自動跑測試的流程。kind 開叢集快、用完即丟，很適合放在這種自動化流程裡（<a href="https://kind.sigs.k8s.io/">kind 官方文件</a>）</li>

<li><strong>systemd</strong>：Linux 系統裡負責「開機時把各種服務叫起來、掛了自動重開」的管理員。k3s 的官方安裝腳本會把它註冊成 systemd 服務（<a href="https://docs.k3s.io/">k3s 官方文件</a>），而 Cloud Shell 是容器化的環境，沒有 systemd，所以裝不起來</li>

<li><strong>邊緣設備</strong>：放在工廠、商店、基地台這類「離資料中心很遠」的小電腦</li>
</ul>



<p class="wp-block-paragraph"><strong>本系列選 Minikube 的原因</strong>：Cloud Shell 預裝、Google 已經幫它設好環境變數（輸出裡的 <code>MINIKUBE_HOME=/google/minikube</code>）、有 ingress 和 metrics-server 外掛可以直接開，第 14、17 篇都會用到。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">kubectl 是什麼</h2>



<p class="wp-block-paragraph"><strong>kubectl 是跟 Kubernetes 叢集講話的指令工具</strong>。你打的每一個 kubectl 指令，都會變成一個 HTTPS 請求，送到叢集的 API 伺服器。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：電視遙控器。電視（叢集）在哪裡、是什麼牌子都沒關係，按鈕的用法都一樣</li>

<li><strong>來龍去脈</strong>：kube（Kubernetes）＋ctl（control，控制）。唸法沒有標準，有人唸「kube control」、有人唸「kube C T L」、有人唸「kube cuddle」</li>

<li><strong>為什麼要學</strong>：Kubernetes 幾乎所有操作都靠它；GKE 的網頁主控台能做的事，kubectl 都能做，而且考試只能用它</li>
</ul>



<h3 class="wp-block-heading">kubectl 指令的文法</h3>



<p class="wp-block-paragraph">kubectl 的指令幾乎都長這樣：</p>



<pre class="wp-block-code"><code>kubectl 動詞 資源類型 名字 選項</code></pre>



<p class="wp-block-paragraph">例如 <code>kubectl get pods -o wide</code> 就是「列出（get）所有 Pod（pods），用寬格式（-o wide）顯示」；<code>kubectl delete deployment hello</code> 是「刪除（delete）叫 hello 的 Deployment」。記住這個順序，新指令看一眼就懂。</p>



<h3 class="wp-block-heading">context：kubectl 現在連的是哪個叢集</h3>



<p class="wp-block-paragraph"><strong>context（情境）是 kubectl 記住「現在要連哪個叢集、用誰的身分、預設在哪個命名空間」的一組設定</strong>。這些設定存在家目錄的 <code>~/.kube/config</code> 檔案裡，叫 kubeconfig。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：遙控器上的「切換電視」按鈕。家裡有客廳和臥室兩台電視，按錯台就會關錯電視</li>

<li><strong>為什麼要學</strong>：工作上常常同時有測試和正式兩個叢集，<strong>連錯 context 就會在正式環境刪東西</strong>。下指令前先確認 context 是好習慣</li>
</ul>



<p class="wp-block-paragraph"><code>minikube start</code> 做完會自動把 context 切到 minikube，輸出最後一行就寫 <code>kubectl is now configured to use "minikube" cluster</code>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：開一個叢集，把 kubectl 10 個指令跑一次</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>；如果跳出「授權 Cloud Shell」，這篇用不到 gcloud，按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<h3 class="wp-block-heading">步驟 1：確認工具和機器規格</h3>



<pre class="wp-block-code"><code>which minikube kubectl kind k3s; nproc; free -h | head -2</code></pre>



<pre class="wp-block-code"><code>/usr/bin/minikube
/usr/bin/kubectl
/google/gopath/bin/kind
2
               total        used        free      shared  buff/cache   available
Mem:           7.8Gi       1.8Gi       3.3Gi       1.1Mi       2.9Gi       5.9Gi</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="354" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools.png" alt="Cloud Shell 裡有 minikube、kubectl、kind，沒有 k3s；2 顆 CPU、7.8Gi 記憶體" class="wp-image-13216" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools-300x66.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools-1024x227.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools-768x170.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-01-tools-1536x340.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>which</code> 是「這個指令裝在哪裡」：minikube、kubectl、kind 都找得到，k3s 沒有（沒有印出來）</li>

<li><code>nproc</code> 是 CPU 核心數：<strong>2 顆</strong></li>

<li><code>free -h</code> 是記憶體：總共 <strong>7.8Gi</strong>，目前可用（available）5.9Gi</li>
</ul>



<p class="wp-block-paragraph">Minikube 最低要 2 顆 CPU，這台剛好夠。不同帳號的 Cloud Shell 規格可能不一樣，以你自己跑出來的為準。</p>



<h3 class="wp-block-heading">步驟 2：看 Docker 用了多少空間</h3>



<p class="wp-block-paragraph">Minikube 的節點是 Docker 容器，先看 Docker 現在佔了多少：</p>



<pre class="wp-block-code"><code>docker system df</code></pre>



<pre class="wp-block-code"><code>TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          1         0         1.936GB   1.936GB (100%)
Containers      0         0         0B        0B
Local Volumes   0         0         0B        0B
Build Cache     0         0         0B        0B</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1484" height="390" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-02-docker-df.png" alt="docker system df 顯示只有 1 個映像檔、1.936GB，沒有容器、Volume 和建置快取" class="wp-image-13217" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-02-docker-df.png 1484w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-02-docker-df-300x79.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-02-docker-df-1024x269.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-02-docker-df-768x202.png 768w" sizes="(max-width: 1484px) 100vw, 1484px" /></figure>



<p class="wp-block-paragraph">這台只有 1 個映像檔、1.936GB，沒有容器在跑。<code>RECLAIMABLE</code> 是「可以清掉的空間」，100% 代表這個映像檔目前沒有被任何容器用。</p>



<h3 class="wp-block-heading">步驟 3：開叢集，順便計時</h3>



<p class="wp-block-paragraph"><code>time</code> 放在指令前面，跑完會多印出花了幾秒：</p>



<pre class="wp-block-code"><code>time minikube start</code></pre>



<pre class="wp-block-code"><code>😄  minikube v1.38.1 on Ubuntu 24.04 (amd64)
    ▪ MINIKUBE_FORCE_SYSTEMD=true
    ▪ MINIKUBE_HOME=/google/minikube
    ▪ MINIKUBE_WANTUPDATENOTIFICATION=false
✨  Automatically selected the docker driver. Other choices: ssh, none
❗  Starting v1.39.0, minikube will default to "containerd" container runtime. See #21973 for more info.
📌  Using Docker driver with root privileges
👍  Starting "minikube" primary control-plane node in "minikube" cluster
🚜  Pulling base image v0.0.50 ...
🔥  Creating docker container (CPUs=2, Memory=3072MB) ...
🧯  Docker is nearly out of disk space, which may cause deployments to fail! (95% of capacity). You can pass '--force' to skip this check.
（中間省略：清理硬碟的建議）
🐳  Preparing Kubernetes v1.35.1 on Docker 29.2.1 ...
    ▪ kubelet.cgroups-per-qos=false
    ▪ kubelet.enforce-node-allocatable=""
🔗  Configuring bridge CNI (Container Networking Interface) ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

real    0m34.847s
user    0m2.551s
sys     0m1.958s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="827" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start.png" alt="time minikube start 的輸出：自動選 docker 驅動程式、建立 2 CPU 3072MB 的節點容器、Kubernetes v1.35.1，real 0m34.847s" class="wp-image-13218" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start-300x155.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start-1024x529.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start-768x397.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-03-start-1536x794.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>real 0m34.847s</code>：從按 Enter 到完成，<strong>34.8 秒</strong>。這台之前開過 Minikube，要下載的東西已經存在 <code>/google/minikube</code> 裡；<strong>第一次開要多下載約 792 MiB</strong>（272.45 MiB 的 Kubernetes 映像檔包＋519.58 MiB 的節點映像檔），會再久一點</li>

<li><code>CPUs=2, Memory=3072MB</code>：Minikube 自動幫節點設的上限是 2 顆 CPU、3072MB（3GB）記憶體。這是「最多可以用多少」，不是把資源整個鎖住</li>

<li><code>Docker is nearly out of disk space</code>：只是警告，叢集照樣建好了，下面「實測時的意外」會說明</li>

<li><code>Starting v1.39.0 ... containerd</code>：Minikube 新版會換預設的容器執行環境，下面「新舊對照」會說明</li>
</ul>



<p class="wp-block-paragraph"><strong>算一次記憶體</strong>：這台總共 7.8Gi，Minikube 節點最多吃 3GB，剩下約 4.8Gi 給 Cloud Shell 自己和其他程式用。如果你的 Cloud Shell 記憶體比較小，可以用 <code>minikube start --memory=2048</code> 把上限調低，但不要低於官方建議的 2GB。</p>



<h3 class="wp-block-heading">步驟 4：看叢集狀態</h3>



<pre class="wp-block-code"><code>minikube status</code></pre>



<pre class="wp-block-code"><code>minikube
type: Control Plane
host: Running
kubelet: Running
apiserver: Running
kubeconfig: Configured</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="583" height="482" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-04-status.png" alt="minikube status 顯示 host、kubelet、apiserver 都是 Running，kubeconfig 是 Configured" class="wp-image-13219" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-04-status.png 583w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-04-status-300x248.png 300w" sizes="(max-width: 583px) 100vw, 583px" /></figure>



<p class="wp-block-paragraph">四行分別是：節點容器（host）有在跑、節點上的 kubelet 有在跑、控制平面的 API 伺服器有在跑、kubectl 的設定檔已經指向這個叢集。四個都正常，叢集才能用。</p>



<h3 class="wp-block-heading">步驟 5：確認 kubectl 連的是哪個叢集</h3>



<pre class="wp-block-code"><code>kubectl config get-contexts; kubectl get nodes</code></pre>



<pre class="wp-block-code"><code>CURRENT   NAME       CLUSTER    AUTHINFO   NAMESPACE
*         minikube   minikube   minikube   default
NAME       STATUS   ROLES           AGE   VERSION
minikube   Ready    control-plane   16s   v1.35.1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1301" height="344" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-05-context.png" alt="kubectl config get-contexts 顯示目前的 context 是 minikube，kubectl get nodes 顯示一個 Ready 的節點" class="wp-image-13220" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-05-context.png 1301w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-05-context-300x79.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-05-context-1024x271.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-05-context-768x203.png 768w" sizes="(max-width: 1301px) 100vw, 1301px" /></figure>



<p class="wp-block-paragraph"><code>CURRENT</code> 那欄的 <code>*</code> 代表「現在用的是這個」。只有一個 context 叫 minikube，預設命名空間（NAMESPACE）是 <code>default</code>。<strong>命名空間是叢集裡的資料夾</strong>，沒特別指定時，你建的東西都放在 <code>default</code>。</p>



<h3 class="wp-block-heading">步驟 6：看 Minikube 有哪些外掛</h3>



<p class="wp-block-paragraph"><strong>外掛（addon）是 Minikube 內建、一個指令就能打開的額外功能</strong>，例如網址路由（ingress）、資源監控（metrics-server）、網頁儀表板（dashboard）。</p>



<pre class="wp-block-code"><code>minikube addons list | grep -c disabled; minikube addons list | grep -E 'ADDON NAME|enabled'</code></pre>



<pre class="wp-block-code"><code>37
│         ADDON NAME          │ PROFILE  │   STATUS   │               MAINTAINER               │
│ default-storageclass        │ minikube │ enabled ✅ │ Kubernetes                             │
│ storage-provisioner         │ minikube │ enabled ✅ │ minikube                               │</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="234" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons.png" alt="minikube addons list 顯示 37 個外掛關閉、預設開啟 default-storageclass 和 storage-provisioner 兩個" class="wp-image-13221" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons-300x44.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons-1024x150.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons-768x112.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-06-addons-1536x225.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>grep -c disabled</code> 是數「關閉的有幾個」：<strong>37 個</strong>；預設打開的只有 2 個，加起來這版 Minikube 有 39 個外掛。預設開的兩個是「自動幫你準備硬碟空間」用的，<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">第 16 篇</a>講資料保存時會用到。要開別的外掛，用 <code>minikube addons enable 外掛名</code>，<a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">第 14 篇</a>會開 ingress。</p>



<h3 class="wp-block-heading">步驟 7：kubectl 指令 1，create：建一個網站</h3>



<pre class="wp-block-code"><code>kubectl create deployment hello --image=nginx --replicas=2; sleep 20; kubectl get pods -o wide</code></pre>



<pre class="wp-block-code"><code>deployment.apps/hello created
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
hello-9ff96cc5-2lbwc   1/1     Running   0          20s   10.244.0.4   minikube   &lt;none&gt;           &lt;none&gt;
hello-9ff96cc5-sdxmc   1/1     Running   0          20s   10.244.0.3   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="197" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create.png" alt="kubectl create deployment hello 建立 2 個 nginx Pod，都在 minikube 節點上 Running" class="wp-image-13222" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create-300x37.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create-1024x126.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create-768x95.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-07-create-1536x189.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>create deployment</code> 是用一行指令建 Deployment（幫你維持 Pod 數量的設定，<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">第 12 篇</a>細講），<code>--replicas=2</code> 是要 2 份。<code>sleep 20</code> 是等 20 秒讓映像檔下載完。</p>



<h3 class="wp-block-heading">步驟 8：kubectl 指令 2，get：列出東西</h3>



<pre class="wp-block-code"><code>kubectl get deployment,replicaset,pod</code></pre>



<pre class="wp-block-code"><code>NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/hello   2/2     2            2           27s

NAME                             DESIRED   CURRENT   READY   AGE
replicaset.apps/hello-9ff96cc5   2         2         2       27s

NAME                       READY   STATUS    RESTARTS   AGE
pod/hello-9ff96cc5-2lbwc   1/1     Running   0          27s
pod/hello-9ff96cc5-sdxmc   1/1     Running   0          27s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1589" height="574" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all.png" alt="kubectl get deployment,replicaset,pod 一次列出 hello 的 Deployment、ReplicaSet 和 2 個 Pod" class="wp-image-13223" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all.png 1589w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all-300x108.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all-1024x370.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all-768x277.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-08-get-all-1536x555.png 1536w" sizes="(max-width: 1589px) 100vw, 1589px" /></figure>



<p class="wp-block-paragraph"><code>get</code> 後面可以用逗號一次列好幾種資源。這裡看得到三層關係：1 個 Deployment 管 1 個 ReplicaSet，ReplicaSet 管 2 個 Pod。<code>DESIRED 2</code>（想要 2 個）、<code>CURRENT 2</code>（現在 2 個）、<code>READY 2</code>（準備好 2 個），三個數字一樣就代表健康。</p>



<h3 class="wp-block-heading">步驟 9：kubectl 指令 3，describe：看詳細資料和事件</h3>



<p class="wp-block-paragraph">先把第一個 Pod 的名字存進變數 <code>P</code>，後面幾步都用它：</p>



<pre class="wp-block-code"><code>P=$(kubectl get pods -l app=hello -o jsonpath='{.items[0].metadata.name}'); echo $P; kubectl describe pod $P | tail -12</code></pre>



<pre class="wp-block-code"><code>hello-9ff96cc5-2lbwc
QoS Class:                   BestEffort
Node-Selectors:              &lt;none&gt;
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  33s   default-scheduler  Successfully assigned default/hello-9ff96cc5-2lbwc to minikube
  Normal  Pulling    33s   kubelet            spec.containers{nginx}: Pulling image "nginx"
  Normal  Pulled     25s   kubelet            spec.containers{nginx}: Successfully pulled image "nginx" in 1.494s (7.829s including waiting). Image size: 163294089 bytes.
  Normal  Created    25s   kubelet            spec.containers{nginx}: Container created
  Normal  Started    25s   kubelet            spec.containers{nginx}: Container started</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="379" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe.png" alt="kubectl describe pod 最下面的 Events，From 欄寫著 default-scheduler 和 kubelet" class="wp-image-13224" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe-300x71.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe-1024x243.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe-768x182.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-09-describe-1536x364.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>變數</strong>是「幫一段文字取名字」，<code>P=...</code> 存起來，之後打 <code>$P</code> 就等於那個 Pod 名字，不用每次複製貼上。<code>-l app=hello</code> 是用標籤挑 Pod，<code>-o jsonpath=...</code> 是只取第一個的名字</li>

<li><code>describe</code> 會印很長一段，<code>tail -12</code> 只看最後 12 行，也就是 <strong>Events（事件）</strong></li>

<li><strong>排錯時最常看的就是 Events</strong>：<code>From</code> 那欄寫是誰做的，<code>default-scheduler</code> 挑節點、<code>kubelet</code> 拉映像檔和啟動容器</li>
</ul>



<p class="wp-block-paragraph"><code>Pulled</code> 那行有兩個時間：真正下載 1.494 秒，加上排隊等待一共 7.829 秒。因為 2 個 Pod 同時要拉同一個映像檔，第二個要等第一個下載完。</p>



<h3 class="wp-block-heading">步驟 10：kubectl 指令 4，logs：看容器印出來的訊息</h3>



<pre class="wp-block-code"><code>kubectl logs $P --tail=5</code></pre>



<pre class="wp-block-code"><code>2026/11/20 14:58:59 [notice] 1#1: OS: Linux 6.18.55+
2026/11/20 14:58:59 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2026/11/20 14:58:59 [notice] 1#1: start worker processes
2026/11/20 14:58:59 [notice] 1#1: start worker process 29
2026/11/20 14:58:59 [notice] 1#1: start worker process 30</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="337" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs.png" alt="kubectl logs 顯示 nginx 啟動時印出的最後 5 行訊息" class="wp-image-13225" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs-300x63.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs-1024x216.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs-768x162.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-10-logs-1536x324.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>日誌（log）是程式執行時印出來的紀錄</strong>。<code>logs</code> 等於 Docker 的 <code>docker logs</code>（<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">第 2 篇</a>），<code>--tail=5</code> 只看最後 5 行。nginx 開了 2 個工作程序（worker process 29、30），對應這個節點的 2 顆 CPU。時間是 UTC（世界標準時間），台灣時間要加 8 小時，也就是 22:58。</p>



<h3 class="wp-block-heading">步驟 11：kubectl 指令 5，exec：在容器裡執行指令</h3>



<pre class="wp-block-code"><code>kubectl exec $P -- nginx -v; kubectl exec $P -- head -2 /etc/os-release</code></pre>



<pre class="wp-block-code"><code>nginx version: nginx/1.31.9
PRETTY_NAME="Debian GNU/Linux 13 (trixie)"
NAME="Debian GNU/Linux"</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="261" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec.png" alt="kubectl exec 在 Pod 裡執行 nginx -v 和讀 /etc/os-release，顯示 nginx 1.31.9、Debian 13" class="wp-image-13226" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec-1024x167.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec-768x125.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-11-exec-1536x251.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>--</code> 後面就是「要在容器裡跑的指令」。這次的 nginx 映像檔是 <strong>nginx 1.31.9、底層是 Debian 13</strong>。想直接進去容器打指令，可以用 <code>kubectl exec -it $P -- bash</code>，跟 <code>docker exec -it</code> 一樣，打 <code>exit</code> 離開。</p>



<h3 class="wp-block-heading">步驟 12：kubectl 指令 6，expose：幫網站開一個固定入口</h3>



<p class="wp-block-paragraph">Pod 的 IP 會變（Pod 重建就換一個），所以要用 <strong>Service（服務）</strong> 給它一個固定的入口。<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">第 13 篇</a>會細講三種 Service，這裡先開最基本的：</p>



<pre class="wp-block-code"><code>kubectl expose deployment hello --port=80; kubectl get service hello</code></pre>



<pre class="wp-block-code"><code>service/hello exposed
NAME    TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
hello   ClusterIP   10.97.239.94   &lt;none&gt;        80/TCP    0s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="271" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose.png" alt="kubectl expose 幫 hello 開一個 ClusterIP 類型的 Service，IP 是 10.97.239.94、Port 80" class="wp-image-13227" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose-300x51.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose-1024x173.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose-768x130.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-12-expose-1536x260.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>TYPE ClusterIP</code> 是「只有叢集裡面連得到」的類型，IP 是 <code>10.97.239.94</code>、Port 是 80（Port 是同一台機器上不同服務的分機號碼，網頁預設用 80）。<code>EXTERNAL-IP &lt;none&gt;</code> 代表外面連不進來。</p>



<h3 class="wp-block-heading">步驟 13：kubectl 指令 7，port-forward：把叢集裡的服務接到 Cloud Shell</h3>



<p class="wp-block-paragraph">叢集外面要怎麼測這個網站？用 <code>port-forward</code> 開一條暫時的通道：</p>



<pre class="wp-block-code"><code>kubectl port-forward svc/hello 8080:80 &gt;/dev/null 2&gt;&amp;1 &amp; sleep 3; curl -s localhost:8080 | grep -i title</code></pre>



<pre class="wp-block-code"><code>[1] 13041
&lt;title&gt;Welcome to nginx!&lt;/title&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="154" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward.png" alt="kubectl port-forward 在背景執行，curl localhost:8080 拿到 Welcome to nginx! 的網頁標題" class="wp-image-13228" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward-300x29.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward-1024x99.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward-768x74.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-13-port-forward-1536x148.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>8080:80</code> 是「Cloud Shell 的 8080 接到 Service 的 80」</li>

<li>最後的 <code>&amp;</code> 是<strong>放到背景執行</strong>，這樣終端機不會被它佔住；<code>[1] 13041</code> 是背景工作的編號和程序編號</li>

<li><code>&gt;/dev/null 2&gt;&amp;1</code> 是把它的訊息丟掉，畫面比較乾淨</li>

<li><code>curl -s localhost:8080</code> 打開網頁，<code>grep -i title</code> 只看標題：<code>Welcome to nginx!</code>，網站通了</li>
</ul>



<p class="wp-block-paragraph">想用瀏覽器看，按 Cloud Shell 右上角的「網頁預覽」，選「透過以下通訊埠預覽：8080」，跟<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇</a>看 nginx 網頁的做法一樣。</p>



<h3 class="wp-block-heading">步驟 14：kubectl 指令 8，scale：調整 Pod 數量</h3>



<pre class="wp-block-code"><code>kubectl scale deployment hello --replicas=4; sleep 8; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>deployment.apps/hello scaled
NAME                   READY   STATUS    RESTARTS   AGE
hello-9ff96cc5-2lbwc   1/1     Running   0          73s
hello-9ff96cc5-6nkwz   1/1     Running   0          8s
hello-9ff96cc5-dzbf5   1/1     Running   0          8s
hello-9ff96cc5-sdxmc   1/1     Running   0          73s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="387" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale.png" alt="kubectl scale 把 hello 從 2 個 Pod 擴成 4 個，新的 2 個 AGE 8 秒" class="wp-image-13229" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale-300x73.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale-1024x248.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale-768x186.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-14-scale-1536x372.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">從 2 個變 4 個：原本的 2 個 <code>AGE 73s</code>，新的 2 個 <code>AGE 8s</code>，8 秒內就是 <code>Running</code>，因為映像檔已經在節點上，不用重新下載。</p>



<h3 class="wp-block-heading">步驟 15：用 -o yaml 看 Kubernetes 存了什麼</h3>



<p class="wp-block-paragraph">這篇到目前為止都是用指令建的，但 Kubernetes 真正存的是一份 YAML 設定（YAML 是用縮排表示層次的設定檔格式）。加 <code>-o yaml</code> 就能看到：</p>



<pre class="wp-block-code"><code>kubectl get deployment hello -o yaml | head -45</code></pre>



<pre class="wp-block-code"><code>（前面省略：apiVersion、kind、metadata 開頭幾行）
  labels:
    app: hello
  name: hello
  namespace: default
  resourceVersion: "562"
  uid: 8753627a-2b7c-4e10-9398-5874926dcb7d
spec:
  progressDeadlineSeconds: 600
  replicas: 4
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: hello
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: hello
    spec:
      containers:
      - image: nginx
        imagePullPolicy: Always
        name: nginx
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 4
  conditions:</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="876" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml.png" alt="kubectl get deployment hello -o yaml 顯示 spec.replicas 是 4、容器映像檔是 nginx" class="wp-image-13230" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml-300x164.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml-1024x561.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml-768x420.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-15-yaml-1536x841.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">重點看兩塊：<code>spec</code>（規格）是<strong>你想要的樣子</strong>，<code>replicas: 4</code> 就是步驟 14 用 scale 改的；<code>status</code>（狀態）是<strong>現在實際的樣子</strong>，<code>availableReplicas: 4</code>。Kubernetes 一直在做的事，就是讓 status 追上 spec。</p>



<p class="wp-block-paragraph">這也是 <code>kubectl apply -f 檔名</code> 的由來：與其每次打指令，不如把 spec 寫成 YAML 檔，用 <code>apply</code> 交給叢集，檔案就是紀錄。第 11 篇開始會改用這種寫法。</p>



<h3 class="wp-block-heading">步驟 16：kubectl explain：忘記欄位怎麼寫時查這個</h3>



<pre class="wp-block-code"><code>kubectl explain deployment.spec.replicas</code></pre>



<pre class="wp-block-code"><code>GROUP:      apps
KIND:       Deployment
VERSION:    v1

FIELD: replicas &lt;integer&gt;

DESCRIPTION:
    Number of desired pods. This is a pointer to distinguish between explicit
    zero and not specified. Defaults to 1.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="599" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain.png" alt="kubectl explain deployment.spec.replicas 說明 replicas 是整數、代表想要的 Pod 數量、預設 1" class="wp-image-13231" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain-300x112.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain-1024x383.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain-768x288.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-16-explain-1536x575.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>explain</code> 是 kubectl 內建的說明書：<code>replicas</code> 是整數（integer），代表想要幾個 Pod，<strong>沒寫的話預設 1</strong>。寫 YAML 忘記欄位名稱時，不用上網查，直接 explain。</p>



<h3 class="wp-block-heading">步驟 17：minikube stop，關機但資料留著</h3>



<p class="wp-block-paragraph">先把背景的 port-forward 關掉（<code>kill %1</code> 是結束第 1 個背景工作），再關叢集：</p>



<pre class="wp-block-code"><code>kill %1; time minikube stop; minikube status</code></pre>



<pre class="wp-block-code"><code>✋  Stopping node "minikube"  ...
🛑  Powering off "minikube" via SSH ...
🛑  1 node stopped.
[1]+  Terminated              kubectl port-forward svc/hello 8080:80 &gt; /dev/null 2&gt;&amp;1

real    0m6.128s
user    0m0.228s
sys     0m0.159s
minikube
type: Control Plane
host: Stopped
kubelet: Stopped
apiserver: Stopped
kubeconfig: Stopped</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="650" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop.png" alt="minikube stop 花 6.1 秒關掉節點，minikube status 全部變成 Stopped" class="wp-image-13232" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop-300x122.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop-1024x416.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop-768x312.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-17-stop-1536x624.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">關機 <strong>6.1 秒</strong>，status 四行都變成 <code>Stopped</code>。這時節點容器停了，但裡面的資料（etcd 裡的 Deployment、Service）都還在。</p>



<h3 class="wp-block-heading">步驟 18：再開一次，Deployment 都還在</h3>



<pre class="wp-block-code"><code>time minikube start | tail -3; kubectl get deployment,service</code></pre>



<pre class="wp-block-code"><code>（前面省略：硬碟空間警告）
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟  Enabled addons: default-storageclass, storage-provisioner
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

real    0m13.458s
user    0m0.844s
sys     0m0.533s
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/hello   4/4     4            4           116s

NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/hello        ClusterIP   10.97.239.94   &lt;none&gt;        80/TCP    66s
service/kubernetes   ClusterIP   10.96.0.1      &lt;none&gt;        443/TCP   2m23s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="584" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart.png" alt="重新 minikube start 只花 13.5 秒，hello 的 Deployment 4/4 和 Service 都還在" class="wp-image-13233" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart-300x110.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart-1024x374.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart-768x280.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-18-restart-1536x561.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">從停止狀態重開只要 <strong>13.5 秒</strong>，比新建（34.8 秒）快一半以上，而且 <code>hello</code> 的 Deployment 還是 4/4、Service 的 IP 也沒變。</p>



<p class="wp-block-paragraph"><code>service/kubernetes</code> 是叢集內建的 Service，讓叢集裡的程式可以找到 API 伺服器（443 是 HTTPS 的預設 Port），不要刪它。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-03-lifecycle.png" alt="minikube start、stop、delete 的差別：start 34.8 秒、stop 6.1 秒且資料留著、delete 全部刪除" class="wp-image-13234" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-03-lifecycle.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-03-lifecycle-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-03-lifecycle-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-03-lifecycle-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">步驟 19：kubectl 指令 9，delete：刪掉不要的東西</h3>



<pre class="wp-block-code"><code>kubectl delete service hello; kubectl delete deployment hello; kubectl get all</code></pre>



<pre class="wp-block-code"><code>service "hello" deleted from default namespace
deployment.apps "hello" deleted from default namespace
NAME                       READY   STATUS        RESTARTS      AGE
pod/hello-9ff96cc5-2lbwc   1/1     Terminating   1 (36s ago)   2m7s
pod/hello-9ff96cc5-6nkwz   1/1     Terminating   1 (36s ago)   62s
pod/hello-9ff96cc5-dzbf5   1/1     Terminating   1 (36s ago)   62s
pod/hello-9ff96cc5-sdxmc   1/1     Terminating   1 (36s ago)   2m7s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    &lt;none&gt;        443/TCP   2m34s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="497" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete.png" alt="kubectl delete 刪掉 hello 的 Service 和 Deployment，4 個 Pod 狀態變成 Terminating" class="wp-image-13235" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete-300x93.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete-1024x318.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete-768x239.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-19-delete-1536x477.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪掉 Deployment，底下的 ReplicaSet 和 Pod 會跟著被刪，Pod 狀態先變成 <code>Terminating</code>（結束中），幾秒後就消失。<strong>刪 Pod 會被補回來，刪 Deployment 才是真的不要了</strong>。</p>



<p class="wp-block-paragraph"><code>RESTARTS 1 (36s ago)</code> 是因為步驟 17、18 把整個節點關機又開機，裡面的容器都重開過一次，下面「實測時的意外」會說明。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-02-kubectl-10.png" alt="kubectl 必學 10 個指令：get、describe、create、apply -f、logs、exec、expose、port-forward、scale、delete" class="wp-image-13236" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-02-kubectl-10.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-02-kubectl-10-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-02-kubectl-10-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-cards-02-kubectl-10-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">新舊對照：Minikube 1.39 起預設改用 containerd</h2>



<p class="wp-block-paragraph"><code>minikube start</code> 每次都會印這行：<code>Starting v1.39.0, minikube will default to "containerd" container runtime</code>。</p>



<p class="wp-block-paragraph">查了 Minikube 官方發布頁，<strong>v1.39.0 已經在 2026 年 9 月 1 日發布</strong>，預設的 Kubernetes 版本是 v1.37.0，預設的容器執行環境改成 containerd（<a href="https://github.com/kubernetes/minikube/releases">Minikube Releases</a>，2026 年 11 月查）。Cloud Shell 預裝的還是 v1.38.1，所以這篇看到的是舊預設：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Cloud Shell 預裝（v1.38.1）</th><th>Minikube 最新版（v1.39.0）</th></tr></thead><tbody><tr><td>預設 Kubernetes</td><td>v1.35.1</td><td>v1.37.0</td></tr><tr><td>預設容器執行環境</td><td>Docker（<code>Preparing Kubernetes v1.35.1 on Docker 29.2.1</code>）</td><td>containerd</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">對讀者的影響很小：你建的 Pod、Deployment、Service 寫法都一樣。差別在 <code>minikube ssh</code> 進節點以後，舊版可以用 <code>docker ps</code> 看容器，containerd 版要改用 <code>crictl ps</code>。哪天 Cloud Shell 升級了，輸出裡的 <code>on Docker</code> 會變成 <code>on containerd</code>，不用緊張。</p>



<p class="wp-block-paragraph"><strong>containerd 是什麼？</strong> containerd 是一個專門負責「跑容器」的軟體，原本是 Docker 裡面的一個零件，後來獨立出來，現在是 Kubernetes 最常用的容器執行環境。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. 這台 Cloud Shell 只有 2 顆 CPU</h3>



<p class="wp-block-paragraph">之前用另一個帳號的 Cloud Shell 測，是 4 顆 CPU、15GiB 記憶體；這次 test27 這台只有 <strong>2 顆 CPU、7.8GiB</strong>。Cloud Shell 給的規格不一定每個人一樣，所以這篇在步驟 1 先查一次。2 顆 CPU 剛好是 Minikube 的最低需求，跑本系列的練習夠用，但同時開很多 Pod 會比較慢。</p>



<h3 class="wp-block-heading">2. 只有 1 個映像檔，還是說硬碟快滿了</h3>



<p class="wp-block-paragraph"><code>docker system df</code> 只有 1 個 1.936GB 的映像檔，<code>minikube start</code> 卻還是警告 <code>Docker is nearly out of disk space ... (95% of capacity)</code>。代表 Cloud Shell 給 Docker 的系統空間本來就小，不是你放了太多東西。這只是警告，叢集照樣建好、網站照樣跑；真的建失敗才需要 <code>docker system prune -a</code> 清理（它會先問你確定才刪）。</p>



<h3 class="wp-block-heading">3. stop 再 start，Pod 會重開一次</h3>



<p class="wp-block-paragraph">步驟 19 看到每個 Pod 都是 <code>RESTARTS 1</code>。原因是 <code>minikube stop</code> 把整個節點關機，裡面的容器當然也停了；開機後 kubelet 照著帳本把它們重新跑起來，所以重啟次數加 1。Deployment、Service 的設定都還在，只是容器是新開的，<strong>容器裡沒有存到 Volume 的資料會不見</strong>（第 16 篇會講怎麼保存）。</p>



<h3 class="wp-block-heading">4. 開關時間每次不一樣</h3>



<p class="wp-block-paragraph">寫完這篇後，同一台 Cloud Shell 又完整跑了一次同樣的步驟：新建 35.4 秒（第一次 34.8 秒）、重開 14.6 秒（第一次 13.5 秒），差不多；但 <code>minikube stop</code> 從 6.1 秒變成 <strong>16.2 秒</strong>。原因沒查到，可能跟當下機器的負載有關，文中的秒數當參考就好。</p>



<h3 class="wp-block-heading">5. 之後的篇目開叢集要加 &#8211;cni=kindnet</h3>



<p class="wp-block-paragraph">這篇的操作都正常，但寫到第 13 篇 Service 時發現：在 Cloud Shell 用預設的 <code>minikube start</code>，<strong>Pod 連 Service 會不通、叢集內的 DNS 也查不到名字</strong>。原因是 Cloud Shell 的系統核心沒有 <code>br_netfilter</code> 模組，Minikube 預設的 bridge 網路外掛需要它。解法是開叢集時改用 <code>minikube start --cni=kindnet</code>，本系列第 13 篇以後都這樣開，詳細過程寫在第 13 篇的「實測時的意外」。</p>



<h3 class="wp-block-heading">6. 事件訊息多了「spec.containers{nginx}:」</h3>



<p class="wp-block-paragraph">步驟 9 的 Events，kubelet 寫的訊息前面多了 <code>spec.containers{nginx}:</code>，標出是 Pod 裡哪一個容器的事件。網路上舊教學的截圖沒有這段，看到不用以為是錯誤。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<pre class="wp-block-code"><code>minikube delete; minikube status</code></pre>



<pre class="wp-block-code"><code>🔥  Deleting "minikube" in docker ...
🔥  Deleting container "minikube" ...
🔥  Removing /google/minikube/.minikube/machines/minikube ...
💀  Removed all traces of the "minikube" cluster.
🤷  Profile "minikube" not found. Run "minikube profile list" to view all profiles.
👉  To start a cluster, run: "minikube start"</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="346" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup.png" alt="minikube delete 刪掉整個叢集，minikube status 顯示找不到 minikube" class="wp-image-13237" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup-300x65.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup-1024x221.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup-768x166.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct10-shots-20-cleanup-1536x332.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>minikube delete</code> 會把節點容器和叢集資料全部刪掉，下次 <code>minikube start</code> 是一個全新的空叢集。三個指令怎麼選：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>指令</th><th>做什麼</th><th>實測時間</th><th>什麼時候用</th></tr></thead><tbody><tr><td><code>minikube start</code></td><td>建立或開機</td><td>新建 34.8 秒、重開 13.5 秒</td><td>開始練習</td></tr><tr><td><code>minikube stop</code></td><td>關機，資料留著</td><td>6.1 秒</td><td>今天先練到這，明天接著用</td></tr><tr><td><code>minikube delete</code></td><td>全部刪掉</td><td>幾秒</td><td>想重來、或要釋放空間</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Cloud Shell 和 Minikube 都不收費，不刪也不會被扣錢；但 Cloud Shell 閒置一段時間會被回收，回收後 Minikube 的叢集也不會留著。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>



<p class="wp-block-paragraph">在 Google Cloud 上，叢集是用 <strong>GKE（Google Kubernetes Engine）</strong> 建的，不是 Minikube；但<strong>操作叢集的工具一樣是 kubectl</strong>，這篇學的 10 個指令全部照用。</p>



<p class="wp-block-paragraph">差別只在「怎麼讓 kubectl 連到 GKE」：GKE 的叢集建好後，要用 gcloud 指令把那個叢集的連線資訊加進 kubeconfig，kubectl 的 context 就會多一個 GKE 的叢集。這一步會在<a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">第 25 篇</a>〈GKE 部署教學〉實際做。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Minikube</th><th>GKE</th></tr></thead><tbody><tr><td>建叢集</td><td><code>minikube start</code></td><td>主控台或 gcloud 指令（第 24 篇會做）</td></tr><tr><td>操作</td><td>kubectl</td><td>kubectl（一樣）</td></tr><tr><td>節點</td><td>1 個 Docker 容器</td><td>好幾台雲端虛擬機器</td></tr><tr><td>費用</td><td>免費</td><td>叢集管理費每小時 0.10 美元＋節點費用（2026 年 11 月查 <a href="https://cloud.google.com/kubernetes-engine/pricing">GKE 定價頁</a>）</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「你平常在哪裡練 Kubernetes？」</strong>：講得出 Minikube 或 kind，並說明為什麼選它（例如「Minikube 外掛多，可以練 Ingress 和 HPA」）</li>

<li><strong>「Minikube 和正式叢集差在哪？」</strong>：Minikube 通常 1 個節點、控制平面和工作節點在同一台，不能拿來測高可用；正式叢集控制平面多份、節點多台</li>

<li><strong>「<code>minikube stop</code> 和 <code>minikube delete</code> 差在哪？」</strong>：stop 關機保留資料，delete 全部刪掉</li>

<li><strong>「Pod 有問題，你第一個打什麼指令？」</strong>：<code>kubectl describe pod</code> 看 Events，再 <code>kubectl logs</code> 看程式印了什麼</li>

<li><strong>「怎麼確認自己沒有連錯叢集？」</strong>：<code>kubectl config get-contexts</code> 看 <code>*</code> 在哪一個</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKA、CKAD）</h3>



<p class="wp-block-paragraph">兩張都是<strong>上機實作考</strong>，費用 445 美元、2 小時、含 1 次補考、效期 2 年（2026 年 11 月查 <a href="https://training.linuxfoundation.org/certification/certified-kubernetes-administrator-cka/">CKA 官方頁</a>）。考試環境就是終端機加真的叢集，所以：</p>


<ul class="wp-block-list">
<li><strong>kubectl 打得快是基本功</strong>：這篇的 10 個指令要不看筆記就打得出來</li>

<li><strong>會用 <code>kubectl explain</code></strong>：忘了 YAML 欄位怎麼寫，現場查最快</li>

<li><strong>習慣先確認 context</strong>：工作上和考試都可能同時面對好幾個叢集，動手前先確認自己連到哪一個，才不會在錯的叢集操作</li>

<li><strong>用指令產生 YAML 草稿</strong>：考試時間很緊，常見做法是先用 <code>kubectl create</code> 產生 YAML 再修改，第 11 篇會實際示範</li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「本機練習」「單節點叢集」</td><td>Minikube、kind</td></tr><tr><td>「CI 裡開臨時叢集」</td><td>kind</td></tr><tr><td>「邊緣設備」「輕量」</td><td>k3s</td></tr><tr><td>「切換叢集」「kubeconfig」</td><td><code>kubectl config use-context</code></td></tr><tr><td>「看 Pod 為什麼起不來」</td><td><code>kubectl describe pod</code>（Events）、<code>kubectl logs</code></td></tr><tr><td>「進容器下指令」</td><td><code>kubectl exec -it Pod名 -- sh</code></td></tr><tr><td>「臨時從本機連進叢集的服務」</td><td><code>kubectl port-forward</code></td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Minikube 要錢嗎？</h3>



<p class="wp-block-paragraph">不用。Minikube 是免費的開源軟體，在 Cloud Shell 跑也不收費（Cloud Shell 本身免費）。要付錢的是雲端上的正式叢集，例如 GKE 每個叢集每小時有 0.10 美元的管理費（2026 年 11 月查）。</p>



<h3 class="wp-block-heading">Minikube 一定要先裝 Docker 嗎？</h3>



<p class="wp-block-paragraph">在自己的電腦上，Minikube 需要一個「做出節點」的方法，最常用的是 Docker，也可以用 VirtualBox 這類虛擬機器軟體。在 Cloud Shell 裡 Docker、kubectl、Minikube 全部預裝好了，什麼都不用裝。</p>



<h3 class="wp-block-heading">Minikube 和 kind 差在哪？要選哪個？</h3>



<p class="wp-block-paragraph">兩個都能在一台電腦上開 Kubernetes 叢集。Minikube 外掛多（這版 39 個，像 ingress、metrics-server、dashboard），適合學習和本機開發；kind 的每個節點都是 Docker 容器，開關很快，官方定位是測試 Kubernetes 本身和 CI。新手學觀念選 Minikube 就好。</p>



<h3 class="wp-block-heading">為什麼 Cloud Shell 不能用 k3s？</h3>



<p class="wp-block-paragraph">k3s 的官方安裝腳本會把 k3s 註冊成 systemd 服務，而 Cloud Shell 是容器化的環境，沒有 systemd，所以裝不起來。Cloud Shell 已經預裝 Minikube，直接用它就好。</p>



<h3 class="wp-block-heading">minikube stop 和 minikube delete 差在哪？</h3>



<p class="wp-block-paragraph"><code>minikube stop</code> 是關機，Deployment、Service 都留著，實測 6.1 秒關、13.5 秒重開。<code>minikube delete</code> 是整個叢集刪掉，下次 start 是全新的空叢集。今天先練到這就 stop，想從頭來過就 delete。</p>



<h3 class="wp-block-heading">Minikube 新版改用 containerd，會影響練習嗎？</h3>



<p class="wp-block-paragraph">幾乎不會。Minikube v1.39.0（2026 年 9 月發布）預設改用 containerd、Kubernetes v1.37.0；Cloud Shell 目前還是 v1.38.1，用 Docker、Kubernetes v1.35.1。Pod、Deployment、Service 的寫法完全一樣，只有進節點看容器時要從 <code>docker ps</code> 改成 <code>crictl ps</code>。</p>



<h3 class="wp-block-heading">kubectl get all 真的會列出「全部」嗎？</h3>



<p class="wp-block-paragraph">不會。<code>get all</code> 只列 Pod、Service、Deployment、ReplicaSet 這類常用的工作負載和服務，ConfigMap、Secret、Ingress 這些不在裡面，要另外指定。這次實測刪完東西後用 <code>get all</code>，看得到 Pod 和 Service，但它不代表叢集裡就只剩這些。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>Minikube 是在一台電腦上開 Kubernetes 叢集的工具</strong>：Cloud Shell 預裝，實測新建 34.8 秒、關機 6.1 秒、重開 13.5 秒，完全免費</li>

<li><strong>跟 kind、k3s、GKE 的差別</strong>：Minikube 外掛多適合學習；kind 適合 CI；k3s 適合邊緣設備但 Cloud Shell 沒有 systemd 裝不起來；GKE 是正式環境要付費</li>

<li><strong>kubectl 10 個必學指令</strong>：get、describe、create、apply -f、logs、exec、expose、port-forward、scale、delete；再加上 explain 查欄位</li>

<li><strong>Kubernetes 存的是 YAML</strong>：<code>-o yaml</code> 看得到 spec（你要的）和 status（現在的），所以之後改用 <code>apply -f</code> 管理</li>

<li><strong>新舊對照</strong>：Minikube v1.39.0 起預設 containerd、Kubernetes v1.37.0；Cloud Shell 目前還是 v1.38.1</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">Docker 入門教學：不用安裝，用 Cloud Shell 跑出第一個容器</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">Docker 常用指令一次看懂：run、ps、logs、exec、stop、rm</a></li>

<li>上一篇：第 9 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a></li>

<li>下一篇：第 11 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/t-career-change-beginners-guide-cloud-technology/">轉職 IT 新手必學知識完整指南：從零基礎到雲端技術入門</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">有了一個隨時能開關的叢集，下一步就是自己寫 YAML 把容器放進去。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Minikube 要錢嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不用。Minikube 是免費的開源軟體，在 Cloud Shell 跑也不收費（Cloud Shell 本身免費）。要付錢的是雲端上的正式叢集，例如 GKE 每個叢集每小時有 0.10 美元的管理費（2026 年 11 月查）。"
      }
    },
    {
      "@type": "Question",
      "name": "Minikube 一定要先裝 Docker 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "在自己的電腦上，Minikube 需要一個「做出節點」的方法，最常用的是 Docker，也可以用 VirtualBox 這類虛擬機器軟體。在 Cloud Shell 裡 Docker、kubectl、Minikube 全部預裝好了，什麼都不用裝。"
      }
    },
    {
      "@type": "Question",
      "name": "Minikube 和 kind 差在哪？要選哪個？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "兩個都能在一台電腦上開 Kubernetes 叢集。Minikube 外掛多（這版 39 個，像 ingress、metrics-server、dashboard），適合學習和本機開發；kind 的每個節點都是 Docker 容器，開關很快，官方定位是測試 Kubernetes 本身和 CI。新手學觀念選 Minikube 就好。"
      }
    },
    {
      "@type": "Question",
      "name": "為什麼 Cloud Shell 不能用 k3s？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "k3s 的官方安裝腳本會把 k3s 註冊成 systemd 服務，而 Cloud Shell 是容器化的環境，沒有 systemd，所以裝不起來。Cloud Shell 已經預裝 Minikube，直接用它就好。"
      }
    },
    {
      "@type": "Question",
      "name": "minikube stop 和 minikube delete 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "`minikube stop` 是關機，Deployment、Service 都留著，實測 6.1 秒關、13.5 秒重開。`minikube delete` 是整個叢集刪掉，下次 start 是全新的空叢集。今天先練到這就 stop，想從頭來過就 delete。"
      }
    },
    {
      "@type": "Question",
      "name": "Minikube 新版改用 containerd，會影響練習嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "幾乎不會。Minikube v1.39.0（2026 年 9 月發布）預設改用 containerd、Kubernetes v1.37.0；Cloud Shell 目前還是 v1.38.1，用 Docker、Kubernetes v1.35.1。Pod、Deployment、Service 的寫法完全一樣，只有進節點看容器時要從 `docker ps` 改成 `crictl ps`。"
      }
    },
    {
      "@type": "Question",
      "name": "kubectl get all 真的會列出「全部」嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不會。`get all` 只列 Pod、Service、Deployment、ReplicaSet 這類常用的工作負載和服務，ConfigMap、Secret、Ingress 這些不在裡面，要另外指定。這次實測刪完東西後用 `get all`，看得到 Pod 和 Service，但它不代表叢集裡就只剩這些。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</title>
		<link>https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=gke-deploy-artifact-registry-gateway-hpa</link>
					<comments>https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:34:54 +0000</pubDate>
				<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Artifact Registry]]></category>
		<category><![CDATA[Cloud Build]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[GKE]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13540</guid>

					<description><![CDATA[<p>GKE 部署教學：Cloud Build 建映像檔推上 Artifact Registry，Deployment 寫好 requests，用 LoadBalancer、Gateway 對外，HPA 自動擴展，全程實測。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>GKE 部署怎麼做？映像檔推上 Artifact Registry，寫好 requests 部署，Gateway 對外、HPA 擴展。</strong></p>



<p class="wp-block-paragraph">第 10～18 篇在 Cloud Shell 用 Minikube 把 Kubernetes（K8s）練了一輪，用的都是 Docker Hub 上現成的 nginx；第 24 篇建好了一個 GKE Autopilot 叢集。這篇把兩邊接起來，<strong>把自己寫的程式部署到 GKE</strong>：從原始碼一路走到「全世界打得到的網址」，再讓它在流量變大時自動多開 Pod。</p>



<p class="wp-block-paragraph">這篇用的是第 4 篇那支 Flask 小網站。整條路線會實際跑一次並計時：Cloud Build 建映像檔、推上 Artifact Registry、Deployment 寫好資源要求、先用 LoadBalancer Service 對外、再換成 GKE 預裝的 Gateway API、最後開 HPA 用壓力測試讓它真的擴展。每一段都對照「在 Minikube 怎麼做、在 GKE 有什麼不一樣」。</p>



<p class="wp-block-paragraph">這是「容器系列」第 25 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，GKE 1.36.4、Google Cloud SDK 592.0.0）。價格、版本是 2026 年 11 月查官方文件的數字，以後可能調整。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-01-flow.png" alt="GKE 部署整條路線：原始碼用 Cloud Build 建成映像檔，推到 Artifact Registry，GKE 的 Deployment 拉映像檔跑成 Pod，LoadBalancer Service 或 Gateway 對外，HPA 依 CPU 自動增減 Pod，附這篇實測的每一段時間" class="wp-image-13512" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-01-flow.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-01-flow-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-01-flow-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-01-flow-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>練習和上線中間差一段路</strong>：Minikube 篇用的是 Docker Hub 現成映像檔、<code>minikube tunnel</code> 臨時拿 IP；公司真的要上線，映像檔要放自己的私人倉庫、網址要真的對外、流量大時要自動加 Pod</li>

<li><strong>照抄 Minikube 的 YAML 會多付錢</strong>：GKE Autopilot 照 Pod 的資源要求（requests）收錢，第 24 篇實測沒寫會被補成 0.5 vCPU、2 GiB，這篇算給你看寫跟不寫差多少</li>

<li><strong>Ingress 正在換成 Gateway API</strong>：第 14 篇提過 ingress-nginx 在 2026 年 3 月退場、Ingress API 凍結；GKE 叢集一建好就預裝了 Gateway 要用的 GatewayClass，新專案直接用 Gateway</li>

<li><strong>面試和證照常考</strong>：「怎麼把容器部署到 GKE」「怎麼讓它自動擴展」「LoadBalancer 和 Ingress、Gateway 怎麼選」，ACE、PCA 的情境題都會出</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">整條路線：從程式到 GKE 上線的 5 站</h2>



<p class="wp-block-paragraph">這 5 站在本系列第 12～21 篇都各自教過，這篇是第一次把它們串在同一個叢集上：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>站</th><th>用什麼</th><th>哪一篇教過</th><th>搬到 GKE 要注意的</th></tr></thead><tbody><tr><td>1. 建映像檔</td><td>Cloud Build</td><td>第 21 篇</td><td>不用在自己電腦裝 Docker，雲端建完直接推</td></tr><tr><td>2. 存映像檔</td><td>Artifact Registry</td><td>第 19 篇</td><td>GKE 節點從這裡拉，同一個專案預設就有權限</td></tr><tr><td>3. 跑起來</td><td>Deployment</td><td>第 12 篇</td><td>Autopilot 一定要寫 requests</td></tr><tr><td>4. 對外</td><td>LoadBalancer Service、Gateway</td><td>第 13、14 篇</td><td>拿到真的公開 IP，不用 <code>minikube tunnel</code></td></tr><tr><td>5. 自動擴展</td><td>HPA</td><td>第 17 篇</td><td>指標內建；Pod 放不下時 GKE 自己開節點</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>映像檔</strong>（Image）是「把程式和它需要的環境打包好的檔案」，<strong>Pod</strong> 是 K8s 裡跑容器的最小單位，第 3、11 篇有完整說明。<strong>Artifact Registry</strong> 是 Google Cloud 的私人映像檔倉庫，第 19 篇建過；<strong>Cloud Build</strong> 是在雲端幫你執行 <code>docker build</code> 的服務，第 21 篇用過。</p>



<h3 class="wp-block-heading">Gateway API 是什麼：K8s 新一代的「大門管理」</h3>



<p class="wp-block-paragraph"><strong>Gateway API 是 Kubernetes 用來描述「外面的流量怎麼進到叢集」的新標準，取代 Ingress；在 GKE 上建一個 Gateway，GKE 就幫你建一台 Google Cloud 的應用程式負載平衡器。</strong></p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：辦公大樓的大門。<strong>GatewayClass</strong> 是物業公司提供的「門的款式」（自動門、旋轉門），<strong>Gateway</strong> 是你實際裝在大樓的那一扇門（有自己的地址），<strong>HTTPRoute</strong> 是門口的指示牌（「找 ct-web 往這邊走」）</li>

<li><strong>來龍去脈</strong>：舊的 Ingress 把「門」和「指示牌」寫在同一個 YAML，各家的特殊功能只能塞在註解（annotation）裡，越寫越亂。Gateway API 把它拆成三層，2023 年推出正式版 v1.0；第 14 篇提過 Ingress API 已經凍結、不再加新功能</li>

<li><strong>為什麼要學</strong>：GKE 已經預裝好 GatewayClass，新專案要用網址、路徑分流、掛 HTTPS 憑證，都會走 Gateway。只會 Ingress 的話，看新文件和新專案會卡住</li>
</ul>



<p class="wp-block-paragraph"><strong>負載平衡器</strong>（Load Balancer）是把進來的流量分給後面好幾台機器的服務，像餐廳門口的帶位員。</p>



<h3 class="wp-block-heading">GKE 預裝的 GatewayClass，這篇選哪一個</h3>



<p class="wp-block-paragraph">第 24 篇建叢集時，事件裡就出現了 <code>gke-l7-</code> 開頭的 GatewayClass。主要的 4 個（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/gateway-api">官方 Gateway API 說明</a>和<a href="https://cloud.google.com/kubernetes-engine/docs/how-to/deploying-gateways">部署 Gateway 說明</a>）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>GatewayClass</th><th>建出來的負載平衡器</th><th>要不要先建 proxy-only 子網路</th></tr></thead><tbody><tr><td><code>gke-l7-global-external-managed</code></td><td>全球外部應用程式負載平衡器</td><td>不用（<strong>這篇用這個</strong>）</td></tr><tr><td><code>gke-l7-regional-external-managed</code></td><td>區域外部應用程式負載平衡器</td><td>要</td></tr><tr><td><code>gke-l7-rilb</code></td><td>內部應用程式負載平衡器（只給 VPC 裡面連）</td><td>要</td></tr><tr><td><code>gke-l7-gxlb</code></td><td>傳統版（classic）全球外部負載平衡器</td><td>不用，但官方建議改用第一個</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>proxy-only 子網路</strong>（Proxy-only subnet）是一段專門保留給負載平衡器代理程式用的內部 IP 範圍，要在 VPC 網路裡另外建，區域型的負載平衡器才有地方放代理（<a href="https://cloud.google.com/load-balancing/docs/proxy-only-subnets">官方說明</a>）。這篇的專案不動網路設定，所以選<strong>不用建子網路的全球型</strong>。</p>



<p class="wp-block-paragraph">全球型用的是 <strong>Anycast IP</strong>：同一個 IP 在全世界的 Google 機房都有人接，使用者會被導到最近的入口，再走 Google 自己的網路到台灣的叢集。</p>



<h3 class="wp-block-heading">LoadBalancer Service 和 Gateway 差在哪</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>LoadBalancer Service（第 13 篇）</th><th>Gateway（這篇用 <code>gke-l7-global-external-managed</code>）</th></tr></thead><tbody><tr><td>建出來的負載平衡器</td><td>外部直通式網路負載平衡器</td><td>全球外部應用程式負載平衡器</td></tr><tr><td>看什麼分流</td><td>第 4 層：只看 IP 和 Port</td><td>第 7 層：看網址、路徑、Header</td></tr><tr><td>對外 IP</td><td>區域 IP（asia-east1）</td><td>全球 Anycast IP</td></tr><tr><td>一個 IP 掛幾個服務</td><td>一個 Service 一個 IP</td><td>多個 HTTPRoute 共用一個 Gateway</td></tr><tr><td>HTTPS 憑證</td><td>要自己在容器裡處理</td><td>可以掛在 Gateway 上</td></tr><tr><td>這篇實測多久能連</td><td>46.7 秒拿到 IP，馬上能連</td><td>1 分 37 秒拿到 IP，再等 141 秒才回 200</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>第 4 層、第 7 層</strong>指的是網路分層模型的層數：第 4 層只知道「送到哪個 IP 的哪個 Port」，第 7 層看得懂 HTTP 的內容（網址、路徑），所以才能做「<code>/api</code> 給 A 服務、<code>/shop</code> 給 B 服務」這種分流。只有一個服務、不需要路徑分流時，LoadBalancer Service 最快最簡單。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-02-minikube-vs-gke.png" alt="從 Minikube 搬到 GKE 要換的 5 件事：映像檔從 Docker Hub 改成 Cloud Build 推到 Artifact Registry；LoadBalancer 不用 minikube tunnel；網址分流從 ingress 外掛改成預裝的 Gateway API；HPA 指標內建；資源要求不寫會被補 500m、2Gi 並照它收錢" class="wp-image-13513" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-02-minikube-vs-gke.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-02-minikube-vs-gke-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-02-minikube-vs-gke-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-02-minikube-vs-gke-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">算一次：requests 寫不寫，帳單差多少</h2>



<p class="wp-block-paragraph">Autopilot 一般用途的 Pod 照 Pod 宣告的<strong>資源要求</strong>（Resource requests）計費，CPU、記憶體、暫存空間各算各的。<strong>資源要求</strong>是 Pod 告訴 K8s「我至少需要多少」，<code>100m</code> 是 0.1 顆 vCPU，<code>128Mi</code> 是 128 MiB 記憶體（第 17 篇有單位換算）。台灣 asia-east1 的單價（2026 年 11 月用 Cloud Billing Catalog API 查，第 24 篇同一組）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>項目</th><th>每小時單價（asia-east1）</th></tr></thead><tbody><tr><td>CPU</td><td>每 vCPU 0.0515 美元</td></tr><tr><td>記憶體</td><td>每 GiB 0.0056998 美元</td></tr><tr><td>暫存空間</td><td>每 GiB 0.0001608 美元</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>假設</strong>：跟這篇實作一樣，平常跑 2 個 Pod，一個月 30 天（720 小時）一直開著。</p>



<p class="wp-block-paragraph"><strong>情況 A：沒寫 requests（Autopilot 補 0.5 vCPU、2 GiB、暫存 1 GiB）</strong></p>


<ul class="wp-block-list">
<li>每個 Pod 每小時：0.5 × 0.0515 ＋ 2 × 0.0056998 ＋ 1 × 0.0001608 = <strong>0.0373104 美元</strong></li>

<li>2 個 Pod 一個月：0.0373104 × 2 × 720 = <strong>約 53.73 美元</strong></li>
</ul>



<p class="wp-block-paragraph"><strong>情況 B：寫 100m CPU、128Mi 記憶體（這篇的設定；暫存沒寫，補 1 GiB）</strong></p>


<ul class="wp-block-list">
<li>每個 Pod 每小時：0.1 × 0.0515 ＋ 0.125 × 0.0056998 ＋ 1 × 0.0001608 = 0.00515 ＋ 0.000712475 ＋ 0.0001608 = <strong>0.006023275 美元</strong></li>

<li>2 個 Pod 一個月：0.006023275 × 2 × 720 = <strong>約 8.67 美元</strong>，比情況 A 少約 84%</li>
</ul>



<p class="wp-block-paragraph"><strong>對外還要加轉送規則</strong>：負載平衡器的<strong>轉送規則</strong>（Forwarding rule，「這個 IP、這個 Port 的流量交給哪個負載平衡器」的設定）前 5 條每小時 0.025 美元，一條開一個月 0.025 × 720 = <strong>18 美元</strong>，另加每 GiB 約 0.008 美元起的流量處理費；全球型和區域型的轉送規則分開計算（2026 年 11 月查<a href="https://cloud.google.com/load-balancing/pricing">官方負載平衡定價</a>）。這篇同時開了 LoadBalancer 和 Gateway 兩個，實務上選一個就好。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-03-cost.png" alt="GKE 部署算一次：2 個 Pod 開一個月，沒寫 requests 被補成 500m、2Gi 約 53.73 美元，寫 100m、128Mi 約 8.67 美元省 84%，對外的轉送規則每條每月約 18 美元另加流量處理費" class="wp-image-13514" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-03-cost.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-03-cost-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-03-cost-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-cards-03-cost-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph"><strong>這幾個數字代表什麼</strong>：</p>


<ul class="wp-block-list">
<li><strong>requests 是帳單的開關</strong>：Pod 數不變，requests 從 500m、2Gi 改成 100m、128Mi，費用剩不到兩成。但寫太小，程式不夠用會變慢，後面的 HPA 也會太早擴展。實際工作要先用 <code>kubectl top</code> 看真實用量再決定</li>

<li><strong>HPA 擴展時費用跟著 Pod 數走</strong>：尖峰時從 2 個擴到 6 個，那段時間的運算費就是 3 倍；流量退了縮回 2 個，費用也降回來。這正是 Autopilot 照 Pod 計費的好處</li>

<li><strong>一個月的固定成本主要在負載平衡器</strong>：2 個小 Pod 才 8.67 美元，一條轉送規則就要 18 美元。只是內部用、不用對外的服務，不要隨手開 LoadBalancer</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：把第 4 篇的程式部署到 GKE</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell，專案 dong-dong-gcp-3</strong>（換成你自己的專案）做，大約 40 分鐘，大部分時間在等負載平衡器和 HPA。</p>



<p class="wp-block-paragraph"><strong>會花錢</strong>：沿用第 24 篇的 GKE Autopilot 叢集 <code>ct-gke</code>（管理費每小時 0.10 美元，帳單帳戶這個月沒用掉免費額度的話會被抵掉）；2 個 Pod 照 requests 計費、壓力測試時會多幾個；LoadBalancer 和 Gateway 各一條轉送規則；Cloud Build 每月有 2,500 建置分鐘免費、Artifact Registry 每月前 0.5 GiB 免費。1 小時內做完刪掉，大約 0.2 美元以內。開始前建議先看<a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a>設好預算警示。</p>



<p class="wp-block-paragraph"><strong>還沒有叢集</strong>：照第 24 篇的步驟 1、2 建一個（<code>gcloud container clusters create-auto ct-gke --region=asia-east1</code>，約 6～7 分鐘）。Cloud Shell 怎麼打開請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~ (你的專案ID)$」。</p>



<h3 class="wp-block-heading">步驟 1：連上第 24 篇的 GKE 叢集</h3>



<pre class="wp-block-code"><code>gcloud container clusters get-credentials ct-gke --region=asia-east1; kubectl get nodes</code></pre>



<pre class="wp-block-code"><code>Fetching cluster endpoint and auth data.
kubeconfig entry generated for ct-gke.
NAME                                    STATUS   ROLES    AGE   VERSION
gk3-ct-gke-nap-1excmks3-f2c227a8-zqrb   Ready    &lt;none&gt;   42m   v1.36.4-gke.2377000
gk3-ct-gke-nap-1excmks3-f6b8e9c7-lwlh   Ready    &lt;none&gt;   43m   v1.36.4-gke.2377000</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="263" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials.png" alt="gcloud container clusters get-credentials 連上 GKE Autopilot 叢集 ct-gke，kubectl get nodes 顯示第 24 篇留下的 2 個節點" class="wp-image-13515" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials-1024x168.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials-768x126.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-01-credentials-1536x252.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>get-credentials</code> 把連到 <code>ct-gke</code> 的地址和鑰匙寫進 <code>~/.kube/config</code>，之後的 <code>kubectl</code> 都是對這個叢集下指令（第 24 篇有說明）</li>

<li>還有 2 個節點：第 24 篇的工作負載刪掉後，Autopilot 還沒把機器全部收回。節點的錢不用你付，Autopilot 只照 Pod 的 requests 收</li>
</ul>



<h3 class="wp-block-heading">步驟 2：建 Artifact Registry 存放區</h3>



<pre class="wp-block-code"><code>REPO=asia-east1-docker.pkg.dev/$(gcloud config get-value project 2&gt;/dev/null)/ct-demo; gcloud artifacts repositories create ct-demo --repository-format=docker --location=asia-east1 &amp;&amp; echo $REPO</code></pre>



<pre class="wp-block-code"><code>Create request issued for: [ct-demo]
Waiting for operation [projects/dong-dong-gcp-3/locations/asia-east1/operations/488c86d0-362e-42a8-af1a-4ad7c2c4ee1f] to complete...
....done.
Created repository [ct-demo].
asia-east1-docker.pkg.dev/dong-dong-gcp-3/ct-demo</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="187" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo.png" alt="gcloud artifacts repositories create 在 asia-east1 建立 Docker 格式的 Artifact Registry 存放區 ct-demo，REPO 變數是 asia-east1-docker.pkg.dev/專案ID/ct-demo" class="wp-image-13516" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo-1024x120.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo-768x90.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-02-repo-1536x180.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>REPO=...</code> 把存放區的位址存進<strong>變數</strong>（Variable，給一段文字取名字，之後用 <code>$REPO</code> 代替），後面建映像檔、寫 YAML 都會用到。<code>$(gcloud config get-value project 2&gt;/dev/null)</code> 會自動換成你的專案 ID，<code>2&gt;/dev/null</code> 是把它多印的提示訊息丟掉</li>

<li>映像檔的完整名字長這樣：<code>地區-docker.pkg.dev/專案ID/存放區/映像檔:標籤</code>，第 19 篇有拆解說明</li>
</ul>



<h3 class="wp-block-heading">步驟 3：準備程式（第 4 篇的 Flask 小網站）</h3>



<p class="wp-block-paragraph">跟第 4 篇一模一樣的三個檔案，用 <code>cat &gt; 檔名 &lt;&lt;'EOF'</code> 一次建好（整段複製貼上，按 Enter）：</p>



<pre class="wp-block-code"><code>mkdir -p ~/ct-deploy &amp;&amp; cd ~/ct-deploy
cat &gt; app.py &lt;&lt;'EOF'
import os
import socket
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    hostname = socket.gethostname()
    app_env = os.environ.get("APP_ENV", "not set")
    return f"""
&lt;h1&gt;Hello from my first Docker image!&lt;/h1&gt;
&lt;p&gt;Container ID (hostname): {hostname}&lt;/p&gt;
&lt;p&gt;APP_ENV: {app_env}&lt;/p&gt;
"""

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8080))
    app.run(host="0.0.0.0", port=port)
EOF
cat &gt; requirements.txt &lt;&lt;'EOF'
flask==3.1.3
EOF
cat &gt; Dockerfile &lt;&lt;'EOF'
FROM python:3.14-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 8080
CMD ["python", "app.py"]
EOF
ls; cat Dockerfile</code></pre>



<pre class="wp-block-code"><code>app.py  Dockerfile  requirements.txt
FROM python:3.14-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 8080
CMD ["python", "app.py"]</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="912" height="415" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-03-files.png" alt="在 Cloud Shell 的 ct-deploy 資料夾建好第 4 篇的 app.py、requirements.txt、Dockerfile，準備用 Cloud Build 建成映像檔部署到 GKE" class="wp-image-13517" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-03-files.png 912w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-03-files-300x137.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-03-files-768x349.png 768w" sizes="(max-width: 912px) 100vw, 912px" /></figure>


<ul class="wp-block-list">
<li>網頁會印出 <strong>hostname</strong>：在 K8s 裡 hostname 就是 Pod 的名字，等一下連線時可以看出是哪個 Pod 回應的</li>

<li><code>APP_ENV</code> 是<strong>環境變數</strong>（Environment variable，程式啟動時從外面讀進去的設定值），等一下在 Deployment 裡設成 <code>gke</code></li>
</ul>



<h3 class="wp-block-heading">步驟 4：用 Cloud Build 建映像檔、推上 Artifact Registry</h3>



<p class="wp-block-paragraph">在 Minikube 篇，映像檔不是用 Docker Hub 的現成品，就是要用 <code>minikube image load</code> 塞進叢集。GKE 的節點在 Google Cloud 上，要從<strong>網路上拿得到的倉庫</strong>拉映像檔，所以先建好推上 Artifact Registry：</p>



<pre class="wp-block-code"><code>time gcloud builds submit --region=asia-east1 --tag $REPO/ct-web:v1</code></pre>



<pre class="wp-block-code"><code>starting build "57381d2b-ae59-4ce7-9e6e-d65903b84049" using release legacy
（中間省略）
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
（中間省略）
Step 1/7 : FROM python:3.14-slim
（中間省略）
Successfully built 85265b91ddc4
Successfully tagged asia-east1-docker.pkg.dev/dong-dong-gcp-3/ct-demo/ct-web:v1
PUSH
（中間省略）
v1: digest: sha256:46f5799a4908bf28b480f6d0a6779696b2eba9a36e49a420907c661b9f81d48e size: 1991
DONE
ID: 57381d2b-ae59-4ce7-9e6e-d65903b84049
CREATE_TIME: 2026-11-21T04:09:27+00:00
DURATION: 21S
SOURCE: gs://dong-dong-gcp-3_cloudbuild/source/1795234166.275054-49df57e8d2b640cd8f5054eab727cd7a.tgz
IMAGES: asia-east1-docker.pkg.dev/dong-dong-gcp-3/ct-demo/ct-web:v1
STATUS: SUCCESS

real    0m26.800s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build.png" alt="gcloud builds submit 用 Cloud Build 在 asia-east1 建置映像檔 ct-web:v1 並推上 Artifact Registry，建置 21 秒、整個指令 26.8 秒，STATUS SUCCESS" class="wp-image-13518" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-04-build-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>gcloud builds submit --tag</code> 把目前資料夾打包上傳，Cloud Build 在雲端照 Dockerfile 建映像檔，建好推到 <code>--tag</code> 指定的位址（第 21 篇的第一種做法）</li>

<li><strong>建置 21 秒、整個指令 26.8 秒</strong>，多的 5 秒是打包上傳原始碼。你的電腦不用裝 Docker，也不用自己 <code>docker push</code></li>

<li><code>using release legacy</code>、<code>DEPRECATED: The legacy builder</code>：Cloud Build 的 docker 步驟還在用舊版建置器，不是 BuildKit（第 21 篇也遇到），目前不影響結果</li>

<li>原始碼壓縮檔放在 <code>gs://專案ID_cloudbuild/source/</code>，「用完記得刪」會清掉</li>
</ul>



<h3 class="wp-block-heading">步驟 5：確認映像檔在存放區裡</h3>



<pre class="wp-block-code"><code>gcloud artifacts docker images list $REPO --include-tags</code></pre>



<pre class="wp-block-code"><code>Listing items under project dong-dong-gcp-3, location asia-east1, repository ct-demo.
IMAGE: asia-east1-docker.pkg.dev/dong-dong-gcp-3/ct-demo/ct-web
DIGEST: sha256:46f5799a4908bf28b480f6d0a6779696b2eba9a36e49a420907c661b9f81d48e
TAGS: v1
CREATE_TIME: 2026-11-21T04:09:49
UPDATE_TIME: 2026-11-21T04:09:49
SIZE: 50003055</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1545" height="415" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images.png" alt="gcloud artifacts docker images list 顯示 Artifact Registry 存放區 ct-demo 裡有映像檔 ct-web，標籤 v1，大小 50003055 位元組約 50 MB" class="wp-image-13519" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images.png 1545w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images-300x81.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images-1024x275.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images-768x206.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-05-images-1536x413.png 1536w" sizes="(max-width: 1545px) 100vw, 1545px" /></figure>


<ul class="wp-block-list">
<li>映像檔 <code>ct-web</code>、標籤 <code>v1</code>，大小 50,003,055 位元組，約 50 MB（壓縮後的大小）</li>

<li><strong>只有 1 筆</strong>：第 19 篇在 Cloud Shell 用 Docker 29 推，會多出建置證明（attestation）那幾筆；Cloud Build 的舊版建置器不會附，所以只有映像檔本身</li>
</ul>



<h3 class="wp-block-heading">步驟 6：寫 Deployment，這次寫好 requests</h3>



<p class="wp-block-paragraph">跟第 12 篇的 Deployment 比，多了三樣東西：映像檔改成 Artifact Registry 的位址、加上 <code>resources.requests</code>、加上 <code>readinessProbe</code>。這次用 <code>&lt;&lt;EOF</code>（<strong>EOF 沒有加單引號</strong>），讓 <code>${REPO}</code> 自動換成你的存放區位址：</p>



<pre class="wp-block-code"><code>cat &gt; deployment.yaml &lt;&lt;EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ct-web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: ct-web
  template:
    metadata:
      labels:
        app: ct-web
    spec:
      containers:
      - name: web
        image: ${REPO}/ct-web:v1
        ports:
        - containerPort: 8080
        env:
        - name: APP_ENV
          value: gke
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
        readinessProbe:
          httpGet:
            path: /
            port: 8080
EOF
grep image: deployment.yaml</code></pre>



<pre class="wp-block-code"><code>        image: asia-east1-docker.pkg.dev/dong-dong-gcp-3/ct-demo/ct-web:v1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1322" height="1265" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-06-yaml.png" alt="用 cat 和沒加單引號的 EOF 建立 GKE 的 deployment.yaml，grep 確認 image 已經換成 Artifact Registry 的完整位址 asia-east1-docker.pkg.dev/專案ID/ct-demo/ct-web:v1" class="wp-image-13520" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-06-yaml.png 1322w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-06-yaml-300x287.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-06-yaml-1024x980.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-06-yaml-768x735.png 768w" sizes="(max-width: 1322px) 100vw, 1322px" /></figure>


<ul class="wp-block-list">
<li><code>&lt;&lt;'EOF'</code>（有單引號）裡的 <code>$</code> 會原封不動寫進檔案；<code>&lt;&lt;EOF</code>（沒單引號）會先把 <code>${REPO}</code> 換成變數的值。<code>grep image:</code> 確認換成功了，沒換到的話這行會是 <code>image: /ct-web:v1</code></li>

<li><code>requests: cpu: 100m, memory: 128Mi</code>：每個 Pod 要 0.1 顆 vCPU、128 MiB 記憶體。Autopilot 的最小值是 50m、52 MiB，CPU 和記憶體的比例要在 1:1 到 1:6.5（以 vCPU:GiB 算）之間；0.1 vCPU 配 0.125 GiB 是 1:1.25，合規（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-resource-requests">官方資源要求說明</a>）</li>

<li><code>readinessProbe</code>：K8s 每隔幾秒打一次 <code>/</code>，回 200 才把流量導給這個 Pod（第 17 篇的就緒探針）</li>

<li><code>replicas: 2</code>：先開 2 個，後面交給 HPA 決定要幾個</li>
</ul>



<h3 class="wp-block-heading">步驟 7：部署</h3>



<pre class="wp-block-code"><code>kubectl apply -f deployment.yaml; time kubectl rollout status deployment/ct-web --timeout=10m</code></pre>



<pre class="wp-block-code"><code>deployment.apps/ct-web created
Waiting for deployment "ct-web" rollout to finish: 0 out of 2 new replicas have been updated...
Waiting for deployment "ct-web" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "ct-web" rollout to finish: 1 of 2 updated replicas are available...
deployment "ct-web" successfully rolled out

real    0m18.485s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="329" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply.png" alt="kubectl apply 把 ct-web 部署到 GKE Autopilot，kubectl rollout status 在 18.485 秒內等到 2 個副本全部就緒，沒有出現 Autopilot 補資源的警告" class="wp-image-13521" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply-300x62.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply-1024x211.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply-768x158.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-07-apply-1536x316.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>18.5 秒就好</strong>：第 24 篇第一次部署要等 GKE 開節點，花了 1 分多鐘；這次節點已經在了，只要拉映像檔、啟動容器</li>

<li><strong>這次沒有黃色的 <code>Warning: autopilot-default-resources-mutator</code></strong>：requests 自己寫了，Autopilot 不用幫你補</li>

<li>節點能直接拉 Artifact Registry 的映像檔，是因為 GKE 節點預設用 Compute Engine 預設服務帳戶，同一個專案裡有讀取權限；映像檔放在別的專案，要另外給節點的服務帳戶「Artifact Registry 讀取者」（<code>roles/artifactregistry.reader</code>）角色（2026 年 11 月查<a href="https://cloud.google.com/artifact-registry/docs/integrate-gke">官方說明</a>）</li>
</ul>



<h3 class="wp-block-heading">步驟 8：確認 requests 沒被改</h3>



<pre class="wp-block-code"><code>kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,CPU:.spec.containers[0].resources.requests.cpu,MEMORY:.spec.containers[0].resources.requests.memory,EPHEMERAL:.spec.containers[0].resources.requests.ephemeral-storage,CPU_LIMIT:.spec.containers[0].resources.limits.cpu</code></pre>



<pre class="wp-block-code"><code>NAME                      STATUS    CPU    MEMORY   EPHEMERAL   CPU_LIMIT
ct-web-6d979cf88f-cbzpk   Running   100m   128Mi    1Gi         &lt;none&gt;
ct-web-6d979cf88f-spbwm   Running   100m   128Mi    1Gi         &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="150" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests.png" alt="kubectl get pods custom-columns 顯示 GKE Autopilot 上 ct-web 兩個 Pod 的資源要求保持 100m CPU、128Mi 記憶體，暫存空間補成 1Gi，CPU 上限是 none" class="wp-image-13522" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests-300x28.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests-1024x96.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests-768x72.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-08-requests-1536x144.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>100m、128Mi 原樣保留</strong>：這個叢集是 1.36 版，支援<strong>爆發</strong>（Bursting，Pod 可以暫時用到超過 requests 的資源），不再把 CPU 進位到 250m 的倍數（1.30.2 版以前的叢集會進位）</li>

<li><code>EPHEMERAL 1Gi</code>：暫存空間沒寫，Autopilot 補 1 GiB，一個月約 0.12 美元，影響很小</li>

<li><code>CPU_LIMIT &lt;none&gt;</code>：沒寫上限（limits）。在 Autopilot，沒寫上限的 Pod 可以爆發到「同一個節點上所有 Pod 的 requests 加總裡，別人沒用到的部分」（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/how-to/pod-bursting-gke">官方爆發說明</a>）</li>
</ul>



<h3 class="wp-block-heading">步驟 9：先用 LoadBalancer Service 對外</h3>



<p class="wp-block-paragraph">第 13 篇在 Minikube 開 LoadBalancer 要另外跑 <code>minikube tunnel</code>；在 GKE 同一個指令會真的建一個 Google Cloud 的負載平衡器：</p>



<pre class="wp-block-code"><code>kubectl expose deployment ct-web --name=ct-web-lb --type=LoadBalancer --port=80 --target-port=8080; time (until kubectl get service ct-web-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}' | grep -q .; do sleep 5; done); kubectl get service ct-web-lb</code></pre>



<pre class="wp-block-code"><code>service/ct-web-lb exposed

real    0m46.753s
NAME        TYPE           CLUSTER-IP       EXTERNAL-IP     PORT(S)        AGE
ct-web-lb   LoadBalancer   34.118.236.162   34.81.139.144   80:32672/TCP   47s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="224" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer.png" alt="kubectl expose 在 GKE 建立 LoadBalancer Service ct-web-lb，等 46.7 秒拿到外部 IP 34.81.139.144，對外 Port 80 轉到容器的 8080" class="wp-image-13523" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer-1024x143.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer-768x108.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-09-loadbalancer-1536x215.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--port=80</code> 是對外的 Port，<code>--target-port=8080</code> 是容器裡 Flask 聽的 Port（第 13 篇講過 port 和 targetPort 的差別）</li>

<li><strong>46.7 秒拿到外部 IP</strong>，第 24 篇是 57 秒，大約都在 1 分鐘內</li>

<li>這個 IP 跟第 24 篇拿到的<strong>一模一樣</strong>（34.81.139.144），原因寫在「實測時的意外」</li>
</ul>



<h3 class="wp-block-heading">步驟 10：連 6 次，看流量分給 2 個 Pod</h3>



<pre class="wp-block-code"><code>IP=$(kubectl get service ct-web-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}'); for i in 1 2 3 4 5 6; do curl -s http://$IP | grep -o 'hostname): [^&lt;]*'; done; curl -s http://$IP | grep APP_ENV</code></pre>



<pre class="wp-block-code"><code>hostname): ct-web-6d979cf88f-spbwm
hostname): ct-web-6d979cf88f-cbzpk
hostname): ct-web-6d979cf88f-spbwm
hostname): ct-web-6d979cf88f-cbzpk
hostname): ct-web-6d979cf88f-spbwm
hostname): ct-web-6d979cf88f-cbzpk
&lt;p&gt;APP_ENV: gke&lt;/p&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="225" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb.png" alt="curl 連 GKE LoadBalancer 的外部 IP 6 次，回應輪流來自 ct-web 的兩個 Pod spbwm 和 cbzpk，APP_ENV 是 gke" class="wp-image-13524" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb-1024x144.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb-768x108.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-10-curl-lb-1536x216.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>回應的 hostname 在兩個 Pod 之間輪流，代表負載平衡器真的把流量分給了 2 個 Pod</li>

<li><code>APP_ENV: gke</code>：Deployment 裡設的環境變數有傳進容器</li>

<li><code>for i in 1 2 3 4 5 6; do ...; done</code> 是「同一個指令跑 6 次」；<code>grep -o</code> 只留下 hostname 那一段</li>
</ul>



<h3 class="wp-block-heading">步驟 11：看叢集裡有哪些 GatewayClass</h3>



<pre class="wp-block-code"><code>kubectl get gatewayclass</code></pre>



<pre class="wp-block-code"><code>NAME                                            CONTROLLER                                   ACCEPTED   AGE
gke-l7-global-external-managed                  networking.gke.io/gateway                    True       47m
gke-l7-gxlb                                     networking.gke.io/gateway                    True       47m
gke-l7-regional-external-managed                networking.gke.io/gateway                    True       47m
gke-l7-rilb                                     networking.gke.io/gateway                    True       47m
gke-passthrough-lb-external-managed             networking.gke.io/persistent-ip-controller   True       48m
gke-passthrough-lb-internal-managed             networking.gke.io/persistent-ip-controller   True       48m
gke-persistent-fast-regional-external-managed   networking.gke.io/persistent-ip-controller   True       48m
gke-persistent-fast-regional-internal-managed   networking.gke.io/persistent-ip-controller   True       48m
gke-persistent-regional-external-managed        networking.gke.io/persistent-ip-controller   True       48m
gke-persistent-regional-internal-managed        networking.gke.io/persistent-ip-controller   True       48m</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="438" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass.png" alt="kubectl get gatewayclass 列出 GKE 預裝的 10 個 GatewayClass，包含 gke-l7-global-external-managed、gke-l7-regional-external-managed、gke-l7-rilb、gke-l7-gxlb，ACCEPTED 都是 True" class="wp-image-13525" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass-300x82.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass-1024x280.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass-768x210.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-11-gatewayclass-1536x420.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>前 4 個 <code>gke-l7-</code> 開頭的，就是「GKE 預裝的 GatewayClass」那張表的 4 種，<code>CONTROLLER</code> 是 <code>networking.gke.io/gateway</code>，代表由 GKE 的 Gateway 控制器負責建負載平衡器</li>

<li>後 6 個 <code>gke-passthrough-</code>、<code>gke-persistent-</code> 開頭的屬於另一個控制器 <code>persistent-ip-controller</code>，用來給第 4 層服務保留固定 IP，這篇用不到</li>

<li><code>ACCEPTED True</code>：控制器已經接手，可以直接用。這些都是 GKE 自己裝的，不用另外安裝 Gateway API</li>
</ul>



<h3 class="wp-block-heading">步驟 12：開一個叢集內部用的 Service，寫 Gateway 和 HTTPRoute</h3>



<p class="wp-block-paragraph">Gateway 要把流量交給一個 Service。這裡另外開一個 <strong>ClusterIP</strong>（只在叢集裡面能連）的 Service <code>ct-web</code>，再寫兩個檔案：</p>



<pre class="wp-block-code"><code>kubectl expose deployment ct-web --port=80 --target-port=8080
cat &gt; gateway.yaml &lt;&lt;'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: ct-gw
spec:
  gatewayClassName: gke-l7-global-external-managed
  listeners:
  - name: http
    protocol: HTTP
    port: 80
EOF
cat &gt; route.yaml &lt;&lt;'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: ct-route
spec:
  parentRefs:
  - name: ct-gw
  rules:
  - backendRefs:
    - name: ct-web
      port: 80
EOF
kubectl get service</code></pre>



<pre class="wp-block-code"><code>service/ct-web exposed
NAME         TYPE           CLUSTER-IP       EXTERNAL-IP     PORT(S)        AGE
ct-web       ClusterIP      34.118.233.241   &lt;none&gt;          80/TCP         0s
ct-web-lb    LoadBalancer   34.118.236.162   34.81.139.144   80:32672/TCP   102s
kubernetes   ClusterIP      34.118.224.1     &lt;none&gt;          443/TCP        51m</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1174" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip.png" alt="kubectl expose 建立 ClusterIP Service ct-web 給 Gateway 用，kubectl get service 列出 ct-web、ct-web-lb 和系統的 kubernetes Service" class="wp-image-13526" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip-300x220.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip-1024x751.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip-768x564.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-12-clusterip-1536x1127.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>gateway.yaml</strong>（門）：<code>gatewayClassName</code> 選全球外部型，<code>listeners</code> 說這扇門接 HTTP、Port 80</li>

<li><strong>route.yaml</strong>（指示牌）：<code>parentRefs</code> 說「我是掛在 <code>ct-gw</code> 這扇門上的」，<code>backendRefs</code> 說「進來的流量都交給 Service <code>ct-web</code> 的 80 Port」。沒寫 <code>matches</code>，就是所有路徑都送過去</li>

<li>想做第 14 篇那種 <code>/a</code>、<code>/b</code> 分流，就在 <code>rules</code> 底下加 <code>matches: - path: {type: PathPrefix, value: /a}</code>，每條規則指到不同的 Service</li>

<li><code>ct-web-lb</code> 先留著，等一下兩種對外方式可以比較</li>
</ul>



<h3 class="wp-block-heading">步驟 13：部署 Gateway，等它變成 Programmed</h3>



<pre class="wp-block-code"><code>kubectl apply -f gateway.yaml -f route.yaml; time kubectl wait gateway/ct-gw --for=condition=Programmed --timeout=15m; kubectl get gateway ct-gw</code></pre>



<pre class="wp-block-code"><code>gateway.gateway.networking.k8s.io/ct-gw created
httproute.gateway.networking.k8s.io/ct-route created
gateway.gateway.networking.k8s.io/ct-gw condition met

real    1m36.965s
NAME    CLASS                            ADDRESS        PROGRAMMED   AGE
ct-gw   gke-l7-global-external-managed   136.81.43.58   True         97s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="262" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply.png" alt="kubectl apply 建立 Gateway ct-gw 和 HTTPRoute ct-route，kubectl wait 等 1 分 37 秒 Gateway 變成 Programmed，拿到全球 IP 136.81.43.58" class="wp-image-13527" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply-1024x168.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply-768x126.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-13-gateway-apply-1536x252.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>kubectl wait --for=condition=Programmed</code>：一直等到 Gateway 的 <code>Programmed</code> 狀態變成 True。官方文件說 <code>Programmed</code> 才是「負載平衡器設定好了」的訊號，舊的 <code>Ready</code> 狀態已經保留給以後用</li>

<li><strong>1 分 37 秒</strong>拿到全球 IP <code>136.81.43.58</code>。這段時間 GKE 在背後建了一整套負載平衡器：轉送規則、目標 Proxy、網址對應、後端服務、健康檢查、防火牆規則</li>
</ul>



<h3 class="wp-block-heading">步驟 14：等 Gateway 真的能連</h3>



<p class="wp-block-paragraph"><code>Programmed</code> 不等於馬上連得到。每 10 秒打一次，印出 HTTP 狀態碼，直到回 200：</p>



<pre class="wp-block-code"><code>GW=$(kubectl get gateway ct-gw -o jsonpath='{.status.addresses[0].value}'); echo $GW; S=$(date +%s); until c=$(curl -s -o /dev/null -w '%{http_code}' http://$GW); [ "$c" = 200 ]; do printf '%s ' "$c"; sleep 10; done; echo; echo "200 after $(( $(date +%s)-S ))s"</code></pre>



<pre class="wp-block-code"><code>136.81.43.58
000 000 000 000 000 000 000 000 000 000 000 404 404 404
200 after 141s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="150" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait.png" alt="每 10 秒 curl 一次 GKE Gateway 的全球 IP，先是 11 次 000 連不上、再 3 次 404，141 秒後才回 200" class="wp-image-13528" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait-300x28.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait-1024x96.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait-768x72.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-14-gateway-wait-1536x144.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>000</code>：連線根本沒建立，全世界的 Google 入口還沒拿到這個 IP 的設定</li>

<li><code>404</code>：負載平衡器已經接起來了，但「網址要送給誰」的規則還沒生效，所以回找不到</li>

<li><strong>141 秒後才回 200</strong>。加上步驟 13 的 1 分 37 秒，<strong>從 apply 到真的能用大約 4 分鐘</strong>；LoadBalancer Service 是 47 秒。全球型負載平衡器要把設定推到全世界的入口，所以比較慢</li>

<li><code>until ...; do ...; done</code> 是「條件不成立就一直做」，<code>printf</code> 把每次的狀態碼印在同一行</li>
</ul>



<h3 class="wp-block-heading">步驟 15：從 Gateway 連看看</h3>



<pre class="wp-block-code"><code>for i in 1 2 3 4; do curl -s http://$GW | grep -o 'hostname): [^&lt;]*'; done; curl -s -o /dev/null -w "code=%{http_code} total=%{time_total}s\n" http://$GW; kubectl get httproute ct-route</code></pre>



<pre class="wp-block-code"><code>hostname): ct-web-6d979cf88f-spbwm
hostname): ct-web-6d979cf88f-cbzpk
code=200 total=0.010847s
NAME       HOSTNAMES   AGE
ct-route               4m10s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="187" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl.png" alt="透過 GKE Gateway 的全球 IP 連 ct-web，4 次裡只有 2 次印出 hostname，最後一次 code=200、0.011 秒，kubectl get httproute 顯示 ct-route" class="wp-image-13529" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl-1024x120.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl-768x90.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-15-gateway-curl-1536x180.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>回應一樣來自 <code>spbwm</code>、<code>cbzpk</code> 兩個 Pod，Gateway 跟 LoadBalancer Service 用的是同一組 Pod</li>

<li><strong>連 4 次只印出 2 個 hostname</strong>：剛回 200 的頭幾分鐘，有些請求還會失敗，下一步確認</li>

<li><code>HOSTNAMES</code> 是空的：HTTPRoute 沒限定網域，打 IP 就能連；正式環境會寫 <code>hostnames: ["www.你的網域"]</code></li>
</ul>



<h3 class="wp-block-heading">步驟 16：再連 12 次，確認 Gateway 穩定了</h3>



<pre class="wp-block-code"><code>for i in $(seq 1 12); do curl -s -o /dev/null -w '%{http_code} ' http://$GW; done; echo</code></pre>



<pre class="wp-block-code"><code>200 200 200 200 200 200 200 200 200 200 200 200</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="136" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable.png" alt="過了約 1 分鐘再連 GKE Gateway 12 次，HTTP 狀態碼全部是 200，全球外部應用程式負載平衡器已經穩定" class="wp-image-13530" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable-300x26.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable-1024x87.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable-768x65.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-16-gateway-stable-1536x131.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">再過約 1 分鐘，12 次全部 200。<strong>Gateway 剛回 200 的頭一兩分鐘還會偶爾失敗</strong>，上線、切換網域時要預留這段時間，不要一看到第一個 200 就把舊的入口拆掉。</p>



<h3 class="wp-block-heading">步驟 17：開 HPA，目標 CPU 50%</h3>



<p class="wp-block-paragraph">第 17 篇在 Minikube 開 HPA 之前，要先 <code>minikube addons enable metrics-server</code>；GKE 的指標服務是內建的，直接開：</p>



<pre class="wp-block-code"><code>kubectl autoscale deployment ct-web --cpu=50% --min=2 --max=10; sleep 60; kubectl get hpa ct-web; kubectl top pods</code></pre>



<pre class="wp-block-code"><code>horizontalpodautoscaler.autoscaling/ct-web autoscaled
NAME     REFERENCE           TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
ct-web   Deployment/ct-web   cpu: 1%/50%   2         10        2          60s
NAME                      CPU(cores)   MEMORY(bytes)
ct-web-6d979cf88f-cbzpk   1m           34Mi
ct-web-6d979cf88f-spbwm   1m           25Mi</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="219" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale.png" alt="kubectl autoscale 用新寫法 --cpu=50% 幫 GKE 上的 ct-web 建立 HPA，最少 2 個最多 10 個，TARGETS 顯示 cpu 1%/50%，kubectl top pods 顯示兩個 Pod 各用 1m CPU、25～34Mi 記憶體" class="wp-image-13531" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale-300x41.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale-1024x140.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale-768x105.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-17-autoscale-1536x210.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>HPA</strong>（Horizontal Pod Autoscaler，水平 Pod 自動擴展）依 CPU 這類指標自動調整 Pod 數量，第 17 篇有完整說明</li>

<li><code>--cpu=50%</code>：目標是「平均每個 Pod 的 CPU 用量到 requests 的 50%」，requests 是 100m，所以目標是每個 Pod 用 50m。第 17 篇用的舊參數 <code>--cpu-percent</code> 已經棄用，這次用新寫法，沒有出現棄用警告</li>

<li><code>--min=2 --max=10</code>：最少留 2 個（一個壞了還有另一個），最多 10 個（避免流量暴衝時帳單跟著暴衝）</li>

<li><code>TARGETS cpu: 1%/50%</code>：開完 1 分鐘就有數字，不像 Minikube 會先顯示 <code>&lt;unknown&gt;</code> 一陣子</li>

<li><code>kubectl top pods</code>：每個 Pod 實際只用 1m CPU、25～34 MiB 記憶體。記憶體要了 128Mi 只用到 3 成，正式環境可以觀察幾天再調低</li>
</ul>



<h3 class="wp-block-heading">步驟 18：壓力測試，看 HPA 擴展</h3>



<p class="wp-block-paragraph">跟第 17 篇一樣，開一個 busybox Pod 不停地連 <code>ct-web</code>，每 30 秒印一次 HPA 的狀態（時間是 UTC，台灣時間要加 8 小時）：</p>



<pre class="wp-block-code"><code>kubectl run load-generator --image=busybox:1.37 --restart=Never -- /bin/sh -c 'while true; do wget -q -O- http://ct-web &gt; /dev/null; done'; for i in $(seq 1 10); do sleep 30; echo "$(date +%T) $(kubectl get hpa ct-web --no-headers)"; done</code></pre>



<pre class="wp-block-code"><code>Warning: autopilot-default-resources-mutator:Autopilot updated Pod default/load-generator: defaulted unspecified 'cpu' resource for containers [load-generator] (see http://g.co/gke/autopilot-defaults).
pod/load-generator created
04:19:14 ct-web   Deployment/ct-web   cpu: 125%/50%   2     10    4     96s
04:19:44 ct-web   Deployment/ct-web   cpu: 125%/50%   2     10    5     2m6s
04:20:14 ct-web   Deployment/ct-web   cpu: 125%/50%   2     10    5     2m37s
04:20:45 ct-web   Deployment/ct-web   cpu: 52%/50%    2     10    5     3m7s
04:21:15 ct-web   Deployment/ct-web   cpu: 52%/50%    2     10    5     3m37s
04:21:45 ct-web   Deployment/ct-web   cpu: 50%/50%    2     10    5     4m7s
04:22:15 ct-web   Deployment/ct-web   cpu: 50%/50%    2     10    5     4m37s
04:22:45 ct-web   Deployment/ct-web   cpu: 51%/50%    2     10    5     5m8s
04:23:16 ct-web   Deployment/ct-web   cpu: 51%/50%    2     10    5     5m38s
04:23:46 ct-web   Deployment/ct-web   cpu: 49%/50%    2     10    5     6m8s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="334" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load.png" alt="GKE 上的 HPA 壓力測試：load-generator 開始後 30 秒內 ct-web 的 CPU 到 125%，Pod 從 2 個擴到 4 個，1 分鐘內到 5 個，之後 CPU 回到 50% 左右維持 5 個" class="wp-image-13532" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load-300x63.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load-1024x214.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load-768x160.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-18-load-1536x321.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>30 秒內從 2 個擴到 4 個，1 分鐘內到 5 個</strong>。<code>cpu: 125%/50%</code> 是「平均每個 Pod 用了 requests 的 125%」，也就是 125m</li>

<li>用第 17 篇的公式算一次：<strong>期望 Pod 數 ＝ 無條件進位（目前 Pod 數 × 目前使用率 ÷ 目標使用率）＝ 2 × 125 ÷ 50 ＝ 5</strong>，跟實際停在 5 個一樣</li>

<li>擴到 5 個之後，同樣的流量分給 5 個 Pod，使用率降到 49～52%，剛好在目標附近，HPA 就不再加</li>

<li><strong>用量 125% 超過 requests 100%</strong>：這就是步驟 8 說的爆發，沒寫上限的 Pod 可以暫時用到比 requests 多的 CPU</li>

<li>黃色 <code>Warning</code>：<code>kubectl run</code> 沒辦法寫 requests，Autopilot 幫 load-generator 補了預設值（第 24 篇看過），壓測完就刪，影響不大</li>
</ul>



<h3 class="wp-block-heading">步驟 19：新的 Pod 放在哪裡</h3>



<pre class="wp-block-code"><code>kubectl get pods -o wide | cut -c1-150; kubectl top pods; kubectl get nodes</code></pre>



<pre class="wp-block-code"><code>NAME                      READY   STATUS    RESTARTS   AGE     IP            NODE                                    NOMINATED NODE   READINESS GATES
ct-web-6d979cf88f-cbzpk   1/1     Running   0          13m     10.70.1.7     gk3-ct-gke-nap-1excmks3-f2c227a8-zqrb   &lt;none&gt;           &lt;none&gt;
ct-web-6d979cf88f-d7818   1/1     Running   0          4m51s   10.70.0.133   gk3-ct-gke-nap-1excmks3-544f3138-pwfh   &lt;none&gt;           1/1
ct-web-6d979cf88f-hz4ml   1/1     Running   0          4m51s   10.70.1.132   gk3-ct-gke-nap-1excmks3-f6b8e9c7-xpfg   &lt;none&gt;           1/1
ct-web-6d979cf88f-kwc7j   1/1     Running   0          4m38s   10.70.0.134   gk3-ct-gke-nap-1excmks3-544f3138-pwfh   &lt;none&gt;           1/1
ct-web-6d979cf88f-spbwm   1/1     Running   0          13m     10.70.1.8     gk3-ct-gke-nap-1excmks3-f2c227a8-zqrb   &lt;none&gt;           &lt;none&gt;
load-generator            1/1     Running   0          5m8s    10.70.0.132   gk3-ct-gke-nap-1excmks3-544f3138-pwfh   &lt;none&gt;           &lt;none&gt;
NAME                      CPU(cores)   MEMORY(bytes)
ct-web-6d979cf88f-cbzpk   54m          34Mi
ct-web-6d979cf88f-d7818   44m          32Mi
ct-web-6d979cf88f-hz4ml   45m          25Mi
ct-web-6d979cf88f-kwc7j   48m          24Mi
ct-web-6d979cf88f-spbwm   57m          25Mi
load-generator            360m         6Mi
NAME                                    STATUS   ROLES    AGE   VERSION
gk3-ct-gke-nap-1excmks3-544f3138-pwfh   Ready    &lt;none&gt;   13m   v1.36.4-gke.2377000
gk3-ct-gke-nap-1excmks3-544f3138-v2dd   Ready    &lt;none&gt;   97s   v1.36.4-gke.2377000
gk3-ct-gke-nap-1excmks3-f2c227a8-zqrb   Ready    &lt;none&gt;   57m   v1.36.4-gke.2377000
gk3-ct-gke-nap-1excmks3-f6b8e9c7-lwlh   Ready    &lt;none&gt;   58m   v1.36.4-gke.2377000
gk3-ct-gke-nap-1excmks3-f6b8e9c7-xpfg   Ready    &lt;none&gt;   10m   v1.36.4-gke.2377000</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="505" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes.png" alt="kubectl get pods -o wide 顯示 HPA 新開的 3 個 ct-web Pod 都 Running，放在現有的節點上，新 Pod 的 READINESS GATES 是 1/1；kubectl top pods 顯示每個 ct-web 用 44～57m CPU，load-generator 用 360m；叢集有 5 個節點" class="wp-image-13533" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes-300x95.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes-1024x323.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes-768x242.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-19-pods-nodes-1536x485.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>3 個新 Pod 放在已經開著的節點上</strong>（<code>pwfh</code>、<code>xpfg</code>），不用等開新機器，所以 30 秒內就能接流量。第 24 篇第一次部署要等 GKE 開節點，多花了約 45 秒；如果新 Pod 放不下，Autopilot 一樣會自動開節點，只是擴展會慢一點</li>

<li><strong>新 Pod 的 <code>READINESS GATES</code> 是 <code>1/1</code>，舊的是 <code>&lt;none&gt;</code></strong>：Gateway 用的是「容器原生負載平衡」（Container-native load balancing，負載平衡器直接把流量送到 Pod 的 IP，不經過節點轉一手），GKE 會幫新 Pod 加一道就緒關卡，等負載平衡器的健康檢查也通過才算就緒，避免流量打到還沒準備好的 Pod（<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/container-native-load-balancing">官方說明</a>）</li>

<li><code>kubectl top pods</code>：5 個 ct-web 各用 44～57m，平均約 50m，正好是目標（100m 的 50%）。load-generator 自己用了 360m，壓測工具本身也很吃 CPU</li>

<li>節點有 5 台，其中 <code>v2dd</code> 才開 97 秒，是 GKE 自己決定多準備的。Autopilot 照 Pod 收錢，節點數不影響帳單</li>
</ul>



<h3 class="wp-block-heading">步驟 20：停掉壓力，看 HPA 多久縮回來</h3>



<pre class="wp-block-code"><code>kubectl delete pod load-generator --now; for i in $(seq 1 9); do sleep 60; echo "$(date +%T) $(kubectl get hpa ct-web --no-headers)"; done</code></pre>



<pre class="wp-block-code"><code>pod "load-generator" deleted from default namespace
04:25:03 ct-web   Deployment/ct-web   cpu: 7%/50%   2     10    5     7m25s
04:26:03 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     8m25s
04:27:03 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     9m25s
04:28:03 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     10m
04:29:03 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     11m
04:30:04 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     12m
04:31:04 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    5     13m
04:32:04 ct-web   Deployment/ct-web   cpu: 0%/50%   2     10    3     14m
04:33:04 ct-web   Deployment/ct-web   cpu: 1%/50%   2     10    3     15m</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="262" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down.png" alt="刪掉 load-generator 後每分鐘看一次 GKE 的 HPA：CPU 1 分鐘內掉到 1%，但 Pod 數維持 5 個約 8 分鐘，04:32 才縮成 3 個" class="wp-image-13534" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down-1024x168.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down-768x126.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20-scale-down-1536x252.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--now</code> 是立刻刪掉、不等 30 秒的正常關機時間（<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">第 11 篇</a>看過 busybox 收到關機訊號不理，刪除要等滿 30 秒）</li>

<li><strong>CPU 1 分鐘內就掉到 1%，Pod 數卻維持 5 個約 8 分鐘</strong>，04:32 才縮成 3 個，9 分鐘結束時還沒回到最少的 2 個</li>

<li>這是故意的：HPA 縮減前有 <strong>5 分鐘的穩定視窗</strong>（scale-down stabilization window），要看到連續 5 分鐘都不需要那麼多 Pod 才縮，避免流量忽高忽低時一直開了又關（2026 年 11 月查<a href="https://cloud.google.com/kubernetes-engine/docs/concepts/horizontalpodautoscaler">官方 HPA 說明</a>）。擴展則沒有等待，0 秒就動</li>

<li>對帳單的意思：尖峰過後還會多付幾分鐘的 Pod 錢，但比「尖峰時 Pod 不夠、網站變慢」划算</li>
</ul>



<p class="wp-block-paragraph">再看一次現在的 Pod：</p>



<pre class="wp-block-code"><code>date +%T; kubectl get hpa ct-web; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>04:33:24
NAME     REFERENCE           TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
ct-web   Deployment/ct-web   cpu: 1%/50%   2         10        3          15m
NAME                      READY   STATUS    RESTARTS   AGE
ct-web-6d979cf88f-5l77c   1/1     Running   0          7m31s
ct-web-6d979cf88f-cbzpk   1/1     Running   0          23m
ct-web-6d979cf88f-spbwm   1/1     Running   0          23m</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1442" height="381" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20b-hpa-now.png" alt="縮減後再看 GKE 的 HPA 還是 3 個副本，Pod 列表裡多了一個 7 分 31 秒前才建立的 ct-web-6d979cf88f-5l77c，是 GKE 整理節點時重開的" class="wp-image-13535" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20b-hpa-now.png 1442w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20b-hpa-now-300x79.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20b-hpa-now-1024x271.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-20b-hpa-now-768x203.png 768w" sizes="(max-width: 1442px) 100vw, 1442px" /></figure>



<p class="wp-block-paragraph">剩下的 3 個 Pod 裡，<code>5l77c</code> 是 7 分 31 秒前才建立的，不在壓測時新開的那 3 個裡面。壓力停掉後，GKE 一邊縮 Pod、一邊把用不到的節點收掉，原本在那些節點上的 Pod 會被搬到別台重開。<strong>所以程式要能隨時被關掉、在別台重開也不出事</strong>，這也是 K8s 要求應用「無狀態」的原因（<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">第 16 篇</a>講過資料要放在 Volume 或外部資料庫）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. Gateway 顯示 Programmed，還要再等 2 分多鐘才連得到</h3>



<p class="wp-block-paragraph">一般以為 <code>kubectl wait --for=condition=Programmed</code> 回來就能用了。實測 Programmed 之後，先是 11 次連不上（<code>000</code>）、再 3 次 <code>404</code>，<strong>141 秒後才回 200</strong>；剛回 200 時連 4 次還有 2 次失敗，再過 1 分鐘才 12 次全部成功。全球型負載平衡器要把設定推到全世界的 Google 入口，所以會有這段空窗。換網域、切流量時，要用 <code>curl</code> 連續確認一陣子都是 200，才把舊的入口拆掉。</p>



<h3 class="wp-block-heading">2. LoadBalancer 拿到的 IP，跟第 24 篇一模一樣</h3>



<p class="wp-block-paragraph">步驟 9 拿到的外部 IP 是 <code>34.81.139.144</code>，跟第 24 篇刪掉的那個 LoadBalancer 是同一個。LoadBalancer Service 預設用的是<strong>臨時外部 IP</strong>（Ephemeral IP），Service 刪掉後 IP 會還給 Google，之後可能被分給任何人，這次剛好又分回同一個專案。反過來說，<strong>刪掉 Service 再重建，IP 通常會變</strong>，網域的 DNS 記錄要跟著改。正式環境要固定 IP，要先保留一個靜態外部 IP 位址，再指定給 Service 或 Gateway（<a href="https://cloud.google.com/vpc/docs/ip-addresses">官方 IP 位址說明</a>）。</p>



<h3 class="wp-block-heading">3. GatewayClass 有 10 個，不只文件常講的 4 個</h3>



<p class="wp-block-paragraph">第 24 篇的事件裡只看到 4 個 <code>gke-l7-</code> 開頭的 GatewayClass，步驟 11 列出來卻有 10 個，多的 6 個是 <code>gke-passthrough-</code>、<code>gke-persistent-</code> 開頭、由另一個控制器 <code>persistent-ip-controller</code> 負責，用途是幫第 4 層的服務保留固定 IP。看到這麼多不用緊張，對外的網頁服務選 <code>gke-l7-global-external-managed</code> 就好。</p>



<h3 class="wp-block-heading">4. 擴展 30 秒、縮回 8 分鐘</h3>



<p class="wp-block-paragraph">HPA 擴展幾乎是立刻的：壓測開始後 30 秒內就從 2 個變 4 個。縮回卻慢很多：CPU 1 分鐘就掉到 1%，Pod 數維持 5 個約 8 分鐘才縮成 3 個。這是 HPA 預設的 5 分鐘縮減穩定視窗，不是故障。想縮快一點，可以在 HPA 的 YAML 寫 <code>behavior.scaleDown.stabilizationWindowSeconds</code> 調短，但流量忽高忽低的服務會因此一直開了又關。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<h3 class="wp-block-heading">先刪 HPA、Gateway、Service、Deployment</h3>



<p class="wp-block-paragraph"><strong>負載平衡器先刪</strong>：LoadBalancer 和 Gateway 都是照小時計費、而且對全世界開著的。</p>



<pre class="wp-block-code"><code>kubectl delete hpa ct-web; kubectl delete -f route.yaml -f gateway.yaml; time kubectl delete service ct-web-lb; kubectl delete service ct-web; kubectl delete deployment ct-web; kubectl get all</code></pre>



<pre class="wp-block-code"><code>horizontalpodautoscaler.autoscaling "ct-web" deleted from default namespace
httproute.gateway.networking.k8s.io "ct-route" deleted from default namespace
gateway.gateway.networking.k8s.io "ct-gw" deleted from default namespace
service "ct-web-lb" deleted from default namespace

real    0m33.031s
service "ct-web" deleted from default namespace
deployment.apps "ct-web" deleted from default namespace
NAME                          READY   STATUS        RESTARTS   AGE
pod/ct-web-6d979cf88f-5l77c   1/1     Terminating   0          8m51s
pod/ct-web-6d979cf88f-cbzpk   1/1     Terminating   0          24m
pod/ct-web-6d979cf88f-spbwm   1/1     Terminating   0          24m

NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   34.118.224.1   &lt;none&gt;        443/TCP   74m</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="407" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s.png" alt="依序刪掉 GKE 上的 HPA、HTTPRoute、Gateway、LoadBalancer Service（花 33 秒）、ClusterIP Service 和 Deployment，3 個 Pod 正在 Terminating，只剩系統的 kubernetes Service" class="wp-image-13536" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s-300x76.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s-1024x260.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s-768x195.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-21-cleanup-k8s-1536x391.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>刪 LoadBalancer Service 花了 33 秒</strong>，<code>kubectl</code> 會等負載平衡器拆完才回來；<strong>刪 Gateway 是馬上回來</strong>，負載平衡器在背後慢慢拆，所以要另外確認</li>

<li><code>service/kubernetes</code> 是叢集內建的，<strong>不要刪</strong></li>
</ul>



<h3 class="wp-block-heading">確認負載平衡器真的拆掉了</h3>



<p class="wp-block-paragraph">等 90 秒，查專案裡還有沒有這篇建的轉送規則：</p>



<pre class="wp-block-code"><code>sleep 90; gcloud compute forwarding-rules list --filter="name~ct-gw OR description~ct-web-lb" --format='table(name,region.basename(),IPAddress)'</code></pre>



<pre class="wp-block-code"><code>WARNING: The following filter keys were not present in any resource : description, name</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="114" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb.png" alt="等 90 秒後用 gcloud compute forwarding-rules list 查 Gateway 和 LoadBalancer 的轉送規則，只出現 filter keys were not present in any resource 的警告，代表專案裡已經沒有任何轉送規則" class="wp-image-13537" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb-300x21.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb-1024x73.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb-768x55.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-22-cleanup-lb-1536x109.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這個警告的意思是「專案裡一筆轉送規則都沒有，所以找不到這些欄位」，也就是 LoadBalancer 和 Gateway 的轉送規則都已經刪光了。另外查網路端點群組、後端服務、健康檢查、防火牆規則，跟 <code>ct-</code> 有關的也都是 0 筆（2026 年 11 月實測）。</p>



<h3 class="wp-block-heading">刪存放區和 Cloud Shell 裡的資料夾</h3>



<pre class="wp-block-code"><code>cd ~ &amp;&amp; rm -rf ~/ct-deploy &amp;&amp; gcloud artifacts repositories delete ct-demo --location=asia-east1 --quiet; gcloud artifacts repositories list --location=asia-east1 --format='value(name.basename())' | grep -c ct-demo</code></pre>



<pre class="wp-block-code"><code>Delete request issued for: [ct-demo]
Waiting for operation [projects/dong-dong-gcp-3/locations/asia-east1/operations/5bfdd746-c68f-4005-b3ef-3e0e4e4a5a7f] to complete...
.done.
Deleted repository [ct-demo].
Listing items under project dong-dong-gcp-3, location asia-east1.

0</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="224" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar.png" alt="刪除 Artifact Registry 存放區 ct-demo 和 Cloud Shell 的 ct-deploy 資料夾，再列出存放區用 grep -c 數 ct-demo，結果是 0" class="wp-image-13538" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar-1024x143.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar-768x108.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-23-cleanup-ar-1536x215.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪存放區會連裡面的映像檔一起刪。最後的 <code>0</code> 是「存放區清單裡 <code>ct-demo</code> 出現 0 次」，確認刪掉了。</p>



<h3 class="wp-block-heading">刪 Cloud Build 留下的原始碼壓縮檔</h3>



<p class="wp-block-paragraph"><code>gcloud builds submit</code> 上傳的原始碼留在 <code>專案ID_cloudbuild</code> 這個 bucket，<strong>bucket 本身不要刪</strong>（之後的建置還會用），只刪這次的檔案：</p>



<pre class="wp-block-code"><code>gcloud builds list --region=asia-east1 --filter='images~ct-demo/ct-web' --format='value(id,source.storageSource.bucket,source.storageSource.object)'</code></pre>



<pre class="wp-block-code"><code>57381d2b-ae59-4ce7-9e6e-d65903b84049	dong-dong-gcp-3_cloudbuild	source/1795234166.275054-49df57e8d2b640cd8f5054eab727cd7a.tgz</code></pre>



<pre class="wp-block-code"><code>gcloud storage rm gs://dong-dong-gcp-3_cloudbuild/source/1795234166.275054-49df57e8d2b640cd8f5054eab727cd7a.tgz</code></pre>



<pre class="wp-block-code"><code>Removing gs://dong-dong-gcp-3_cloudbuild/source/1795234166.275054-49df57e8d2b640cd8f5054eab727cd7a.tgz...</code></pre>



<h3 class="wp-block-heading">叢集先留著（第 26 篇會沿用）</h3>



<pre class="wp-block-code"><code>kubectl get all; gcloud container clusters list --format='table(name,location,currentMasterVersion,autopilot.enabled,status)'</code></pre>



<pre class="wp-block-code"><code>NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   34.118.224.1   &lt;none&gt;        443/TCP   76m
NAME: ct-gke
LOCATION: asia-east1
CURRENT_MASTER_VERSION: 1.36.4-gke.2377000
ENABLED: True
STATUS: RUNNING</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="239" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept.png" alt="清理完 kubectl get all 只剩系統的 kubernetes Service，gcloud container clusters list 顯示 GKE Autopilot 叢集 ct-gke 還在 RUNNING，留給第 26 篇使用" class="wp-image-13539" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept-300x45.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept-1024x153.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept-768x115.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct25-shots-24-cluster-kept-1536x229.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">叢集裡只剩內建的 <code>service/kubernetes</code>。這個叢集第 26 篇還會用，所以先不刪。<strong>你練習完不打算接著做，就直接刪整個叢集</strong>：</p>



<pre class="wp-block-code"><code>gcloud container clusters delete ct-gke --region=asia-east1 --quiet</code></pre>



<p class="wp-block-paragraph">第 26 篇做完會實際刪一次並附上輸出。</p>



<h3 class="wp-block-heading">不刪會怎麼計費</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>資源</th><th>不刪的話（asia-east1，2026 年 11 月查）</th></tr></thead><tbody><tr><td>LoadBalancer Service、Gateway</td><td>轉送規則各每小時 0.025 美元，一條一個月約 18 美元，另加流量處理費</td></tr><tr><td>Deployment 的 2 個 Pod</td><td>照 requests：一個月約 8.67 美元；沒寫 requests 約 53.73 美元</td></tr><tr><td>HPA 擴出來的 Pod</td><td>每多一個，一個月多約 4.34 美元</td></tr><tr><td>Artifact Registry 的 50 MB 映像檔</td><td>每個帳單帳戶每月前 0.5 GiB 免費，超過每 GiB 每月約 0.10 美元（第 19 篇有算法）</td></tr><tr><td>空的 Autopilot 叢集</td><td>管理費每小時 0.10 美元，帳單帳戶當月只有這一個叢集的話被 74.40 美元免費額度抵掉</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">在 Minikube 怎麼做、在 GKE 有什麼不一樣</h2>



<p class="wp-block-paragraph">同一套 Deployment、Service、HPA 的寫法，第 10～18 篇在 Minikube、這篇在 GKE 都能用。不一樣的是叢集外面那一圈：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Minikube（第 10～18 篇）</th><th>GKE Autopilot（這篇實測）</th></tr></thead><tbody><tr><td>映像檔從哪來</td><td>Docker Hub，或 <code>minikube image load</code> 把本機映像檔塞進叢集</td><td>Cloud Build 建好推到 Artifact Registry（26.8 秒）</td></tr><tr><td><code>image:</code> 怎麼寫</td><td><code>nginx:1.30</code> 這種短名字</td><td><code>asia-east1-docker.pkg.dev/專案ID/ct-demo/ct-web:v1</code> 完整位址</td></tr><tr><td>LoadBalancer</td><td>要另開 <code>minikube tunnel</code> 才有 IP</td><td>自動建 Google Cloud 負載平衡器，46.7 秒拿到公開 IP</td></tr><tr><td>網址分流</td><td><code>minikube addons enable ingress</code>（ingress-nginx 已退場）</td><td>Gateway API，GatewayClass 已預裝，約 4 分鐘能連</td></tr><tr><td>HPA 的指標</td><td>要先 <code>minikube addons enable metrics-server</code></td><td>內建，<code>kubectl top</code> 直接能用</td></tr><tr><td>Pod 放不下時</td><td>Pending，要自己加資源</td><td>Autopilot 自動開節點</td></tr><tr><td>資源要求</td><td>不寫也照跑、不收錢</td><td>不寫補 500m、2Gi，照 requests 收錢</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>練 K8s 指令用 Minikube，不花錢；要讓網站真的對外、要自動擴展到多台機器，才上 GKE。</strong></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「怎麼把一個應用部署到 GKE？」</strong>：用 Cloud Build（或 CI/CD）建映像檔推到 Artifact Registry；Deployment 的 <code>image</code> 寫 Artifact Registry 的完整位址、寫好 requests 和 readinessProbe；用 LoadBalancer Service 或 Gateway 對外；用 HPA 依 CPU 自動擴展</li>

<li><strong>「LoadBalancer Service 和 Ingress、Gateway 怎麼選？」</strong>：只有一個服務、只要一個 IP，用 LoadBalancer（第 4 層，最快）；要依網址路徑或網域分流、要在入口掛 HTTPS 憑證、多個服務共用一個 IP，用 Gateway（第 7 層），新專案不要再選 Ingress</li>

<li><strong>「GKE 節點怎麼有權限拉私人映像檔？」</strong>：節點用 Compute Engine 預設服務帳戶（或你指定的節點服務帳戶），需要 Artifact Registry 讀取者角色；同一個專案預設就有，跨專案要另外授權</li>

<li><strong>「HPA 在 Autopilot 上擴展時，節點不夠怎麼辦？」</strong>：HPA 只負責加 Pod，Pod 放不下時 Autopilot 自動開節點（Standard 要開叢集自動調度器）；這也是 Autopilot 擴展比較慢的原因之一</li>
</ul>



<h3 class="wp-block-heading">Google Cloud 證照（ACE、PCA）</h3>



<p class="wp-block-paragraph">Associate Cloud Engineer（ACE）是 2 小時、50～60 題單選和複選的情境選擇題，不是上機考，報名費 125 美元、效期 3 年（2026 年 11 月查<a href="https://cloud.google.com/learn/certification/cloud-engineer">官方考試頁</a>）。這篇的流程在 ACE 常以「部署容器到 GKE 的正確步驟順序」「讓 Deployment 依 CPU 自動擴展用哪個指令」出題；PCA（雲端架構師）會問「全球使用者、要 HTTPS、要依路徑分流」該選哪種負載平衡器。準備方式可以看<a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照怎麼準備</a>。</p>



<p class="wp-block-paragraph">Kubernetes 自己的證照 CKAD、CKA 是上機實作考，<code>kubectl autoscale</code>、<code>kubectl expose</code>、<code>kubectl set image</code> 這類原生指令要很熟；Gateway API 也已經在 CKA 的範圍裡（第 14 篇有整理）。</p>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「私人映像檔」「GKE 要拉映像檔」「取代 Container Registry」</td><td>Artifact Registry</td></tr><tr><td>「不想在本機裝 Docker」「雲端建置」</td><td>Cloud Build（<code>gcloud builds submit</code>）</td></tr><tr><td>「依 CPU 使用率自動增減 Pod」</td><td>HPA（<code>kubectl autoscale</code>）</td></tr><tr><td>「Pod 不夠放時自動加機器」</td><td>Autopilot 自動開節點／Standard 的叢集自動調度器</td></tr><tr><td>「全球使用者、依路徑分流、HTTPS」</td><td>Gateway（全球外部應用程式負載平衡器）</td></tr><tr><td>「只要一個對外 IP、TCP／UDP」</td><td>LoadBalancer Service（直通式網路負載平衡器）</td></tr><tr><td>「Autopilot 帳單太高」</td><td>檢查 requests 有沒有寫、寫太大</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">GKE 部署應用要哪幾個步驟？</h3>



<p class="wp-block-paragraph">五步：用 Cloud Build 建映像檔並推到 Artifact Registry；寫 Deployment，<code>image</code> 填 Artifact Registry 的完整位址、寫好 requests；用 <code>kubectl apply</code> 部署；用 LoadBalancer Service 或 Gateway 對外；用 HPA 依 CPU 自動擴展。這篇在 Autopilot 實測：建映像檔 26.8 秒、部署 18.5 秒、LoadBalancer 46.7 秒拿到 IP、Gateway 約 4 分鐘能連（2026 年 11 月）。</p>



<h3 class="wp-block-heading">GKE 要用 Ingress 還是 Gateway？</h3>



<p class="wp-block-paragraph">新專案用 Gateway。Gateway API 是 Kubernetes 取代 Ingress 的新標準，把「門」和「路由規則」拆開，GKE 叢集已經預裝好 GatewayClass。要對外又不想建 proxy-only 子網路，選 <code>gke-l7-global-external-managed</code>（全球外部應用程式負載平衡器）；官方建議不要再用傳統版的 <code>gke-l7-gxlb</code>（2026 年 11 月查官方文件）。</p>



<h3 class="wp-block-heading">GKE 的 Gateway 建好要多久才能連？</h3>



<p class="wp-block-paragraph">這篇實測（asia-east1，全球外部型）：<code>kubectl apply</code> 後 1 分 37 秒狀態變成 Programmed、拿到全球 IP，之後再等 141 秒才回 200，中間先是連不上（000）、再回 404；剛回 200 的頭幾分鐘偶爾還會失敗。同一個叢集的 LoadBalancer Service 是 46.7 秒拿到 IP、馬上能連。</p>



<h3 class="wp-block-heading">GKE Autopilot 的 requests 要怎麼寫才省錢？</h3>



<p class="wp-block-paragraph">照程式真正用到的量寫，不要不寫。沒寫會被補成 0.5 vCPU、2 GiB，2 個 Pod 一個月約 53.73 美元；這篇寫 100m、128Mi，降到約 8.67 美元。支援爆發的叢集（1.30.2 版以後）最小可以寫 50m、52 MiB，CPU 和記憶體比例要在 1:1 到 1:6.5 之間（2026 年 11 月查官方文件）。</p>



<h3 class="wp-block-heading">GKE 節點拉不到 Artifact Registry 的映像檔怎麼辦？</h3>



<p class="wp-block-paragraph">先看映像檔位址有沒有寫錯（<code>kubectl describe pod</code> 的事件會寫 <code>ImagePullBackOff</code>，<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-troubleshooting-crashloopbackoff/">第 18 篇</a>有排錯步驟）；位址對的話，是節點的服務帳戶沒有讀取權限。同一個專案預設就能拉；跨專案或專案關掉了預設的 Editor 角色時，要給節點的服務帳戶「Artifact Registry 讀取者」（<code>roles/artifactregistry.reader</code>）。</p>



<h3 class="wp-block-heading">GKE 上的 HPA 多久會擴展、多久會縮回？</h3>



<p class="wp-block-paragraph">這篇在 GKE Autopilot 實測（目標 CPU 50%、最少 2 最多 10 個）：壓力開始後 30 秒內從 2 個擴到 4 個，1 分鐘內到 5 個，剛好是公式 2 × 125% ÷ 50% ＝ 5；停掉壓力後 CPU 1 分鐘就降到 1%，但 Pod 數維持約 8 分鐘才縮成 3 個。縮得慢是因為 HPA 預設有 5 分鐘的縮減穩定視窗，擴展則是 0 秒（2026 年 11 月查官方文件）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>GKE 部署 5 站</strong>：Cloud Build 建映像檔 → Artifact Registry 存 → Deployment 跑（寫 requests）→ LoadBalancer 或 Gateway 對外 → HPA 擴展</li>

<li><strong>requests 是 Autopilot 帳單的開關</strong>：2 個 Pod 一個月，沒寫約 53.73 美元、寫 100m、128Mi 約 8.67 美元；這次部署沒出現補資源的警告</li>

<li><strong>對外兩條路</strong>：LoadBalancer Service 是第 4 層，46.7 秒拿到 IP；Gateway 是第 7 層、能依路徑分流，約 4 分鐘才能連。不想動網路設定就選全球型 <code>gke-l7-global-external-managed</code></li>

<li><strong>HPA 擴得快、縮得慢</strong>：壓測 30 秒內 2 個變 4 個、1 分鐘到 5 個（2 × 125% ÷ 50% ＝ 5）；停掉後約 8 分鐘才縮到 3 個，縮減預設有 5 分鐘穩定視窗</li>

<li><strong>跟 Minikube 的差別在叢集外面</strong>：映像檔要放網路上拿得到的倉庫、LoadBalancer 不用 tunnel、Ingress 換 Gateway、指標內建、節點自動開</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 4 篇：<a href="https://dongdonggcp.com/2026/11/18/dockerfile-tutorial-build-first-image/">Dockerfile 怎麼寫？從零打包你的第一個網頁映像檔</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a></li>

<li>第 14 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">Ingress 是什麼？用網址路徑把流量分給不同服務（含 Gateway API）</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">健康檢查與自動擴展：Probe、資源限制、HPA</a></li>

<li>第 19 篇：<a href="https://dongdonggcp.com/2025/07/20/artifact-registry-tutorials/">Artifact Registry 是什麼？把 Docker 映像檔推上 GCP 教學</a></li>

<li>第 21 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">Cloud Build 是什麼？用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run</a></li>

<li>上一篇：第 24 篇：<a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li>下一篇：第 26 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務</a></li>
</ul>



<p class="wp-block-paragraph"><strong>Kubernetes、GKE 相關</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2024/12/02/gke-what-is-helm-charts-what-is-oci-charts/">Helm Charts 是什麼？GKE 上的 Kubernetes 套件管理</a></li>

<li><a href="https://dongdonggcp.com/2024/12/02/what-is-gitops-methodolity-what-is-gitops-process/">GitOps 是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a></li>

<li>影片版（五條指令建 GKE 叢集和 HTTP 負載平衡器，2025 年錄製，介面可能跟現在略有不同）：[[GKE 教學] 032 五條指令完成 GKE Cluster 和 Http Load Balancer](https://www.youtube.com/watch?v=3f-_I8EyzUY)</li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照（PCA）怎麼準備</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析：雲端工程師、架構師、SRE、DevOps、資料工程師差在哪？</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">程式已經在 GKE 上自動擴展了，下一篇處理上線前最後一個問題：Pod 要讀 Cloud Storage 這類 GCP 服務時，怎麼不放金鑰也能安全存取。可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "GKE 部署應用要哪幾個步驟？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "五步：用 Cloud Build 建映像檔並推到 Artifact Registry；寫 Deployment，`image` 填 Artifact Registry 的完整位址、寫好 requests；用 `kubectl apply` 部署；用 LoadBalancer Service 或 Gateway 對外；用 HPA 依 CPU 自動擴展。這篇在 Autopilot 實測：建映像檔 26.8 秒、部署 18.5 秒、LoadBalancer 46.7 秒拿到 IP、Gateway 約 4 分鐘能連（2026 年 11 月）。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE 要用 Ingress 還是 Gateway？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "新專案用 Gateway。Gateway API 是 Kubernetes 取代 Ingress 的新標準，把「門」和「路由規則」拆開，GKE 叢集已經預裝好 GatewayClass。要對外又不想建 proxy-only 子網路，選 `gke-l7-global-external-managed`（全球外部應用程式負載平衡器）；官方建議不要再用傳統版的 `gke-l7-gxlb`（2026 年 11 月查官方文件）。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE 的 Gateway 建好要多久才能連？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "這篇實測（asia-east1，全球外部型）：`kubectl apply` 後 1 分 37 秒狀態變成 Programmed、拿到全球 IP，之後再等 141 秒才回 200，中間先是連不上（000）、再回 404；剛回 200 的頭幾分鐘偶爾還會失敗。同一個叢集的 LoadBalancer Service 是 46.7 秒拿到 IP、馬上能連。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE Autopilot 的 requests 要怎麼寫才省錢？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "照程式真正用到的量寫，不要不寫。沒寫會被補成 0.5 vCPU、2 GiB，2 個 Pod 一個月約 53.73 美元；這篇寫 100m、128Mi，降到約 8.67 美元。支援爆發的叢集（1.30.2 版以後）最小可以寫 50m、52 MiB，CPU 和記憶體比例要在 1:1 到 1:6.5 之間（2026 年 11 月查官方文件）。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE 節點拉不到 Artifact Registry 的映像檔怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "先看映像檔位址有沒有寫錯（`kubectl describe pod` 的事件會寫 `ImagePullBackOff`，第 18 篇有排錯步驟）；位址對的話，是節點的服務帳戶沒有讀取權限。同一個專案預設就能拉；跨專案或專案關掉了預設的 Editor 角色時，要給節點的服務帳戶「Artifact Registry 讀取者」（`roles/artifactregistry.reader`）。"
      }
    },
    {
      "@type": "Question",
      "name": "GKE 上的 HPA 多久會擴展、多久會縮回？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "這篇在 GKE Autopilot 實測（目標 CPU 50%、最少 2 最多 10 個）：壓力開始後 30 秒內從 2 個擴到 4 個，1 分鐘內到 5 個，剛好是公式 2 × 125% ÷ 50% ＝ 5；停掉壓力後 CPU 1 分鐘就降到 1%，但 Pod 數維持約 8 分鐘才縮成 3 個。縮得慢是因為 HPA 預設有 5 分鐘的縮減穩定視窗，擴展則是 0 秒（2026 年 11 月查官方文件）。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Docker、Kubernetes 教學地圖：從容器到 Cloud Run、GKE 全系列整理</title>
		<link>https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=docker-kubernetes-learning-map</link>
					<comments>https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:34:37 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[轉職 IT]]></category>
		<category><![CDATA[Cloud Run]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[GKE]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13572</guid>

					<description><![CDATA[<p>Kubernetes 教學照順序走：Docker 8 篇、Minikube 練 K8s 10 篇、Cloud Run 與 GKE 9 篇。整理 27 篇重點、時間花費、CKA／ACE 路線，前 18 篇在 Cloud Shell 免費做。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/">Docker、Kubernetes 教學地圖：從容器到 Cloud Run、GKE 全系列整理</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Kubernetes 教學先學 Docker 打包容器，再用 Minikube 練 K8s，最後搬上 Cloud Run、GKE。</strong></p>



<p class="wp-block-paragraph">這個系列一共 28 篇。前 27 篇每一篇都在 Google Cloud Shell 實際跑過，文章裡的指令和輸出都是當次跑出來的真實結果；這篇是第 28 篇，把 27 篇排成一張學習地圖，告訴你先讀哪篇、每篇學到什麼、要花多少時間和多少錢。</p>



<p class="wp-block-paragraph">Docker 和原生 Kubernetes 兩段（第 1～18 篇）用不設專案的 Cloud Shell 做，不用安裝任何東西、不用綁信用卡。Cloud Run、GKE 兩段（第 19～26 篇）要在自己的 GCP 專案做，會有少量費用，每篇都寫了大約多少錢、做完怎麼刪。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-01-learning-map.png" alt="Kubernetes 教學地圖：Docker、原生 K8s、Cloud Run 與 Cloud Build、GKE 四段加一篇收尾，共 27 篇的學習順序" class="wp-image-13569" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-01-learning-map.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-01-learning-map-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-01-learning-map-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-01-learning-map-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h2 class="wp-block-heading">為什麼你需要一張學習地圖</h2>



<p class="wp-block-paragraph">Kubernetes（K8s）是自動管理一大群容器的系統，2014 年由 Google 開源，現在是雲端工作最常被要求的技能之一。網路上的 K8s 教學很多，但大多是單篇，順序要自己拼，零基礎的人最常卡在下面三個地方。</p>



<p class="wp-block-paragraph"><strong>第一個坑：跳過 Docker 直接學 K8s。</strong> K8s 的 YAML 裡寫的是映像檔名稱、Port、環境變數，這些都是 Docker 的觀念。沒做過 <code>docker build</code>、<code>docker run</code>，看 K8s 的 Pod 定義會像在看天書。</p>



<p class="wp-block-paragraph"><strong>第二個坑：一開始就上雲端叢集。</strong> GKE 叢集光管理費就是每小時 0.10 美元（2026 年 11 月查官方定價頁），Autopilot 叢集沒寫資源要求，每個 Pod 會被補成 0.5 vCPU、2 GiB 來計費。先在免費的 Minikube 把觀念練熟，上雲端時只要學「哪裡不一樣」。</p>



<p class="wp-block-paragraph"><strong>第三個坑：照著過時的教學做。</strong> 這個系列查證時就碰到好幾個：Container Registry 已在 2025 年 3 月 18 日關閉、ingress-nginx 在 2026 年 3 月退場、<code>docker-compose</code>（v1）早就不維護。照舊教學打指令，不是報錯就是做出已經不建議的架構。</p>



<p class="wp-block-paragraph">這張地圖的順序就是為了避開這三個坑：先 Docker、再原生 K8s、最後才上 GCP，每一段都用前一段做出來的東西接著練。</p>



<h2 class="wp-block-heading">先認識 10 個名詞：一張表看懂</h2>



<p class="wp-block-paragraph">整個系列會反覆出現下面這些名詞。每個名詞第一次正式教的篇目，都有更完整的白話解釋和實作。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話是什麼</th><th>生活比喻</th><th>來龍去脈、為什麼要學</th><th>詳細在</th></tr></thead><tbody><tr><td>容器（Container）</td><td>容器是把程式和它需要的環境打包在一起、可以獨立執行的單位</td><td>貨櫃：裡面裝什麼都行，碼頭用同一種吊車搬</td><td>為了解決「我電腦可以跑、你電腦不行」；雲端服務幾乎都以容器為單位部署</td><td>第 1 篇</td></tr><tr><td>映像檔（Image）</td><td>映像檔是做出容器的唯讀範本</td><td>雞蛋糕模具，容器是烤出來的雞蛋糕</td><td>一份映像檔可以開很多個容器；部署到雲端，交出去的就是映像檔</td><td>第 3 篇</td></tr><tr><td>Docker</td><td>Docker 是最普及的容器工具，負責做映像檔、開容器</td><td>做模具、烤雞蛋糕的那台機器</td><td>2013 年推出後讓容器變成日常工具；後面每一段都從 Docker 做出的映像檔開始</td><td>第 1 篇</td></tr><tr><td>Dockerfile</td><td>Dockerfile 是描述映像檔怎麼做的文字檔</td><td>食譜</td><td>寫成檔案，同一份食譜誰來做結果都一樣；面試常要你看懂一份</td><td>第 4 篇</td></tr><tr><td>Kubernetes（K8s）</td><td>Kubernetes 是自動管理一大群容器的系統：開幾個、放哪台、壞了重開</td><td>碼頭調度中心</td><td>名字是希臘文「舵手」，K 和 s 中間有 8 個字母，所以簡寫 K8s；容器一多就需要它</td><td>第 9 篇</td></tr><tr><td>叢集（Cluster）</td><td>叢集是一群一起工作的機器，K8s 把它們當成一台大電腦用</td><td>整個碼頭</td><td>分成控制平面（做決定）和節點（跑容器）；GKE 收的就是「一個叢集」的管理費</td><td>第 9 篇</td></tr><tr><td>Minikube</td><td>Minikube 是在一台電腦上開迷你 K8s 叢集的練習工具</td><td>駕訓班的練習場</td><td>Cloud Shell 已經預裝，實測約 35 秒開好，免費練到熟</td><td>第 10 篇</td></tr><tr><td>Artifact Registry</td><td>Artifact Registry 是 GCP 的私人映像檔倉庫</td><td>雞蛋糕模具的倉庫</td><td>取代 2025 年 3 月關閉的 Container Registry；Cloud Run、GKE 部署前映像檔要先放這裡</td><td>第 19 篇</td></tr><tr><td>Cloud Run</td><td>Cloud Run 是交出映像檔就拿到網址的代管容器服務，沒流量時縮到 0</td><td>叫計程車：不用買車、不用顧車</td><td>不用管叢集和機器；ACE、PCA 情境題最常出現的答案之一</td><td>第 20 篇</td></tr><tr><td>GKE（Google Kubernetes Engine）</td><td>GKE 是 Google 代管的 Kubernetes</td><td>長租一台有司機的車</td><td>控制平面 Google 顧，YAML 和 <code>kubectl</code> 跟 Minikube 一樣；正式環境跑 K8s 的常見選擇</td><td>第 24 篇</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">另外兩個 IT 基礎名詞也會一直出現：<strong>Port（埠號）</strong> 是同一台機器上區分不同服務的門牌號碼，例如網頁常用 80、8080；<strong>YAML</strong> 是用縮排表示層級的設定檔格式，K8s 和 Docker Compose 都用它。</p>



<h2 class="wp-block-heading">這個系列適合誰、要花多少時間、會不會花錢</h2>



<h3 class="wp-block-heading">適合誰</h3>


<ul class="wp-block-list">
<li><strong>完全零基礎、想進雲端或 DevOps 的人</strong>：不用會 Linux，每個指令都有實際輸出可以對照，跟著貼就跑得出來</li>

<li><strong>準備 Kubernetes 證照（CKA、CKAD）的人</strong>：原生 K8s 段（第 9～18 篇）每篇都附了上機考會用到的指令</li>

<li><strong>準備 Google Cloud 證照（ACE、PCA）的人</strong>：Cloud Run、GKE 段（第 19～27 篇）每篇都整理了情境題的判斷關鍵字</li>

<li><strong>已經會 Docker、想補 K8s 和 GCP 的人</strong>：可以直接從第 9 篇開始</li>
</ul>



<h3 class="wp-block-heading">要花多少時間</h3>



<p class="wp-block-paragraph">每篇開頭都寫了「動手做大約幾分鐘」，加起來如下（不含閱讀觀念的時間）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>段落</th><th>篇數</th><th>動手做時間</th><th>在哪裡做</th></tr></thead><tbody><tr><td>Docker</td><td>第 1～8 篇，共 8 篇</td><td>每篇 10～25 分鐘，合計約 2 小時 15 分</td><td>Cloud Shell，不設專案</td></tr><tr><td>原生 Kubernetes</td><td>第 9～18 篇，共 10 篇</td><td>每篇 15～30 分鐘，合計約 3 小時 25 分</td><td>Cloud Shell＋Minikube，不設專案</td></tr><tr><td>Cloud Run 與 Cloud Build</td><td>第 19～23 篇，共 5 篇</td><td>每篇 15～60 分鐘，合計約 2 小時 25 分</td><td>自己的 GCP 專案</td></tr><tr><td>GKE</td><td>第 24～26 篇，共 3 篇</td><td>第 24、25 篇各約 30、40 分鐘，再加第 26 篇</td><td>自己的 GCP 專案</td></tr><tr><td>收尾</td><td>第 27 篇</td><td>不用動手</td><td>只要讀</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>算一次</strong>：前三段加起來約 2 小時 15 分＋3 小時 25 分＋2 小時 25 分＝8 小時 5 分，再加 GKE 段約 1 小時 10 分以上，總共大約 9～10 小時的動手時間。一天做 1 小時，大約兩週走完；一個週末各做 4 小時，大約兩個週末。時間主要花在等待：建 GKE 叢集約 6～7 分鐘、Cloud Run 縮到零要等 15 分鐘以上、HPA 縮回去要等約 5～8 分鐘。</p>



<h3 class="wp-block-heading">會不會花錢</h3>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-03-cost-map.png" alt="Kubernetes 教學會不會花錢：Docker、K8s 段在 Cloud Shell 免費，Cloud Run 段大多在免費額度內，GKE 段叢集管理費每小時 0.10 美元" class="wp-image-13570" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-03-cost-map.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-03-cost-map-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-03-cost-map-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-03-cost-map-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>段落</th><th>費用</th><th>依據</th></tr></thead><tbody><tr><td>Docker、原生 K8s（第 1～18 篇）</td><td>0 元</td><td>Cloud Shell 對有 Google 帳號的人免費，每週可用 50 小時（第 1 篇查<a href="https://cloud.google.com/shell/pricing">官方定價頁</a>）；Minikube 開在 Cloud Shell 裡，不另外收費</td></tr><tr><td>Cloud Run 與 Cloud Build（第 19～23 篇）</td><td>照著做大多是 0 元</td><td>Cloud Run 每月免費 180,000 vCPU 秒、360,000 GiB 秒、200 萬次請求；Artifact Registry 每月前 0.5 GiB 免費；Cloud Build 每月 2,500 建置分鐘免費（2026 年 11 月查 <a href="https://cloud.google.com/run/pricing">Cloud Run 定價頁</a>與各服務定價頁）。第 22 篇測最小執行個體開了約 17.5 分鐘，閒置費約 0.004 美元</td></tr><tr><td>GKE（第 24～26 篇）</td><td>第 24 篇實測 1 小時內做完刪掉，約 0.25 美元以內</td><td>叢集管理費每小時 0.10 美元，每個帳單帳戶每月有 74.40 美元免費額度可抵一個叢集；Pod 照資源要求計費，另加負載平衡器的轉送規則（2026 年 11 月查 <a href="https://cloud.google.com/kubernetes-engine/pricing">GKE 定價頁</a>）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>算一次：GKE 叢集忘了刪會怎樣？</strong> 管理費每小時 0.10 美元 × 一個月約 730 小時＝73 美元。帳單帳戶每月的 74.40 美元免費額度剛好抵掉一個叢集的管理費，所以第一個叢集忘了刪，管理費不會收；但開第二個叢集，第二個的 73 美元就要自己付。</p>



<p class="wp-block-paragraph"><strong>再算一次：Pod 有沒有寫資源要求，差很多。</strong> 第 24 篇實測，3 個 nginx 在 GKE Autopilot 沒寫資源要求，被補成每個 0.5 vCPU、2 GiB，一個月約 80.59 美元；照需要寫成 250m、512Mi，降到約 34.31 美元，少了一半以上。數字越大代表 Google 替你保留的資源越多，就算程式根本用不到也照算。</p>



<p class="wp-block-paragraph">開始做 GCP 段之前，建議先設好預算警示，做法在<a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a>。</p>



<h2 class="wp-block-heading">學習地圖：五段、27 篇怎麼接</h2>



<p class="wp-block-paragraph">整個系列用<strong>同一個網頁程式</strong>從頭做到尾：第 4 篇用 Dockerfile 把它打包成映像檔，原生 K8s 段在 Minikube 上把它跑成 Deployment，第 19 篇推上 Artifact Registry，第 20 篇部署到 Cloud Run，第 25 篇再搬上 GKE。每一段都接著用前一段做出來的東西，所以建議照順序讀。</p>



<h3 class="wp-block-heading">第一段：Docker（第 1～8 篇）</h3>



<p class="wp-block-paragraph">目標是<strong>會做映像檔、會開容器、會讓多個容器互連</strong>。從第 1 篇的 <code>docker run hello-world</code> 開始，到第 7 篇用一個 YAML 檔同時開起網站和 MySQL 資料庫，第 8 篇把 Python 映像檔從 1.64GB 瘦到 201MB。</p>



<p class="wp-block-paragraph">學完這段，你看得懂 Dockerfile、知道資料為什麼會消失、知道容器之間怎麼用名字互連。這些都是下一段 K8s YAML 裡會直接出現的欄位。</p>



<h3 class="wp-block-heading">第二段：原生 Kubernetes（第 9～18 篇）</h3>



<p class="wp-block-paragraph">目標是<strong>在 Minikube 上把 K8s 的核心物件全部操作一次</strong>：Pod、Deployment、Service、Ingress、ConfigMap、Secret、PVC、Probe、HPA，最後故意做出 5 種錯誤來練排錯。</p>



<p class="wp-block-paragraph">這段全部在免費的 Cloud Shell 做。Cloud Shell 是 Google 免費借你的一台雲端 Linux 電腦，用瀏覽器就能操作，裡面已經裝好 Docker、kubectl、Minikube。這段的指令和 CKA、CKAD 上機考用的是同一套 <code>kubectl</code>。</p>



<h3 class="wp-block-heading">第三段：Cloud Run 與 Cloud Build（第 19～23 篇）</h3>



<p class="wp-block-paragraph">目標是<strong>把映像檔放上 GCP、用最省事的方式上線</strong>。第 19 篇建 Artifact Registry 倉庫、推映像檔；第 20 篇部署到 Cloud Run，拿到 HTTPS 網址、做版本與流量分割；第 21 篇用 Cloud Build 讓建映像檔和部署自動化；第 22 篇算收費、量冷啟動；第 23 篇比較 Cloud Run 的服務、Jobs、functions。</p>



<p class="wp-block-paragraph">這段開始要用自己的 GCP 專案，專案、帳單、IAM 這些基礎不在這個系列重教，可以先看<a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a>。</p>



<h3 class="wp-block-heading">第四段：GKE（第 24～26 篇）</h3>



<p class="wp-block-paragraph">目標是<strong>把在 Minikube 練過的 K8s 搬上正式的雲端叢集</strong>。第 24 篇建 Autopilot 叢集、比較 Autopilot 和 Standard 的收費；第 25 篇把應用從 Artifact Registry 部署到 GKE，用 Gateway 對外、HPA 自動擴展；第 26 篇用 Workload Identity 讓 Pod 不放金鑰就能存取 GCP 服務。</p>



<p class="wp-block-paragraph">這段會發現 YAML 幾乎不用改，不一樣的都在叢集外面：映像檔要放網路上拿得到的倉庫、LoadBalancer 直接拿到對外 IP、節點由 Google 自動開關。</p>



<h3 class="wp-block-heading">收尾：怎麼選（第 27 篇）</h3>



<p class="wp-block-paragraph">最後一篇把 Cloud Run、GKE、Compute Engine 放在同一張表比較，並用台灣 asia-east1 的單價算三個情境：每月 300 萬次請求的小網站，Cloud Run 約 10.48 美元最便宜；24 小時不停的背景工作，Compute Engine 約 60.47 美元最便宜。這是 PCA 情境題最常考的判斷。</p>



<h2 class="wp-block-heading">27 篇重點整理表</h2>



<p class="wp-block-paragraph">下面五張表照段落排列，每篇一列：學到什麼、最關鍵的指令、實測時最值得記住的數字。已經發布的篇名可以直接點進去。</p>



<h3 class="wp-block-heading">Docker 段</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>篇</th><th>篇名</th><th>學到什麼</th><th>關鍵指令</th><th>實測亮點</th></tr></thead><tbody><tr><td>第 1 篇</td><td><a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">Docker 入門教學：不用安裝，用 Cloud Shell 跑出第一個容器</a></td><td>映像檔、容器、Registry 三個名詞；在 Cloud Shell 跑出第一個網頁</td><td><code>docker run -d -p 8080:80 nginx</code></td><td>不用安裝、不用專案，約 10 分鐘看到網頁</td></tr><tr><td>第 2 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">Docker 常用指令一次看懂：run、ps、logs、exec、stop、rm</a></td><td>6 個核心指令；stop 和 rm 的差別</td><td><code>docker logs --tail 20</code>、<code>docker exec -it</code></td><td>臨時容器加 <code>--rm</code> 跑完自動清掉</td></tr><tr><td>第 3 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-image-vs-container-layer-tag/">Docker 映像檔和容器差在哪？Image、Layer、Tag 白話解釋</a></td><td>映像檔是一疊唯讀的層；Tag 和 Digest</td><td><code>docker history</code>、<code>docker pull</code></td><td>共用層省下約 117MB；<code>latest</code> 是 1.31.8、<code>stable</code> 是 1.30.6，latest 不等於最穩</td></tr><tr><td>第 4 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/dockerfile-tutorial-build-first-image/">Dockerfile 怎麼寫？從零打包你的第一個網頁映像檔</a></td><td>FROM、COPY、RUN、CMD；指令順序影響建置速度</td><td><code>docker build -t 名稱:Tag .</code></td><td>改一行程式重建 0.94 秒 vs 6.96 秒；加 <code>--init</code> 停容器 0.19 秒 vs 10 秒</td></tr><tr><td>第 5 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-volume-vs-bind-mount/">Docker 資料會消失？Volume 和 Bind Mount 怎麼選</a></td><td>Volume、Bind Mount、tmpfs 三種存法</td><td><code>docker volume create</code>、<code>-v</code></td><td>空的 Bind Mount 蓋住原檔案，網頁直接 403</td></tr><tr><td>第 6 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-network-container-communication-flask-mysql/">容器之間怎麼連線？Docker Network 與 Port 對應實作</a></td><td>自訂網路用容器名稱互連；Port 對應</td><td><code>docker network create</code>、<code>--network</code></td><td>PyMySQL 連 MySQL 8 要多裝 <code>cryptography</code></td></tr><tr><td>第 7 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-compose-tutorial-flask-mysql/">Docker Compose 教學：一個 YAML 開起網站＋資料庫</a></td><td>一個 YAML 管多個容器；等資料庫健康再啟動</td><td><code>docker compose up -d</code>、<code>down -v</code></td><td>資料庫 6.0 秒 Healthy 後，網站 6.2 秒才啟動</td></tr><tr><td>第 8 篇</td><td><a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">映像檔太肥怎麼辦？Docker 多階段建置與 .dockerignore</a></td><td>slim 基底、多階段建置、.dockerignore</td><td><code>COPY --from=builder</code></td><td>1.64GB 瘦到 201MB；送進建置的資料從 209.77MB 變 187B</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">原生 Kubernetes 段</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>篇</th><th>篇名</th><th>學到什麼</th><th>關鍵指令</th><th>實測亮點</th></tr></thead><tbody><tr><td>第 9 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a></td><td>控制平面與節點各有哪些元件、一個 Pod 怎麼被建出來</td><td><code>kubectl get pods -n kube-system</code></td><td>拿掉排程器，新 Pod 卡 Pending、舊的照跑，放回去 45 秒內恢復</td></tr><tr><td>第 10 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></td><td>Minikube 和 kind、k3s、GKE 的差別；kubectl 10 個指令</td><td><code>minikube start</code>、<code>kubectl get</code></td><td>新建 34.8 秒、關機 6.1 秒、重開 13.5 秒</td></tr><tr><td>第 11 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a></td><td>YAML 四大塊；宣告式的 apply</td><td><code>kubectl apply -f pod.yaml</code></td><td>改 Pod 的 Port 被 Forbidden；刪除 nginx 0.72 秒、sleep 30.9 秒</td></tr><tr><td>第 12 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></td><td>Deployment、ReplicaSet、Pod 三層；maxSurge 計算</td><td><code>kubectl rollout undo</code></td><td>刪一個 Pod 1 秒補回；3 個副本換版時最多 4 個、至少 3 個可用</td></tr><tr><td>第 13 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a></td><td>三種 Service 一層包一層；叢集內 DNS</td><td><code>kubectl expose</code>、<code>minikube tunnel</code></td><td>Cloud Shell 的 Minikube 要加 <code>--cni=kindnet</code>，不然 Pod 連 Service 不通</td></tr><tr><td>第 14 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">Ingress 是什麼？用網址路徑把流量分給不同服務（含 Gateway API）</a></td><td>Ingress 規則與控制器；Gateway API 三個角色</td><td><code>minikube addons enable ingress</code></td><td>沒有規則的 <code>/</code> 回 404；ingress-nginx 2026 年 3 月退場</td></tr><tr><td>第 15 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</a></td><td>環境變數和檔案兩種給法；Secret 不是加密</td><td><code>kubectl create secret generic</code></td><td>檔案約 85 秒自動更新，環境變數要重啟才生效</td></tr><tr><td>第 16 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a></td><td>emptyDir、PV、PVC、StorageClass</td><td><code>kubectl get pvc</code></td><td>5 秒內 Bound；刪 PVC 後 PV 連資料一起消失</td></tr><tr><td>第 17 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">健康檢查與自動擴展：Probe、資源限制、HPA</a></td><td>三種 Probe；requests、limits；HPA 公式</td><td><code>kubectl autoscale --cpu=50%</code></td><td>壓力測試從 1 個 Pod 擴到 7 個，約 5 分鐘縮回</td></tr><tr><td>第 18 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/k8s-pod-troubleshooting-crashloopbackoff/">Pod 起不來怎麼辦？CrashLoopBackOff、ImagePullBackOff、Pending 排錯</a></td><td>get、describe、logs 三步驟；Exit Code 意思</td><td><code>kubectl logs --previous</code></td><td>故意做出 5 種錯誤，Exit Code 137 是被 OOMKilled</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Cloud Run 與 Cloud Build 段</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>篇</th><th>篇名</th><th>學到什麼</th><th>關鍵指令</th><th>實測亮點</th></tr></thead><tbody><tr><td>第 19 篇</td><td><a href="https://dongdonggcp.com/2025/07/20/artifact-registry-tutorials/">Artifact Registry 是什麼？把 Docker 映像檔推上 GCP 教學</a></td><td>映像檔名稱就是地址；建倉庫、推、拉</td><td><code>docker push</code>、<code>gcloud artifacts repositories create</code></td><td>推送 1.9 秒；兩個版本共用片段只算一份</td></tr><tr><td>第 20 篇</td><td><a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a></td><td>服務與修訂版本；流量分割、回滾</td><td><code>gcloud run deploy</code>、<code>--to-revisions</code></td><td>11.7 秒拿到 HTTPS 網址；流量 50/50 實際打 10 次是 6:4</td></tr><tr><td>第 21 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">Cloud Build 是什麼？用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run</a></td><td>cloudbuild.yaml 三步；服務帳戶最小權限</td><td><code>gcloud builds submit</code></td><td><code>--tag</code> 26 秒、建置加部署 1 分 5 秒；新服務預設回 403</td></tr><tr><td>第 22 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/cloud-run-pricing-cold-start-min-instances/">Cloud Run 收費怎麼算？Cloud Run pricing、冷啟動、最小執行個體一次看懂</a></td><td>兩種計費方式與分界；冷啟動；並行數</td><td><code>gcloud run services update --min</code></td><td>冷啟動 0.947 秒、熱請求 0.04 秒；留一台最小執行個體一個月約 9.72 美元</td></tr><tr><td>第 23 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/cloud-run-jobs-vs-services-functions/">Cloud Run Jobs 是什麼？服務、Jobs、functions 差在哪、怎麼選</a></td><td>跑完就結束的工作；task 分工與重試</td><td><code>gcloud run jobs execute</code></td><td>用 <code>CLOUD_RUN_TASK_INDEX</code> 把 9 個檔案分給 3 個 task</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">GKE 段</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>篇</th><th>篇名</th><th>學到什麼</th><th>關鍵指令</th><th>實測亮點</th></tr></thead><tbody><tr><td>第 24 篇</td><td><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></td><td>Autopilot 和 Standard 誰管節點、照什麼收錢</td><td><code>gcloud container clusters create-auto</code></td><td>建叢集 6 分 31 秒；沒寫 requests 被補成 500m、2Gi</td></tr><tr><td>第 25 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a></td><td>從 Cloud Build 到 GKE 的 5 站；LoadBalancer 和 Gateway</td><td><code>kubectl get gateway</code>、<code>kubectl autoscale --cpu=50%</code></td><td>LoadBalancer 46.7 秒拿到 IP、Gateway 約 4 分鐘才能連；HPA 30 秒內 2 個擴到 4 個</td></tr><tr><td>第 26 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務</a></td><td>為什麼不要把服務帳戶金鑰放進容器；Pod 用自己的身分讀 Cloud Storage</td><td><code>kubectl create serviceaccount</code>、<code>gcloud storage buckets add-iam-policy-binding</code></td><td>有綁的 Pod 讀得到、沒綁的 403；權杖約 3,500 秒（不到 1 小時）就失效；刪叢集 5 分 54 秒</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">收尾</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>篇</th><th>篇名</th><th>學到什麼</th><th>關鍵依據</th><th>實測亮點</th></tr></thead><tbody><tr><td>第 27 篇</td><td><a href="https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/">Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</a></td><td>控制權、計費、冷啟動、GPU 一張表比較；判斷流程</td><td>前 26 篇的實測數字</td><td>小網站 Cloud Run 約 10.48 美元、GKE Autopilot 約 59.42 美元、Compute Engine 約 60.47 美元</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">同一個觀念，在 Minikube 和 GCP 上各叫什麼</h2>



<p class="wp-block-paragraph">在 Minikube 練過的觀念，到了 GCP 大多有對應的代管服務。這張表是第 9～26 篇的對照，搬上雲端時看這張就知道要換什麼：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>觀念</th><th>在 Docker／Minikube 怎麼做</th><th>在 GCP 上</th><th>在哪篇</th></tr></thead><tbody><tr><td>放映像檔</td><td>本機 <code>docker images</code>，或 Docker Hub</td><td>Artifact Registry</td><td>第 19 篇</td></tr><tr><td>建映像檔</td><td>本機 <code>docker build</code></td><td>Cloud Build</td><td>第 21 篇</td></tr><tr><td>跑一個容器服務</td><td><code>docker run -p</code></td><td>Cloud Run</td><td>第 20 篇</td></tr><tr><td>跑做完就結束的工作</td><td><code>docker run --rm</code></td><td>Cloud Run Jobs</td><td>第 23 篇</td></tr><tr><td>K8s 叢集</td><td><code>minikube start</code></td><td>GKE（Autopilot 或 Standard）</td><td>第 24 篇</td></tr><tr><td>對外網址</td><td><code>minikube tunnel</code>＋LoadBalancer</td><td>GKE 的外部負載平衡器（直接拿到 IP）</td><td>第 25 篇</td></tr><tr><td>依路徑分流</td><td>Minikube ingress 外掛</td><td>GKE Gateway</td><td>第 14、25 篇</td></tr><tr><td>自動擴展</td><td>HPA＋metrics-server 外掛</td><td>GKE 的 HPA（指標內建）、Cloud Run 內建擴展</td><td>第 17、25 篇</td></tr><tr><td>密碼</td><td>Secret（base64，不是加密）</td><td>Secret Manager</td><td>第 15 篇</td></tr><tr><td>存資料</td><td>PVC（Minikube 的本機空間）</td><td>PVC（一顆要錢的雲端硬碟）</td><td>第 16 篇</td></tr><tr><td>存取雲端服務的身分</td><td>金鑰檔放進容器（不建議）</td><td>Workload Identity</td><td>第 26 篇</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">27 篇實測下來，最容易踩的 8 個坑</h2>



<p class="wp-block-paragraph">這些都是實際跑的時候碰到、跟官方文件或網路教學不一樣的地方，每一個在該篇都有完整的原因和修法：</p>


<ol class="wp-block-list">
<li><strong>Cloud Shell 的 Minikube 預設網路外掛會讓 Pod 連不到 Service</strong>：Cloud Shell 的核心沒有 <code>br_netfilter</code> 模組，啟動時加 <code>minikube start --cni=kindnet</code> 就好（第 13 篇）</li>

<li><strong><code>latest</code> 不等於最新</strong>：實測同一個映像檔 <code>latest</code> 是 1.31.8、<code>stable</code> 是 1.30.6，要鎖版本用 Digest（第 3 篇）</li>

<li><strong>容器停下來要等 10 秒</strong>：程式當 PID 1 不理會停止訊號，<code>docker stop</code> 等滿 10 秒才強制結束；加 <code>--init</code> 實測 0.19 秒（第 4 篇）</li>

<li><strong>空的 Bind Mount 會蓋掉原本的檔案</strong>：掛上一個空資料夾，nginx 的網頁直接變 403（第 5 篇）</li>

<li><strong>Secret 不是加密</strong>：base64 一行指令就還原，正式環境要限制權限或改用 Secret Manager（第 15 篇）</li>

<li><strong>Autopilot 不寫資源要求會被補成 500m、2Gi</strong>：3 個 nginx 一個月從約 34.31 美元變約 80.59 美元（第 24 篇）</li>

<li><strong><code>gcloud run deploy --source</code> 預設把映像檔推到另一個倉庫</strong>：加 <code>--image</code> 才會放進你指定的 Artifact Registry 倉庫（第 20 篇）</li>

<li><strong>Cloud Build 部署出來的新服務預設要驗證</strong>：直接開網址回 403，要由有權限的人決定要不要公開（第 21 篇）</li>
</ol>



<h2 class="wp-block-heading">2026 年的新舊對照：看到舊教學這樣寫就是過時了</h2>



<p class="wp-block-paragraph">這個系列每篇寫之前都查了官方文件，下面是查到已經改名、退場或棄用的寫法（2026 年 11 月查證）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>舊寫法或舊名稱</th><th>現在</th><th>在哪篇</th></tr></thead><tbody><tr><td><code>docker-compose</code>（v1，Python 版）</td><td><code>docker compose</code>（外掛，Cloud Shell 實測 v5.7.1），新專案檔名用 <code>compose.yaml</code></td><td>第 7 篇</td></tr><tr><td>Container Registry（<code>gcr.io/專案</code>）</td><td>2025 年 3 月 18 日已關閉，改用 Artifact Registry</td><td>第 19 篇</td></tr><tr><td>ingress-nginx 控制器</td><td>2026 年 3 月退場，Ingress API 凍結，官方建議改用 Gateway API</td><td>第 14 篇</td></tr><tr><td><code>kubectl rollout ... --record</code></td><td>已棄用，改用 annotate 寫 change-cause</td><td>第 12 篇</td></tr><tr><td><code>kubectl get endpoints</code></td><td>v1 Endpoints 從 1.33 起棄用，改看 EndpointSlice</td><td>第 13 篇</td></tr><tr><td><code>kubectl autoscale --cpu-percent=50</code></td><td>改寫成 <code>--cpu=50%</code></td><td>第 17 篇</td></tr><tr><td>Cloud Build 舊的預設服務帳戶</td><td>2024 年起新專案改用 Compute Engine 預設服務帳戶</td><td>第 21 篇</td></tr><tr><td>Cloud Source Repositories</td><td>不再開放新客戶，改接 GitHub 等外部倉庫</td><td>第 21 篇</td></tr><tr><td>Cloud Run「CPU always allocated」</td><td>改名「以執行個體計費」</td><td>第 22 篇</td></tr><tr><td>Cloud Functions（2nd gen）</td><td>改名 Cloud Run functions，官方改推 <code>gcloud run deploy --function</code></td><td>第 23 篇</td></tr><tr><td>Minikube 預設 Docker 執行環境</td><td>v1.39.0 起預設 containerd（Cloud Shell 預裝的還是 v1.38.1）</td><td>第 10 篇</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">三種讀者的建議路線</h2>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-02-reader-paths.png" alt="Kubernetes 教學三種路線：零基礎照順序讀 27 篇、考 CKA／CKAD 主攻第 9～18 篇、考 ACE／PCA 或轉職雲端主攻第 19～27 篇" class="wp-image-13571" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-02-reader-paths.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-02-reader-paths-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-02-reader-paths-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct28-cards-02-reader-paths-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">完全零基礎：照順序走完 27 篇</h3>


<ol class="wp-block-list">
<li><strong>第 1～8 篇（Docker）</strong>：一天一篇，每篇做完把容器清掉再進下一篇</li>

<li><strong>第 9～18 篇（原生 K8s）</strong>：第 10 篇開好 Minikube 後，之後每篇接著用；卡住先翻第 18 篇的排錯三步驟</li>

<li><strong>第 19～23 篇（Cloud Run）</strong>：開始用自己的專案，先設預算警示</li>

<li><strong>第 24～26 篇（GKE）</strong>：建議排在同一天連續做，做完當天刪叢集，管理費最多只算幾個小時</li>

<li><strong>第 27 篇</strong>：回頭把三種服務放在一起想一次</li>
</ol>



<h3 class="wp-block-heading">要考 CKA、CKAD：主攻第 9～18 篇</h3>



<p class="wp-block-paragraph">CKA、CKAD 都是上機實作考，給你真的叢集，2 小時內用 <code>kubectl</code> 把題目做完。原生 K8s 段對應的考試範圍如下（比重是 2026 年 11 月查 Linux Foundation 官方頁）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考試範圍</th><th>比重</th><th>先讀哪幾篇</th></tr></thead><tbody><tr><td>CKA：排錯（Troubleshooting）</td><td>30%</td><td>第 18 篇，再回頭看第 9 篇的元件分工</td></tr><tr><td>CKA：叢集架構、安裝與設定（Cluster Architecture, Installation &amp; Configuration）</td><td>25%</td><td>第 9、10 篇（用 kubeadm 裝叢集、RBAC 這個系列沒完整教，要另外補）</td></tr><tr><td>CKA：服務與網路（Services &amp; Networking）</td><td>20%</td><td>第 13、14 篇</td></tr><tr><td>CKA：工作負載與排程（Workloads &amp; Scheduling）</td><td>15%</td><td>第 11、12、17 篇</td></tr><tr><td>CKA：儲存（Storage）</td><td>10%</td><td>第 16 篇</td></tr><tr><td>CKAD：應用環境、設定與安全（Application Environment, Configuration and Security）</td><td>25%</td><td>第 15、17 篇</td></tr><tr><td>CKAD：應用設計與建置（Application Design and Build）</td><td>20%</td><td>第 4、8、11 篇</td></tr><tr><td>CKAD：應用部署（Application Deployment）</td><td>20%</td><td>第 12 篇（Helm、Kustomize 這個系列沒完整教）</td></tr><tr><td>CKAD：服務與網路（Services and Networking）</td><td>20%</td><td>第 13、14 篇</td></tr><tr><td>CKAD：應用觀測與維護（Application Observability and Maintenance）</td><td>15%</td><td>第 17、18 篇</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>誠實說明</strong>：這個系列的目標是零基礎能跟著做，不是考試題庫。RBAC、NetworkPolicy、Helm、Kustomize、用 kubeadm 裝叢集、etcd 備份這些考試範圍，系列裡只帶過或沒有教，準備考試要另外補。</p>



<h3 class="wp-block-heading">要考 ACE、PCA，或想轉職雲端：主攻第 19～27 篇</h3>



<p class="wp-block-paragraph">ACE、PCA 是情境選擇題，不考你打指令，考的是「這個需求該用哪個服務」。建議先快速讀第 1、4 篇（知道映像檔怎麼來）、第 9、12、13 篇（知道 K8s 在做什麼），然後把第 19～27 篇全部做一次，最後用第 27 篇的判斷流程練情境題。</p>



<p class="wp-block-paragraph">想轉職雲端工程師或 DevOps，面試官最常問的也是這段：「為什麼選 Cloud Run 不選 GKE」「怎麼讓部署自動化」。職缺怎麼分可以看<a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析</a>。</p>



<h2 class="wp-block-heading">用完記得刪：全系列檢查清單</h2>



<p class="wp-block-paragraph">這篇沒有建任何資源，但走完整個系列後，用下面的指令確認沒有東西還在跑。Cloud Shell 裡的 Minikube 不收費，GCP 專案裡的資源才會計費：</p>



<pre class="wp-block-code"><code>minikube delete
gcloud run services list --project 你的專案ID
gcloud run jobs list --project 你的專案ID
gcloud container clusters list --project 你的專案ID
gcloud artifacts repositories list --project 你的專案ID
gcloud compute forwarding-rules list --project 你的專案ID</code></pre>



<p class="wp-block-paragraph"><code>minikube delete</code> 會把 Cloud Shell 裡的練習叢集整個刪掉；後面五行只要有列出你在系列裡建的資源，就照各篇「用完記得刪」那段刪掉。最容易忘的是 GKE 叢集和負載平衡器的轉送規則，兩個都是開著就照小時計費。</p>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">CKA、CKAD：上機實作考</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>項目</th><th>CKA</th><th>CKAD</th></tr></thead><tbody><tr><td>考什麼</td><td>叢集管理者：建置、網路、儲存、排錯</td><td>應用開發者：設計、部署、設定、觀測</td></tr><tr><td>形式</td><td>線上監考、命令列實作</td><td>線上監考、命令列實作</td></tr><tr><td>時間</td><td>2 小時</td><td>2 小時</td></tr><tr><td>費用（單買考試）</td><td>445 美元</td><td>445 美元</td></tr><tr><td>依據版本</td><td>Kubernetes v1.37</td><td>Kubernetes v1.37</td></tr><tr><td>效期</td><td>2 年</td><td>2 年</td></tr><tr><td>其他</td><td>含 1 次補考、2 次模擬考（每次 36 小時）、購買後 12 個月內要考</td><td>同左</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">（2026 年 11 月查 <a href="https://training.linuxfoundation.org/certification/certified-kubernetes-administrator-cka/">CKA 官方頁</a>、<a href="https://training.linuxfoundation.org/certification/certified-kubernetes-application-developer-ckad/">CKAD 官方頁</a>）</p>



<p class="wp-block-paragraph">上機考最缺的是時間，不是觀念。第 10 篇的 kubectl 10 個指令、第 11 篇用 <code>--dry-run=client -o yaml</code> 產生 YAML 草稿、第 18 篇的排錯三步驟，都是考試現場最常用的手法。</p>



<h3 class="wp-block-heading">ACE、PCA：情境選擇題</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>項目</th><th>Associate Cloud Engineer（ACE）</th><th>Professional Cloud Architect（PCA）</th></tr></thead><tbody><tr><td>形式</td><td>50～60 題單選和複選</td><td>50～60 題單選和複選，含 2 個案例情境</td></tr><tr><td>時間</td><td>2 小時</td><td>2 小時</td></tr><tr><td>報名費</td><td>125 美元</td><td>200 美元</td></tr><tr><td>語言</td><td>英文、日文、西班牙文、葡萄牙文</td><td>英文、日文</td></tr><tr><td>效期</td><td>3 年</td><td>2 年</td></tr><tr><td>建議經驗</td><td>6 個月以上 Google Cloud 實作</td><td>3 年以上業界經驗，其中 1 年以上用 Google Cloud 設計方案</td></tr><tr><td>續證考試</td><td>1 小時、20 題、75 美元</td><td>1 小時、25 題、100 美元</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">（2026 年 11 月查 <a href="https://cloud.google.com/learn/certification/cloud-engineer">ACE 官方考試頁</a>、<a href="https://cloud.google.com/learn/certification/cloud-architect">PCA 官方考試頁</a>）</p>



<p class="wp-block-paragraph">情境題看到這些字，就想到對應的服務：「無狀態、沒流量時不想付錢」想到 Cloud Run；「做完就結束、排程執行」想到 Cloud Run Jobs；「已經有 K8s YAML、多個服務互相呼叫」想到 GKE；「指定作業系統、要改核心」想到 Compute Engine；「Pod 存取 Cloud Storage 不要用金鑰」想到 Workload Identity。PCA 怎麼準備可以看<a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照（PCA）怎麼準備</a>。</p>



<h3 class="wp-block-heading">面試最常問的 8 題，答案在哪一篇</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>面試題</th><th>答案在</th></tr></thead><tbody><tr><td>映像檔和容器差在哪？</td><td>第 3 篇</td></tr><tr><td>怎麼讓映像檔變小？</td><td>第 8 篇</td></tr><tr><td>K8s 的控制平面有哪些元件？</td><td>第 9 篇</td></tr><tr><td>Pod 和 Deployment 差在哪？</td><td>第 11、12 篇</td></tr><tr><td>ClusterIP、NodePort、LoadBalancer 差在哪？</td><td>第 13 篇</td></tr><tr><td>Pod 一直 CrashLoopBackOff 怎麼查？</td><td>第 18 篇</td></tr><tr><td>HPA 怎麼算要開幾個 Pod？</td><td>第 17 篇</td></tr><tr><td>Cloud Run 和 GKE 怎麼選？</td><td>第 27 篇</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Kubernetes 教學要從哪裡開始？</h3>



<p class="wp-block-paragraph">從 Docker 開始。Kubernetes 管的是容器，YAML 裡寫的映像檔、Port、環境變數都是 Docker 的觀念，先用第 1～8 篇約 2 小時 15 分的動手時間學會做映像檔、開容器，再從第 9 篇開始學 K8s 會順很多。</p>



<h3 class="wp-block-heading">k8s 教學和 kubernetes 教學一樣嗎？</h3>



<p class="wp-block-paragraph">一樣。K8s 是 Kubernetes 的縮寫，K 和 s 中間剛好有 8 個字母，所以寫成 K8s。Kubernetes 這個名字來自希臘文的「舵手」，2014 年由 Google 開源。搜尋時兩個說法都會找到同一類教學。</p>



<h3 class="wp-block-heading">沒有自己的電腦環境，可以學 Kubernetes 嗎？</h3>



<p class="wp-block-paragraph">可以。這個系列的 Docker 和 K8s 段全部在 Google Cloud Shell 做，只要有 Google 帳號和瀏覽器，不用設專案、不用綁信用卡。Cloud Shell 已經預裝 Docker、kubectl、Minikube，實測開好一個 Minikube 叢集約 35 秒，每週可用 50 小時。</p>



<h3 class="wp-block-heading">學完這個系列要花多少錢？</h3>



<p class="wp-block-paragraph">前 18 篇是 0 元。Cloud Run 段大多在每月免費額度內，第 22 篇測最小執行個體約 17.5 分鐘，閒置費約 0.004 美元。GKE 段做完當天刪叢集，第 24 篇實測 1 小時內做完約 0.25 美元以內；叢集管理費每小時 0.10 美元，每月有 74.40 美元免費額度可以抵一個叢集（2026 年 11 月查官方定價頁）。</p>



<h3 class="wp-block-heading">在 Minikube 學的東西，到 GKE 還能用嗎？</h3>



<p class="wp-block-paragraph">能。Deployment、Service、HPA 的 YAML 幾乎不用改，<code>kubectl</code> 指令也一樣。第 25 篇實測把應用從 Minikube 搬上 GKE，不一樣的都在叢集外面：映像檔要放 Artifact Registry、LoadBalancer 直接拿到對外 IP（實測 46.7 秒）、依路徑分流從 Ingress 換成 Gateway、節點由 Google 自動開。</p>



<h3 class="wp-block-heading">CKA 和 CKAD 要先考哪一個？</h3>



<p class="wp-block-paragraph">看你的工作方向。CKAD 偏應用開發，比重最大的是設定與安全（25%）；CKA 偏叢集管理，比重最大的是排錯（30%）。兩張都是 2 小時上機考、445 美元、效期 2 年（2026 年 11 月查官方頁）。這個系列的第 9～18 篇兩張都用得到，但 RBAC、NetworkPolicy、Helm 要另外補。</p>



<h3 class="wp-block-heading">一定要學 Kubernetes 嗎？Cloud Run 不夠用嗎？</h3>



<p class="wp-block-paragraph">很多專案 Cloud Run 就夠了。第 27 篇用台灣價格算過，每月 300 萬次請求的小網站，Cloud Run 約 10.48 美元，GKE Autopilot 約 59.42 美元。但多個服務互相呼叫、需要永久磁碟、團隊已經在用 K8s 的情況，GKE 比較合適；而且 K8s 是雲端與 DevOps 職缺常列的技能，<a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼</a>這篇有判斷你需不需要它的方法。</p>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>Kubernetes 教學的順序</strong>：Docker（第 1～8 篇）→ 原生 K8s（第 9～18 篇）→ Cloud Run 與 Cloud Build（第 19～23 篇）→ GKE（第 24～26 篇）→ 怎麼選（第 27 篇）</li>

<li><strong>時間</strong>：動手時間合計約 9～10 小時，前 18 篇在 Cloud Shell 免費做，不用安裝、不用綁卡</li>

<li><strong>花費</strong>：Cloud Run 段大多在免費額度內；GKE 叢集管理費每小時 0.10 美元，每月 74.40 美元免費額度抵一個叢集，做完當天刪</li>

<li><strong>證照</strong>：CKA、CKAD 主攻第 9～18 篇（上機考，445 美元）；ACE、PCA 主攻第 19～27 篇（情境選擇題，125、200 美元）</li>

<li><strong>最常踩的坑</strong>：Cloud Shell 的 Minikube 要加 <code>--cni=kindnet</code>、Autopilot 要寫資源要求、看到 <code>gcr.io</code> 和 ingress-nginx 的教學就是舊的</li>
</ul>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列全部 27 篇</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">Docker 入門教學：不用安裝，用 Cloud Shell 跑出第一個容器</a></li>

<li>第 2 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">Docker 常用指令一次看懂：run、ps、logs、exec、stop、rm</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-image-vs-container-layer-tag/">Docker 映像檔和容器差在哪？Image、Layer、Tag 白話解釋</a></li>

<li>第 4 篇：<a href="https://dongdonggcp.com/2026/11/18/dockerfile-tutorial-build-first-image/">Dockerfile 怎麼寫？從零打包你的第一個網頁映像檔</a></li>

<li>第 5 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-volume-vs-bind-mount/">Docker 資料會消失？Volume 和 Bind Mount 怎麼選</a></li>

<li>第 6 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-network-container-communication-flask-mysql/">容器之間怎麼連線？Docker Network 與 Port 對應實作</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-compose-tutorial-flask-mysql/">Docker Compose 教學：一個 YAML 開起網站＋資料庫</a></li>

<li>第 8 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">映像檔太肥怎麼辦？Docker 多階段建置與 .dockerignore</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a></li>

<li>第 14 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">Ingress 是什麼？用網址路徑把流量分給不同服務（含 Gateway API）</a></li>

<li>第 15 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</a></li>

<li>第 16 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a></li>

<li>第 17 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">健康檢查與自動擴展：Probe、資源限制、HPA</a></li>

<li>第 18 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-troubleshooting-crashloopbackoff/">Pod 起不來怎麼辦？CrashLoopBackOff、ImagePullBackOff、Pending 排錯</a></li>

<li>第 19 篇：<a href="https://dongdonggcp.com/2025/07/20/artifact-registry-tutorials/">Artifact Registry 是什麼？把 Docker 映像檔推上 GCP 教學</a></li>

<li>第 20 篇：<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a></li>

<li>第 21 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">Cloud Build 是什麼？用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run</a></li>

<li>第 22 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-run-pricing-cold-start-min-instances/">Cloud Run 收費怎麼算？Cloud Run pricing、冷啟動、最小執行個體一次看懂</a></li>

<li>第 23 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-run-jobs-vs-services-functions/">Cloud Run Jobs 是什麼？服務、Jobs、functions 差在哪、怎麼選</a></li>

<li>第 24 篇：<a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li>第 25 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a></li>

<li>第 26 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務</a></li>

<li>上一篇：第 27 篇：<a href="https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/">Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</a></li>
</ul>



<p class="wp-block-paragraph"><strong>觀念文（先讀這兩篇再開始也可以）</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器（Container）技術是什麼？從零開始看懂 Docker 與容器化應用</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>
</ul>



<p class="wp-block-paragraph"><strong>學完之後的下一步</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/12/02/gke-what-is-helm-charts-what-is-oci-charts/">Helm Charts 是什麼？什麼是 OCI Charts</a></li>

<li><a href="https://dongdonggcp.com/2024/12/02/what-is-gitops-methodolity-what-is-gitops-process/">GitOps 是什麼？方法論與流程</a></li>

<li><a href="https://dongdonggcp.com/2025/04/27/gcp-learning-roadmap/">GCP 學習路徑 Roadmap</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/t-career-change-beginners-guide-cloud-technology/">轉職 IT 新手必學知識完整指南</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析：雲端工程師、架構師、SRE、DevOps 差在哪</a></li>

<li><a href="https://dongdonggcp.com/2025/01/13/how-to-prepare-google-cloud-architect-exam/">雲端架構師證照（PCA）怎麼準備</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">這張地圖從第一個 <code>docker run</code> 一路走到 GKE，跟著做完就有一整套能放進履歷的實作。可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Kubernetes 教學要從哪裡開始？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "從 Docker 開始。Kubernetes 管的是容器，YAML 裡寫的映像檔、Port、環境變數都是 Docker 的觀念，先用第 1～8 篇約 2 小時 15 分的動手時間學會做映像檔、開容器，再從第 9 篇開始學 K8s 會順很多。"
      }
    },
    {
      "@type": "Question",
      "name": "k8s 教學和 kubernetes 教學一樣嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "一樣。K8s 是 Kubernetes 的縮寫，K 和 s 中間剛好有 8 個字母，所以寫成 K8s。Kubernetes 這個名字來自希臘文的「舵手」，2014 年由 Google 開源。搜尋時兩個說法都會找到同一類教學。"
      }
    },
    {
      "@type": "Question",
      "name": "沒有自己的電腦環境，可以學 Kubernetes 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以。這個系列的 Docker 和 K8s 段全部在 Google Cloud Shell 做，只要有 Google 帳號和瀏覽器，不用設專案、不用綁信用卡。Cloud Shell 已經預裝 Docker、kubectl、Minikube，實測開好一個 Minikube 叢集約 35 秒，每週可用 50 小時。"
      }
    },
    {
      "@type": "Question",
      "name": "學完這個系列要花多少錢？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "前 18 篇是 0 元。Cloud Run 段大多在每月免費額度內，第 22 篇測最小執行個體約 17.5 分鐘，閒置費約 0.004 美元。GKE 段做完當天刪叢集，第 24 篇實測 1 小時內做完約 0.25 美元以內；叢集管理費每小時 0.10 美元，每月有 74.40 美元免費額度可以抵一個叢集（2026 年 11 月查官方定價頁）。"
      }
    },
    {
      "@type": "Question",
      "name": "在 Minikube 學的東西，到 GKE 還能用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "能。Deployment、Service、HPA 的 YAML 幾乎不用改，`kubectl` 指令也一樣。第 25 篇實測把應用從 Minikube 搬上 GKE，不一樣的都在叢集外面：映像檔要放 Artifact Registry、LoadBalancer 直接拿到對外 IP（實測 46.7 秒）、依路徑分流從 Ingress 換成 Gateway、節點由 Google 自動開。"
      }
    },
    {
      "@type": "Question",
      "name": "CKA 和 CKAD 要先考哪一個？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "看你的工作方向。CKAD 偏應用開發，比重最大的是設定與安全（25%）；CKA 偏叢集管理，比重最大的是排錯（30%）。兩張都是 2 小時上機考、445 美元、效期 2 年（2026 年 11 月查官方頁）。這個系列的第 9～18 篇兩張都用得到，但 RBAC、NetworkPolicy、Helm 要另外補。"
      }
    },
    {
      "@type": "Question",
      "name": "一定要學 Kubernetes 嗎？Cloud Run 不夠用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "很多專案 Cloud Run 就夠了。第 27 篇用台灣價格算過，每月 300 萬次請求的小網站，Cloud Run 約 10.48 美元，GKE Autopilot 約 59.42 美元。但多個服務互相呼叫、需要永久磁碟、團隊已經在用 K8s 的情況，GKE 比較合適；而且 K8s 是雲端與 DevOps 職缺常列的技能，[Kubernetes 是什麼](https://dongdonggcp.com/2026/07/21/what-is-kubernetes/)這篇有判斷你需不需要它的方法。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/">Docker、Kubernetes 教學地圖：從容器到 Cloud Run、GKE 全系列整理</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-volume-pv-pvc</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:33:41 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13341</guid>

					<description><![CDATA[<p>K8s 資料怎麼保存？Cloud Shell 實測 emptyDir 和 PVC：容器重開、Pod 重建、刪 Deployment、刪 PVC 資料還在不在；RWO 兩個 Pod 都能寫，Delete 政策會連資料刪掉。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>K8s 資料怎麼保存：暫存用 emptyDir，要長久保存就開一張 PVC 申請單，叢集自動配一個 PV，Pod 刪了資料還在。</strong></p>



<p class="wp-block-paragraph">容器裡寫的檔案，容器一重建就不見了（<a href="https://dongdonggcp.com/2026/11/18/docker-volume-vs-bind-mount/">第 5 篇</a>用 Docker 示範過）。Kubernetes 的 Pod 更常被刪掉重建：換版、擴縮、節點維修都會發生。這篇在 Cloud Shell 實際比一次：寫一個網頁檔，<strong>容器重開、Pod 重建、刪掉 Deployment、刪掉 PVC</strong>，四種情況下 emptyDir 和 PVC 的資料各自還在不在。</p>



<p class="wp-block-paragraph">還會實際看到兩件網路上常講錯的事：<strong>PVC 的 ReadWriteOnce 不是「只能一個 Pod 用」</strong>，實測兩個 Pod 同時讀寫都可以；還有<strong>刪掉 PVC，資料是真的會跟著刪</strong>。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 16 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。Deployment 的寫法請先看第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-01-layers.png" alt="K8s 的儲存分四層：Pod 是房客、PVC 是租屋申請單、PV 是一間實際的倉庫、StorageClass 是看到申請單就自動蓋倉庫的建商；Minikube 的 PV 放在節點的 /tmp/hostpath-provisioner/default/data-pvc" class="wp-image-13326" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-01-layers.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-01-layers-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-01-layers-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-01-layers-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>資料庫、上傳檔案不能跟著 Pod 消失</strong>：Pod 隨時會被重建，沒設定好儲存，使用者上傳的照片、資料庫的資料就沒了</li>

<li><strong>刪錯東西資料就真的沒了</strong>：實測刪掉 PVC，背後的 PV 和資料一起被刪。不懂回收政策，清資源時很容易誤刪正式資料</li>

<li><strong>雲端的硬碟要錢</strong>：在 GKE 上每個 PVC 都會建一顆 Google Cloud 的永久磁碟，依容量按月計費；忘記刪就一直扣錢</li>

<li><strong>面試和證照常考</strong>：「PV 和 PVC 差在哪」「ReadWriteOnce 是什麼意思」是經典題；CKA 的「儲存」佔 10%（2026 年 11 月查 Linux Foundation 官方頁）</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Volume 是什麼</h2>



<p class="wp-block-paragraph"><strong>Volume（磁碟區）是掛進 Pod 的一個資料夾，Pod 裡的容器都能讀寫它</strong>（<a href="https://kubernetes.io/docs/concepts/storage/volumes/">Kubernetes 官方說明：Volumes</a>）。Volume 有很多種，差別在「資料放在哪、活多久」。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：Pod 是一間會被常常拆掉重蓋的組合屋，Volume 是屋子裡的置物櫃。有的置物櫃跟著屋子一起拆（emptyDir），有的是外面租的倉庫，屋子拆了倉庫還在（PVC）</li>

<li><strong>來龍去脈</strong>：volume 原本是「一卷、一冊」，電腦裡引申成「一個儲存空間」。第 15 篇把 ConfigMap、Secret 掛成檔案，用的也是 Volume</li>

<li><strong>為什麼要學</strong>：選錯 Volume 種類，不是資料不見，就是浪費錢</li>
</ul>



<p class="wp-block-paragraph">這篇會用到的三種：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>種類</th><th>資料放在哪</th><th>活多久</th><th>適合</th></tr></thead><tbody><tr><td><code>emptyDir</code></td><td>節點上的暫存空間</td><td><strong>跟 Pod 一樣久</strong>，Pod 刪了就沒</td><td>暫存檔、同一個 Pod 的容器互傳資料</td></tr><tr><td><code>configMap</code>、<code>secret</code></td><td>叢集裡的物件</td><td>跟物件一樣久</td><td>設定檔、密碼（第 15 篇）</td></tr><tr><td><code>persistentVolumeClaim</code></td><td>PV 背後的真實硬碟</td><td><strong>跟 PVC 一樣久</strong>，跟 Pod 無關</td><td>資料庫、上傳檔案</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">PV、PVC、StorageClass 是什麼</h2>



<h3 class="wp-block-heading">PV（PersistentVolume，永久磁碟區）</h3>



<p class="wp-block-paragraph"><strong>PV 是叢集裡一塊實際的儲存空間</strong>，可能是雲端硬碟、公司的 NFS 網路硬碟，或 Minikube 節點上的一個資料夾。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：一間實際的倉庫，有大小、有地址</li>

<li><strong>來龍去脈</strong>：persistent 是「持續存在的」。PV 的生命週期跟 Pod 無關，Pod 來來去去，PV 一直在</li>

<li><strong>為什麼要學</strong>：資料最後是存在 PV 背後的硬碟裡；PV 的回收政策決定刪除時資料會不會跟著消失</li>
</ul>



<h3 class="wp-block-heading">PVC（PersistentVolumeClaim，永久磁碟區申請）</h3>



<p class="wp-block-paragraph"><strong>PVC 是一張「我需要多大、怎麼用的儲存空間」的申請單</strong>，Pod 只要指定用哪張 PVC，不用管背後是哪種硬碟。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：租屋申請單：「我要 1 坪、可以進出、只給一家人用」。房客（Pod）只拿著申請單去入住，不用知道是哪個建商蓋的</li>

<li><strong>來龍去脈</strong>：claim 是「申請、認領」。Kubernetes 刻意把「誰要空間」（開發人員寫 PVC）和「空間怎麼來」（管理員或雲端準備 PV）分開，同一份 YAML 才能在 Minikube 和 GKE 都用</li>

<li><strong>為什麼要學</strong>：寫應用程式時你會寫的是 PVC，不是 PV</li>
</ul>



<h3 class="wp-block-heading">StorageClass（儲存類別）</h3>



<p class="wp-block-paragraph"><strong>StorageClass 是「看到申請單就自動建 PV」的規則</strong>，寫著要用哪種硬碟、刪除時要怎麼處理。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：建商。你交申請單，建商依照合約（StorageClass 的設定）自動蓋一間倉庫給你</li>

<li><strong>來龍去脈</strong>：早期管理員要先手動建好一堆 PV 等人來申請（靜態配置）；有了 StorageClass，PVC 一建立就自動產生 PV（動態配置），現在幾乎都用這種</li>

<li><strong>為什麼要學</strong>：GKE、Minikube 都有預設的 StorageClass；寫 PVC 不指定時就用預設的那個</li>
</ul>



<h3 class="wp-block-heading">存取模式（Access Modes）</h3>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-03-access.png" alt="PVC 的存取模式：RWO 是一個節點可讀寫、同節點多個 Pod 都行；ROX 很多節點唯讀；RWX 很多節點可讀寫要 NFS 或 Filestore；RWOP 整個叢集只有一個 Pod 能用，1.29 起穩定" class="wp-image-13327" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-03-access.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-03-access-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-03-access-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-03-access-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">官方文件寫得很清楚：<strong>ReadWriteOnce 是「一個節點」可以讀寫，同一個節點上的多個 Pod 都能同時用</strong>；真的要限制只有一個 Pod，要用 ReadWriteOncePod（Kubernetes 1.29 起穩定）（<a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">官方說明：Persistent Volumes</a>，2026 年 11 月查）。實作步驟 9 會證明。</p>



<h3 class="wp-block-heading">回收政策（Reclaim Policy）</h3>



<p class="wp-block-paragraph">PVC 刪掉之後，PV 和裡面的資料怎麼辦：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>政策</th><th>做什麼</th><th>什麼時候用</th></tr></thead><tbody><tr><td><code>Delete</code></td><td><strong>PV 和背後的硬碟一起刪掉</strong></td><td>動態配置的預設值；測試環境</td></tr><tr><td><code>Retain</code></td><td>PV 和資料保留，等管理員手動處理</td><td>正式環境的重要資料</td></tr><tr><td><code>Recycle</code></td><td>清空內容再給別人用</td><td><strong>已棄用</strong>，官方建議改用動態配置</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：emptyDir 和 PVC 的資料比一比</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，跳出「授權 Cloud Shell」按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<h3 class="wp-block-heading">步驟 1：開叢集</h3>



<pre class="wp-block-code"><code>mkdir -p ~/k8s-vol &amp;&amp; cd ~/k8s-vol; minikube start --cni=kindnet | tail -1</code></pre>



<pre class="wp-block-code"><code>（前面省略：版本提醒和硬碟空間警告）
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="342" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start.png" alt="建立 k8s-vol 資料夾，用 --cni=kindnet 啟動 minikube" class="wp-image-13328" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start-300x64.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start-1024x219.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start-768x164.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-01-start-1536x328.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>--cni=kindnet</code> 的原因請看<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">第 13 篇</a>的「實測時的意外」。</p>



<h3 class="wp-block-heading">步驟 2：看預設的 StorageClass</h3>



<pre class="wp-block-code"><code>kubectl get storageclass</code></pre>



<pre class="wp-block-code"><code>NAME                 PROVISIONER                RECLAIMPOLICY   VOLUMEBINDINGMODE   ALLOWVOLUMEEXPANSION   AGE
standard (default)   k8s.io/minikube-hostpath   Delete          Immediate           false                  6s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="150" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass.png" alt="kubectl get storageclass 顯示 Minikube 預設的 standard，provisioner 是 k8s.io/minikube-hostpath、回收政策 Delete" class="wp-image-13329" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass-300x28.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass-1024x96.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass-768x72.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-02-storageclass-1536x144.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>standard (default)</code>：預設的 StorageClass，PVC 沒指定就用它</li>

<li><code>PROVISIONER k8s.io/minikube-hostpath</code>：負責建 PV 的程式（provisioner，供應者），Minikube 的做法是在節點上開資料夾。<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">第 9 篇</a>看到的 <code>storage-provisioner</code> Pod 就是它</li>

<li><code>RECLAIMPOLICY Delete</code>：PVC 刪了，PV 也刪</li>

<li><code>VOLUMEBINDINGMODE Immediate</code>：PVC 一建立就馬上配 PV</li>

<li><code>ALLOWVOLUMEEXPANSION false</code>：建好之後不能加大</li>
</ul>



<h3 class="wp-block-heading">步驟 3：用 emptyDir 寫一個網頁</h3>



<pre class="wp-block-code"><code>cat &gt; emptydir.yaml &lt;&lt;'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tmp-web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tmp-web
  template:
    metadata:
      labels:
        app: tmp-web
    spec:
      containers:
      - name: nginx
        image: nginx:1.31
        volumeMounts:
        - name: html
          mountPath: /usr/share/nginx/html
      volumes:
      - name: html
        emptyDir: {}
EOF
kubectl apply -f emptydir.yaml; kubectl rollout status deployment tmp-web; P=$(kubectl get pods -l app=tmp-web -o name); kubectl exec $P -- sh -c 'echo "hello emptyDir" &gt; /usr/share/nginx/html/index.html'; kubectl exec $P -- cat /usr/share/nginx/html/index.html</code></pre>



<pre class="wp-block-code"><code>deployment.apps/tmp-web created
Waiting for deployment "tmp-web" rollout to finish: 0 of 1 updated replicas are available...
deployment "tmp-web" successfully rolled out
hello emptyDir</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="727" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write.png" alt="建立用 emptyDir 的 tmp-web，在 nginx 的網頁資料夾寫入 hello emptyDir 並讀出來" class="wp-image-13330" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write-300x136.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write-1024x465.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write-768x349.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-03-emptydir-write-1536x698.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>emptyDir: {}</code>：一個空資料夾，<code>{}</code> 代表全部用預設值</li>

<li>掛在 <code>/usr/share/nginx/html</code>，這是 nginx 放網頁檔的地方</li>

<li>用 <code>kubectl exec ... sh -c 'echo ... &gt; 檔案'</code> 在容器裡寫一個 <code>index.html</code></li>
</ul>



<h3 class="wp-block-heading">步驟 4：容器重開，資料還在</h3>



<p class="wp-block-paragraph">叫 nginx 自己結束（<code>nginx -s quit</code>），容器就會停掉、被 kubelet 重開：</p>



<pre class="wp-block-code"><code>kubectl exec $P -- nginx -s quit; sleep 8; kubectl get pods -l app=tmp-web; kubectl exec $P -- cat /usr/share/nginx/html/index.html</code></pre>



<pre class="wp-block-code"><code>2026/11/20 16:08:31 [notice] 43#43: signal process started
NAME                       READY   STATUS    RESTARTS     AGE
tmp-web-6df9b8dcd6-6trzn   1/1     Running   1 (8s ago)   36s
hello emptyDir</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="184" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart.png" alt="nginx -s quit 讓容器結束，Pod 的 RESTARTS 變成 1，emptyDir 裡的 hello emptyDir 還在" class="wp-image-13331" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart-1024x118.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart-768x88.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-04-container-restart-1536x177.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>RESTARTS 1</code>：容器重開了一次，但 <strong>Pod 還是同一個</strong>（名字、AGE 都沒變），emptyDir 也還在，所以 <code>hello emptyDir</code> 還讀得到。<strong>emptyDir 跟著 Pod 活，不是跟著容器。</strong></p>



<h3 class="wp-block-heading">步驟 5：Pod 刪掉重建，資料不見了</h3>



<pre class="wp-block-code"><code>kubectl delete $P; sleep 5; P=$(kubectl get pods -l app=tmp-web -o name); echo $P; kubectl exec $P -- cat /usr/share/nginx/html/index.html</code></pre>



<pre class="wp-block-code"><code>pod "tmp-web-6df9b8dcd6-6trzn" deleted from default namespace
pod/tmp-web-6df9b8dcd6-fmfd8
cat: /usr/share/nginx/html/index.html: No such file or directory
command terminated with exit code 1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="184" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted.png" alt="刪掉 Pod 後 Deployment 補了新的 fmfd8，emptyDir 是新的空資料夾，cat 回報 No such file or directory" class="wp-image-13332" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted-1024x118.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted-768x88.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-05-pod-deleted-1536x177.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Deployment 補了一個新 Pod（<code>fmfd8</code>），它拿到的是<strong>全新的空 emptyDir</strong>，<code>index.html</code> 不存在了（<code>No such file or directory</code>）。</p>



<h3 class="wp-block-heading">步驟 6：開一張 PVC 申請單</h3>



<pre class="wp-block-code"><code>cat &gt; pvc.yaml &lt;&lt;'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
EOF
kubectl apply -f pvc.yaml; sleep 5; kubectl get pvc,pv</code></pre>



<pre class="wp-block-code"><code>persistentvolumeclaim/data-pvc created
NAME                             STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
persistentvolumeclaim/data-pvc   Bound    pvc-c2d545e6-98cd-4a49-906b-886c9fe6f6e9   1Gi        RWO            standard       &lt;unset&gt;                 5s

NAME                                                        CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM              STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
persistentvolume/pvc-c2d545e6-98cd-4a49-906b-886c9fe6f6e9   1Gi        RWO            Delete           Bound    default/data-pvc   standard       &lt;unset&gt;                          5s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="553" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound.png" alt="建立 1Gi、RWO 的 PVC data-pvc，5 秒內狀態 Bound，並自動產生一個 PV pvc-c2d545e6，回收政策 Delete" class="wp-image-13333" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound-300x104.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound-1024x354.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound-768x265.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-06-pvc-bound-1536x531.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>accessModes: ReadWriteOnce</code>、<code>storage: 1Gi</code>：申請 1Gi（約 10.7 億位元組）、單一節點讀寫</li>

<li>沒寫 <code>storageClassName</code>，就用預設的 <code>standard</code></li>

<li>5 秒內 PVC 的 <code>STATUS</code> 就是 <strong><code>Bound</code>（已綁定）</strong>，而且多了一個 PV <code>pvc-c2d545e6-...</code>，這就是 StorageClass 自動建的</li>

<li>PV 的 <code>CLAIM default/data-pvc</code>：它是給 <code>default</code> 命名空間的 <code>data-pvc</code> 用的；<code>RECLAIM POLICY Delete</code> 照 StorageClass 的設定</li>
</ul>



<p class="wp-block-paragraph"><strong>Gi 和 G 不一樣</strong>：<code>1Gi</code> 是 1024×1024×1024＝1,073,741,824 位元組；<code>1G</code> 是 1,000,000,000 位元組，差了約 7%。Kubernetes 的容量和記憶體習慣用 <code>Gi</code>、<code>Mi</code>。</p>



<h3 class="wp-block-heading">步驟 7：用 PVC 的網站，Pod 重建資料還在</h3>



<p class="wp-block-paragraph">把 emptyDir 換成 PVC，同樣寫一個網頁，然後刪掉 Pod：</p>



<pre class="wp-block-code"><code>cat &gt; pvc-web.yaml &lt;&lt;'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pvc-web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: pvc-web
  template:
    metadata:
      labels:
        app: pvc-web
    spec:
      containers:
      - name: nginx
        image: nginx:1.31
        volumeMounts:
        - name: html
          mountPath: /usr/share/nginx/html
      volumes:
      - name: html
        persistentVolumeClaim:
          claimName: data-pvc
EOF
kubectl apply -f pvc-web.yaml; kubectl rollout status deployment pvc-web; Q=$(kubectl get pods -l app=pvc-web -o name); kubectl exec $Q -- sh -c 'echo "hello PVC" &gt; /usr/share/nginx/html/index.html'; kubectl delete $Q; sleep 5; Q=$(kubectl get pods -l app=pvc-web -o name); echo new pod: $Q; kubectl exec $Q -- cat /usr/share/nginx/html/index.html</code></pre>



<pre class="wp-block-code"><code>deployment.apps/pvc-web created
Waiting for deployment "pvc-web" rollout to finish: 0 of 1 updated replicas are available...
deployment "pvc-web" successfully rolled out
pod "pvc-web-56dbcf999-f2c7x" deleted from default namespace
new pod: pod/pvc-web-56dbcf999-ssbqk
hello PVC</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="814" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives.png" alt="用 PVC 的 pvc-web 寫入 hello PVC，刪掉 Pod f2c7x 後新的 Pod ssbqk 還讀得到 hello PVC" class="wp-image-13334" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives-300x153.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives-1024x521.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives-768x391.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-07-pvc-survives-1536x781.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">跟步驟 3 的 YAML 只差最後兩行：<code>emptyDir: {}</code> 換成 <code>persistentVolumeClaim: claimName: data-pvc</code>。舊 Pod <code>f2c7x</code> 寫入 <code>hello PVC</code> 後被刪掉，新 Pod <code>ssbqk</code> <strong>還讀得到 <code>hello PVC</code></strong>。</p>



<h3 class="wp-block-heading">步驟 8：資料實際放在節點的哪裡</h3>



<pre class="wp-block-code"><code>PVPATH=$(kubectl get pv -o jsonpath='{.items[0].spec.hostPath.path}'); echo $PVPATH; minikube ssh -- cat $PVPATH/index.html</code></pre>



<pre class="wp-block-code"><code>/tmp/hostpath-provisioner/default/data-pvc
hello PVC</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="123" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node.png" alt="PV 的 hostPath 是節點上的 /tmp/hostpath-provisioner/default/data-pvc，minikube ssh 進節點讀到 hello PVC" class="wp-image-13335" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node-300x23.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node-1024x79.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node-768x59.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-08-on-node-1536x118.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Minikube 的 PV 就是節點上的 <code>/tmp/hostpath-provisioner/default/data-pvc</code> 資料夾，進節點直接讀得到 <code>hello PVC</code>。路徑是「命名空間/PVC 名字」。</p>



<p class="wp-block-paragraph">正式環境的 PV 不會是節點上的資料夾（節點壞了資料就沒了），而是雲端硬碟或網路儲存，Pod 換到別的節點也能接上同一顆硬碟。</p>



<h3 class="wp-block-heading">步驟 9：RWO 的 PVC，兩個 Pod 同時用</h3>



<p class="wp-block-paragraph">把 Deployment 擴成 2 個，兩個 Pod 都掛同一張 RWO 的 PVC：</p>



<pre class="wp-block-code"><code>kubectl scale deployment pvc-web --replicas=2; sleep 10; kubectl get pods -l app=pvc-web -o wide; for q in $(kubectl get pods -l app=pvc-web -o name); do kubectl exec $q -- cat /usr/share/nginx/html/index.html; done</code></pre>



<pre class="wp-block-code"><code>deployment.apps/pvc-web scaled
NAME                      READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
pvc-web-56dbcf999-cqqkv   1/1     Running   0          10s   10.244.0.7   minikube   &lt;none&gt;           &lt;none&gt;
pvc-web-56dbcf999-ssbqk   1/1     Running   0          34s   10.244.0.6   minikube   &lt;none&gt;           &lt;none&gt;
hello PVC
hello PVC</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="228" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods.png" alt="把 pvc-web 擴成 2 個 Pod，兩個都在 minikube 節點上 Running，都讀得到 hello PVC" class="wp-image-13336" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods-300x43.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods-1024x146.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods-768x109.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-09-rwo-two-pods-1536x219.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">兩個 Pod 都是 <code>Running</code>，<strong>都讀得到同一份 <code>hello PVC</code></strong>。因為兩個 Pod 在同一個節點（<code>minikube</code>），RWO 允許。</p>



<p class="wp-block-paragraph">這是很常見的誤會：很多人以為 RWO 是「只能一個 Pod 用」，結果兩個 Pod 同時寫同一個檔案，資料就亂了。要真的鎖定一個 Pod，要用 <code>ReadWriteOncePod</code>。如果 Pod 分在不同節點，RWO 的硬碟只能掛在其中一個節點，另一個 Pod 會卡住起不來。</p>



<h3 class="wp-block-heading">步驟 10：刪掉 Deployment，PVC 和 PV 都還在</h3>



<pre class="wp-block-code"><code>kubectl delete deployment pvc-web tmp-web; kubectl get pvc,pv</code></pre>



<pre class="wp-block-code"><code>deployment.apps "pvc-web" deleted from default namespace
deployment.apps "tmp-web" deleted from default namespace
NAME                             STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
persistentvolumeclaim/data-pvc   Bound    pvc-c2d545e6-98cd-4a49-906b-886c9fe6f6e9   1Gi        RWO            standard       &lt;unset&gt;                 54s

NAME                                                        CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM              STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
persistentvolume/pvc-c2d545e6-98cd-4a49-906b-886c9fe6f6e9   1Gi        RWO            Delete           Bound    default/data-pvc   standard       &lt;unset&gt;                          54s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="314" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays.png" alt="刪掉兩個 Deployment 之後，PVC data-pvc 和 PV 都還在，狀態還是 Bound" class="wp-image-13337" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays-300x59.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays-1024x201.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays-768x151.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-10-pvc-stays-1536x301.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Deployment 刪了，PVC 和 PV 都還在、還是 <code>Bound</code>。下次建一個 Deployment 指向 <code>data-pvc</code>，就能接著用裡面的資料。</p>



<h3 class="wp-block-heading">步驟 11：刪掉 PVC，PV 跟著消失</h3>



<pre class="wp-block-code"><code>kubectl delete -f pvc.yaml; sleep 5; kubectl get pvc,pv</code></pre>



<pre class="wp-block-code"><code>persistentvolumeclaim "data-pvc" deleted from default namespace
No resources found</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="246" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted.png" alt="刪掉 PVC data-pvc 之後，kubectl get pvc,pv 顯示 No resources found，PV 也一起被刪" class="wp-image-13338" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted-300x46.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted-1024x157.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted-768x118.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-11-pvc-deleted-1536x236.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>No resources found</code>：PVC 刪了，因為回收政策是 <code>Delete</code>，<strong>PV 和裡面的 <code>hello PVC</code> 一起被刪掉了</strong>。在 GKE 上，這代表那顆雲端硬碟也被刪除，資料救不回來。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-02-lifetime.png" alt="實測寫進去的 index.html 還在嗎：容器重開時 emptyDir 和 PVC 都還在；Pod 重建時 emptyDir 不見、PVC 還在；刪 Deployment 時 PVC 和 PV 都在；刪 PVC 時 PV 跟著刪" class="wp-image-13339" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-02-lifetime.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-02-lifetime-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-02-lifetime-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-cards-02-lifetime-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. RWO 的 PVC 可以兩個 Pod 同時讀寫</h3>



<p class="wp-block-paragraph">原本預期擴成 2 個 Pod 時，第二個會卡住；實測兩個都 Running、都讀得到同一份資料。官方文件寫明 RWO 是「一個節點」，同節點的多個 Pod 都能用。Minikube 只有一個節點，所以一定會遇到這個情況；多節點的叢集裡，Pod 被排到別的節點時才會卡住。</p>



<h3 class="wp-block-heading">2. PVC 5 秒內就 Bound</h3>



<p class="wp-block-paragraph">Minikube 的 StorageClass 是 <code>Immediate</code>，PVC 一建立就配 PV。GKE 的預設 StorageClass 通常是 <code>WaitForFirstConsumer</code>（等到有 Pod 要用才建硬碟，這樣才知道要建在哪個區域），所以在 GKE 上建完 PVC 看到 <code>Pending</code> 是正常的，等 Pod 建起來就會 Bound。</p>



<h3 class="wp-block-heading">3. nginx -s quit 會印一行 notice</h3>



<p class="wp-block-paragraph">步驟 4 讓容器結束時，畫面上多了 <code>[notice] 43#43: signal process started</code>，這是 nginx 收到結束指令時的正常訊息，不是錯誤。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<p class="wp-block-paragraph">步驟 10、11 已經刪掉 Deployment 和 PVC，最後關掉叢集：</p>



<pre class="wp-block-code"><code>minikube delete | tail -1</code></pre>



<pre class="wp-block-code"><code>💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1199" height="206" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-12-cleanup.png" alt="minikube delete 刪掉整個叢集" class="wp-image-13340" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-12-cleanup.png 1199w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-12-cleanup-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-12-cleanup-1024x176.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct16-shots-12-cleanup-768x132.png 768w" sizes="(max-width: 1199px) 100vw, 1199px" /></figure>



<p class="wp-block-paragraph">Cloud Shell 和 Minikube 都不收費。<code>~/k8s-vol</code> 資料夾的 YAML 會留著。</p>



<p class="wp-block-paragraph"><strong>在 GKE 上不刪會怎樣</strong>：每個 PVC 背後是一顆 Google Cloud 的永久磁碟，<strong>刪掉 Deployment 不會刪硬碟</strong>，硬碟會一直計費，要記得 <code>kubectl delete pvc</code>。反過來，重要的資料要把回收政策設成 <code>Retain</code>，避免一刪 PVC 就連硬碟一起刪。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Minikube</th><th>GKE</th></tr></thead><tbody><tr><td>預設 StorageClass</td><td><code>standard</code>（節點上的資料夾）</td><td><code>standard-rwo</code>（Compute Engine 永久磁碟，透過 CSI 驅動程式）</td></tr><tr><td>建 PV 的時機</td><td><code>Immediate</code></td><td>通常是 <code>WaitForFirstConsumer</code></td></tr><tr><td>單一節點讀寫（RWO）</td><td>節點資料夾</td><td>永久磁碟或 Hyperdisk</td></tr><tr><td>多節點讀寫（RWX）</td><td>不支援</td><td>Filestore（網路檔案儲存）、Cloud Storage FUSE</td></tr><tr><td>收費</td><td>免費</td><td>依磁碟容量和類型按月計費</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>CSI（Container Storage Interface，容器儲存介面）是讓各家硬碟接上 Kubernetes 的標準</strong>，跟第 9 篇的 CRI、第 13 篇的 CNI 是同一個思路：Kubernetes 定標準，廠商寫外掛。</p>



<p class="wp-block-paragraph"><strong>Cloud Run</strong> 的容器不保存資料，重開就沒了。資料要放在 Cloud SQL（資料庫）、Cloud Storage（檔案）這類服務；Cloud Run 也能把 Cloud Storage 或 Filestore 掛成資料夾。</p>



<p class="wp-block-paragraph">資料庫這類「每個 Pod 要有自己一顆硬碟」的程式，Kubernetes 用 <strong>StatefulSet</strong> 搭配 <code>volumeClaimTemplates</code>，每個 Pod 自動拿到自己的 PVC。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「PV 和 PVC 差在哪？」</strong>：PV 是實際的儲存空間，PVC 是申請單；Pod 只用 PVC，不直接碰 PV，同一份 YAML 才能在不同環境用</li>

<li><strong>「StorageClass 是做什麼的？」</strong>：動態配置，PVC 一建立就照 StorageClass 的設定自動建 PV</li>

<li><strong>「ReadWriteOnce 是什麼意思？」</strong>：單一節點可讀寫，同節點多個 Pod 都能用；要限制單一 Pod 用 ReadWriteOncePod（1.29 起穩定）</li>

<li><strong>「刪掉 PVC 資料會不見嗎？」</strong>：看回收政策，<code>Delete</code> 會連 PV 和硬碟一起刪，<code>Retain</code> 會保留</li>

<li><strong>「emptyDir 什麼時候用？」</strong>：暫存檔、同一個 Pod 裡容器互傳資料；容器重開還在，Pod 刪了就沒</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKA、CKAD）</h3>



<p class="wp-block-paragraph">上機實作考（445 美元、2 小時；CKA 的「儲存」佔 10%，2026 年 11 月查 Linux Foundation 官方頁）。常見題型：</p>


<ul class="wp-block-list">
<li>建一個 PV（指定容量、存取模式、hostPath）和對應的 PVC，確認 Bound</li>

<li>建一個 Pod 或 Deployment 掛上指定的 PVC</li>

<li>建指定 StorageClass 的 PVC</li>

<li>用 emptyDir 讓同一個 Pod 的兩個容器共用資料</li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「Pod 重建資料要留著」</td><td>PVC</td></tr><tr><td>「暫存」「同 Pod 容器共用」</td><td>emptyDir</td></tr><tr><td>「自動建立 PV」</td><td>StorageClass（動態配置）</td></tr><tr><td>「刪了 PVC 資料保留」</td><td><code>Retain</code> 回收政策</td></tr><tr><td>「只能一個 Pod 讀寫」</td><td>ReadWriteOncePod</td></tr><tr><td>「多個節點同時寫」</td><td>ReadWriteMany（Filestore、NFS）</td></tr><tr><td>「每個 Pod 一顆硬碟」</td><td>StatefulSet＋volumeClaimTemplates</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">PV 和 PVC 有什麼不同？</h3>



<p class="wp-block-paragraph">PV 是叢集裡一塊實際的儲存空間（雲端硬碟、網路硬碟或節點資料夾），PVC 是「我需要多大、怎麼用」的申請單。Pod 只指定 PVC，不直接碰 PV。實測建一張 1Gi 的 PVC，5 秒內就自動產生一個 PV 並綁定（Bound）。</p>



<h3 class="wp-block-heading">Pod 刪掉，資料會不見嗎？</h3>



<p class="wp-block-paragraph">要看用哪種 Volume。emptyDir 跟著 Pod，Pod 刪了資料就沒了（實測新 Pod 讀不到檔案）；PVC 跟 Pod 無關，實測刪掉 Pod 後新 Pod 還讀得到 <code>hello PVC</code>。容器重開（不是 Pod 重建）時，兩種都還在。</p>



<h3 class="wp-block-heading">ReadWriteOnce 是只能一個 Pod 用嗎？</h3>



<p class="wp-block-paragraph">不是。ReadWriteOnce 是「單一節點」可讀寫，同一個節點上的多個 Pod 都能同時用。實測 RWO 的 PVC 擴成 2 個 Pod，兩個都 Running、都讀得到同一份資料。要限制整個叢集只有一個 Pod 能用，請用 ReadWriteOncePod（Kubernetes 1.29 起穩定）。</p>



<h3 class="wp-block-heading">刪掉 PVC 資料還救得回來嗎？</h3>



<p class="wp-block-paragraph">回收政策是 <code>Delete</code> 的話救不回來，PV 和背後的硬碟會一起刪除。實測刪掉 PVC 之後 <code>kubectl get pv</code> 顯示 No resources found。重要資料要把 StorageClass 或 PV 的回收政策設成 <code>Retain</code>，並且定期備份。</p>



<h3 class="wp-block-heading">StorageClass 一定要設定嗎？</h3>



<p class="wp-block-paragraph">不一定。叢集有預設的 StorageClass 時（Minikube 是 <code>standard</code>、GKE 是 <code>standard-rwo</code>），PVC 不寫 <code>storageClassName</code> 就會用預設的。要用不同等級的硬碟（例如更快的 SSD）時，才另外指定。</p>



<h3 class="wp-block-heading">刪掉 Deployment 會刪掉 PVC 嗎？</h3>



<p class="wp-block-paragraph">不會。實測刪掉兩個 Deployment 之後，PVC 和 PV 都還在、狀態還是 Bound。這是好事（資料不會被誤刪），也是陷阱：在 GKE 上 PVC 背後的雲端硬碟會繼續計費，不用了要自己 <code>kubectl delete pvc</code>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>emptyDir 跟著 Pod</strong>：容器重開還在，Pod 重建就沒了；適合暫存</li>

<li><strong>PVC 是申請單、PV 是實際空間、StorageClass 自動配置</strong>：Pod 只寫 PVC，實測 5 秒內 Bound，Pod 刪了資料還在</li>

<li><strong>RWO 是一個節點，不是一個 Pod</strong>：實測兩個 Pod 同時讀寫；要鎖一個 Pod 用 RWOP</li>

<li><strong>回收政策 Delete 會連資料一起刪</strong>：實測刪 PVC 後 PV 跟著消失；重要資料用 Retain</li>

<li><strong>GKE 上 PVC 是一顆要錢的雲端硬碟</strong>，刪 Deployment 不會刪它</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 5 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-volume-vs-bind-mount/">Docker 資料會消失？Volume 和 Bind Mount 怎麼選</a></li>

<li>第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>

<li>上一篇：第 15 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">ConfigMap 和 Secret：設定和密碼不要寫死在映像檔</a></li>

<li>下一篇：第 17 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">健康檢查與自動擴展：Probe、資源限制、HPA</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護</a></li>

<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">資料留得住之後，下一步是讓叢集自己判斷 Pod 健不健康、流量大時自動加開。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "PV 和 PVC 有什麼不同？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "PV 是叢集裡一塊實際的儲存空間（雲端硬碟、網路硬碟或節點資料夾），PVC 是「我需要多大、怎麼用」的申請單。Pod 只指定 PVC，不直接碰 PV。實測建一張 1Gi 的 PVC，5 秒內就自動產生一個 PV 並綁定（Bound）。"
      }
    },
    {
      "@type": "Question",
      "name": "Pod 刪掉，資料會不見嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "要看用哪種 Volume。emptyDir 跟著 Pod，Pod 刪了資料就沒了（實測新 Pod 讀不到檔案）；PVC 跟 Pod 無關，實測刪掉 Pod 後新 Pod 還讀得到 `hello PVC`。容器重開（不是 Pod 重建）時，兩種都還在。"
      }
    },
    {
      "@type": "Question",
      "name": "ReadWriteOnce 是只能一個 Pod 用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不是。ReadWriteOnce 是「單一節點」可讀寫，同一個節點上的多個 Pod 都能同時用。實測 RWO 的 PVC 擴成 2 個 Pod，兩個都 Running、都讀得到同一份資料。要限制整個叢集只有一個 Pod 能用，請用 ReadWriteOncePod（Kubernetes 1.29 起穩定）。"
      }
    },
    {
      "@type": "Question",
      "name": "刪掉 PVC 資料還救得回來嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "回收政策是 `Delete` 的話救不回來，PV 和背後的硬碟會一起刪除。實測刪掉 PVC 之後 `kubectl get pv` 顯示 No resources found。重要資料要把 StorageClass 或 PV 的回收政策設成 `Retain`，並且定期備份。"
      }
    },
    {
      "@type": "Question",
      "name": "StorageClass 一定要設定嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定。叢集有預設的 StorageClass 時（Minikube 是 `standard`、GKE 是 `standard-rwo`），PVC 不寫 `storageClassName` 就會用預設的。要用不同等級的硬碟（例如更快的 SSD）時，才另外指定。"
      }
    },
    {
      "@type": "Question",
      "name": "刪掉 Deployment 會刪掉 PVC 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不會。實測刪掉兩個 Deployment 之後，PVC 和 PV 都還在、狀態還是 Bound。這是好事（資料不會被誤刪），也是陷阱：在 GKE 上 PVC 背後的雲端硬碟會繼續計費，不用了要自己 `kubectl delete pvc`。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">K8s 資料怎麼保存？Volume、PV、PVC 一次看懂</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-service-clusterip-nodeport-loadbalancer</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:33:34 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13292</guid>

					<description><![CDATA[<p>K8s Service 怎麼選？Cloud Shell 實測三種各連一次：Pod 用名字連 ClusterIP、節點 IP 連 NodePort、tunnel 拿 LoadBalancer IP，附 Pod 連不到 Service 的解法。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>K8s Service 怎麼選：內部互連用 ClusterIP、測試用 NodePort、正式對外用 LoadBalancer。</strong></p>



<p class="wp-block-paragraph">Pod 重建一次 IP 就換一次，網站要連資料庫、使用者要連網站，總不能每次都去查新的 IP。Kubernetes 的解法是 <strong>Service</strong>：給一群 Pod 一個固定的名字和 IP。這篇在 Cloud Shell 把三種 Service 各連一次：從另一個 Pod 用名字 <code>who</code> 連 ClusterIP、從 Cloud Shell 連 NodePort、開 <code>minikube tunnel</code> 讓 LoadBalancer 拿到對外 IP，每次都印出是哪個 Pod 回應的。</p>



<p class="wp-block-paragraph">實測時還踩到一個網路上沒人寫的坑：<strong>Cloud Shell 的 Minikube 用預設網路設定時，Pod 連 Service 會整個不通</strong>，DNS 也查不到名字。這篇會說明原因，並改用 <code>minikube start --cni=kindnet</code> 解決。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 13 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。Deployment 的寫法請先看第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-01-types.png" alt="K8s Service 三種類型：ClusterIP 只有叢集裡面連得到、NodePort 加上節點 IP 和 30000 到 32767 的 Port、LoadBalancer 再加一個對外 IP；後一種都包含前一種" class="wp-image-13276" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-01-types.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-01-types-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-01-types-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-01-types-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>Pod 的 IP 靠不住</strong>：實測刪掉一個 Pod，補回來的新 Pod IP 從 <code>10.244.0.4</code> 變成 <code>10.244.0.6</code>。程式裡寫死 Pod IP，Pod 一重建就連不到</li>

<li><strong>選錯類型會多花錢或不安全</strong>：在雲端，每個 LoadBalancer 類型的 Service 都會建一個負載平衡器，是要收費的；資料庫開成 LoadBalancer，等於把它直接放上網路</li>

<li><strong>面試和證照必考</strong>：「ClusterIP、NodePort、LoadBalancer 差在哪」幾乎是 Kubernetes 面試的第一題；CKA 的考試範圍裡「服務與網路」佔 20%（2026 年 11 月查 Linux Foundation 官方頁）</li>

<li><strong>後面每一篇都會用到</strong>：第 14 篇的 Ingress、<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">第 17 篇</a>的自動擴展，流量都是先經過 Service 才到 Pod</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Service 是什麼</h2>



<p class="wp-block-paragraph"><strong>Service 是一個固定的名字和 IP，負責把流量分給背後一群 Pod。</strong> 不管 Pod 怎麼重建、換 IP，連 Service 的那一方都不用改（<a href="https://kubernetes.io/docs/concepts/services-networking/service/">Kubernetes 官方說明：Service</a>）。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳的訂位專線。客人只記得專線號碼，至於今天是哪位店員接、店員有沒有換人，客人不用知道</li>

<li><strong>來龍去脈</strong>：容器時代以前，伺服器的 IP 很少變，寫死在設定檔裡就好。Kubernetes 的 Pod 隨時會被重建、搬到別的節點，IP 一直變，所以需要一層「不會變的入口」</li>

<li><strong>為什麼要學</strong>：在 Kubernetes 裡，程式之間互連幾乎都透過 Service 的名字，不會直接用 Pod IP</li>
</ul>



<h3 class="wp-block-heading">Service 怎麼知道要把流量送給誰</h3>



<p class="wp-block-paragraph"><strong>靠標籤選擇器（selector）。</strong> Service 的 YAML 寫 <code>selector: app: who</code>，Kubernetes 就會一直盯著「標籤是 <code>app=who</code> 而且準備好的 Pod」，把它們的 IP 記在一份叫 <strong>EndpointSlice（端點切片）</strong> 的清單裡。Pod 增加、刪除、換 IP，這份清單會自動更新。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-02-how.png" alt="Service 怎麼找到 Pod：Pod 裡用 http://who 連到 Service who 10.101.20.235，Service 透過 EndpointSlice 和 selector app=who 找到 3 個 Pod 的 IP；Pod 重建 IP 會換但 Service 不變" class="wp-image-13277" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-02-how.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-02-how-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-02-how-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-02-how-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">叢集裡的 DNS：用名字連 Service</h3>



<p class="wp-block-paragraph"><strong>DNS（Domain Name System）是把「名字」翻成「IP」的電話簿。</strong> Kubernetes 叢集裡有一個 CoreDNS（<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">第 9 篇</a>在 <code>kube-system</code> 看過它），每建一個 Service，它就自動多一筆：</p>



<pre class="wp-block-code"><code>Service名字.命名空間.svc.cluster.local</code></pre>



<p class="wp-block-paragraph">這篇的 Service 叫 <code>who</code>、放在 <code>default</code> 命名空間，全名就是 <code>who.default.svc.cluster.local</code>。同一個命名空間裡的 Pod，直接用 <code>who</code> 就連得到。站上有一篇 <a href="https://dongdonggcp.com/2025/11/19/what-is-dns-domain-name-system-guide/">DNS 是什麼</a> 講得更完整。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">三種 Service 類型</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>類型</th><th>白話</th><th>誰連得到</th><th>什麼時候用</th></tr></thead><tbody><tr><td><strong>ClusterIP</strong>（預設）</td><td>叢集內部專用的固定 IP</td><td>只有叢集裡的 Pod</td><td>網站連資料庫、服務之間互叫</td></tr><tr><td><strong>NodePort</strong></td><td>在每個節點上開一個固定 Port</td><td>連得到節點 IP 的人</td><td>測試、沒有雲端負載平衡器的環境</td></tr><tr><td><strong>LoadBalancer</strong></td><td>跟雲端要一個對外的負載平衡器和 IP</td><td>網路上任何人（看防火牆設定）</td><td>正式環境對外服務</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">三個是<strong>一層包一層</strong>的關係：建 NodePort 時 Kubernetes 也會給它一個 ClusterIP；建 LoadBalancer 時也會有 ClusterIP 和 NodePort。實作的步驟 9 會看到 LoadBalancer 的 <code>PORT(S)</code> 欄寫著 <code>80:30815/TCP</code>，那個 30815 就是它自帶的 NodePort。</p>



<h3 class="wp-block-heading">ClusterIP：叢集內部的分機</h3>



<p class="wp-block-paragraph"><strong>ClusterIP 是只在叢集裡面有效的虛擬 IP。</strong> 叢集外面（包括 Cloud Shell 本身）連不到，實作步驟 7 會證明。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：公司內部分機，外面的人打不進來</li>

<li><strong>為什麼要學</strong>：資料庫、快取這類「只給自己人用」的服務一定要用它，不要對外開</li>
</ul>



<h3 class="wp-block-heading">NodePort：在每個節點開一扇側門</h3>



<p class="wp-block-paragraph"><strong>NodePort 是在叢集的每個節點上，開一個 30000～32767 之間的 Port</strong>，連「任一個節點的 IP:這個 Port」，流量就會被轉進 Service。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：每間分店的側門都貼同一個門牌號碼，從哪間分店進去都能找到同一個櫃檯</li>

<li><strong>來龍去脈</strong>：30000～32767 是 Kubernetes 預設保留給 NodePort 的範圍，避免跟節點上其他程式（像網頁的 80、SSH 的 22）撞號</li>

<li><strong>為什麼要學</strong>：沒有雲端負載平衡器的環境（自己機房、練習用叢集）常用它；但 Port 號很醜、節點 IP 會變，正式對外通常不直接用</li>
</ul>



<h3 class="wp-block-heading">LoadBalancer：跟雲端要一個正門</h3>



<p class="wp-block-paragraph"><strong>LoadBalancer 是請雲端服務商建一個負載平衡器（Load Balancer），給你一個對外 IP</strong>，流量從這個 IP 進來後分給各節點、再進到 Pod。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：在大馬路上開一個正門，還請了一位門口接待，把客人平均分到各個櫃檯</li>

<li><strong>來龍去脈</strong>：這個類型要靠雲端服務商配合（GKE 會幫你建 Google Cloud 的負載平衡器）。Minikube 沒有雲端可以要，所以 <code>EXTERNAL-IP</code> 會一直是 <code>&lt;pending&gt;</code>，要開 <code>minikube tunnel</code> 模擬</li>

<li><strong>為什麼要學</strong>：GKE 上最常見的對外方式之一。但<strong>每個 LoadBalancer Service 都是一個要收費的負載平衡器</strong>，服務一多就該考慮第 14 篇的 Ingress（多個服務共用一個入口）</li>
</ul>



<h3 class="wp-block-heading">三個 Port 別搞混</h3>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-03-ports.png" alt="三個 Port 別搞混：targetPort 80 是 Pod 裡程式在聽的 Port、port 80 是 Service 自己的 Port、nodePort 31194 是節點上開的 Port，預設從 30000 到 32767 隨機挑" class="wp-image-13278" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-03-ports.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-03-ports-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-03-ports-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-cards-03-ports-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph"><code>kubectl get service</code> 的 <code>PORT(S)</code> 欄寫 <code>80:31194/TCP</code>，意思是「Service 的 80 Port，對應到節點上的 31194 Port，用 TCP 協定」。TCP 是網路傳資料最常用的規則，網頁走的就是它。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：三種 Service 各連一次</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，跳出「授權 Cloud Shell」按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<p class="wp-block-paragraph">這篇用的映像檔是 <code>traefik/whoami</code>，它是一個很小的網頁程式，<strong>每次被連都會回報自己的主機名稱（也就是 Pod 名字）</strong>，很適合看流量被分到哪個 Pod。</p>



<h3 class="wp-block-heading">步驟 1：用 kindnet 網路外掛開叢集</h3>



<p class="wp-block-paragraph"><strong>注意這篇開叢集的指令多了 <code>--cni=kindnet</code></strong>，原因在「實測時的意外」第 1 點。如果你之前開過 Minikube，先 <code>minikube delete</code> 再重開：</p>



<pre class="wp-block-code"><code>mkdir -p ~/k8s-svc &amp;&amp; cd ~/k8s-svc
minikube delete | tail -1; minikube start --cni=kindnet | tail -1</code></pre>



<pre class="wp-block-code"><code>💀  Removed all traces of the "minikube" cluster.
（中間省略：版本提醒和硬碟空間警告）
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="364" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start.png" alt="minikube delete 後用 --cni=kindnet 重新啟動叢集，顯示 Done" class="wp-image-13279" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start-300x68.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start-1024x233.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start-768x175.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-01-start-1536x349.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>CNI（Container Network Interface，容器網路介面）是 Kubernetes 用來「接網路線」的外掛標準</strong>，決定 Pod 之間的封包怎麼走。kindnet 是其中一種簡單的實作，原本是 kind 這個工具在用的。</p>



<h3 class="wp-block-heading">步驟 2：部署 3 個 whoami Pod</h3>



<pre class="wp-block-code"><code>cat &gt; who.yaml &lt;&lt;'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: who
spec:
  replicas: 3
  selector:
    matchLabels:
      app: who
  template:
    metadata:
      labels:
        app: who
    spec:
      containers:
      - name: whoami
        image: traefik/whoami:v1.12
        ports:
        - containerPort: 80
EOF
kubectl apply -f who.yaml; sleep 25; kubectl get pods -o wide</code></pre>



<pre class="wp-block-code"><code>deployment.apps/who created
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
who-7bb7b9cb67-c6rbq   1/1     Running   0          25s   10.244.0.4   minikube   &lt;none&gt;           &lt;none&gt;
who-7bb7b9cb67-dx4j4   1/1     Running   0          25s   10.244.0.5   minikube   &lt;none&gt;           &lt;none&gt;
who-7bb7b9cb67-nsxsk   1/1     Running   0          25s   10.244.0.2   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="778" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy.png" alt="部署 3 個 traefik/whoami 的 Pod，IP 分別是 10.244.0.4、10.244.0.5、10.244.0.2" class="wp-image-13280" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy-300x146.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy-1024x498.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy-768x373.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-02-deploy-1536x747.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這份 YAML 跟第 12 篇的 Deployment 一樣，只是映像檔換成 <code>traefik/whoami:v1.12</code>、標籤是 <code>app: who</code>。3 個 Pod 各有一個 IP。</p>



<h3 class="wp-block-heading">步驟 3：刪掉一個 Pod，IP 就換了</h3>



<pre class="wp-block-code"><code>kubectl delete $(kubectl get pods -l app=who -o name | head -1); sleep 3; kubectl get pods -o wide</code></pre>



<pre class="wp-block-code"><code>pod "who-7bb7b9cb67-c6rbq" deleted from default namespace
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
who-7bb7b9cb67-dx4j4   1/1     Running   0          36s   10.244.0.5   minikube   &lt;none&gt;           &lt;none&gt;
who-7bb7b9cb67-flgj7   1/1     Running   0          4s    10.244.0.6   minikube   &lt;none&gt;           &lt;none&gt;
who-7bb7b9cb67-nsxsk   1/1     Running   0          36s   10.244.0.2   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="224" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes.png" alt="刪掉 IP 是 10.244.0.4 的 Pod，補回來的新 Pod flgj7 拿到 10.244.0.6" class="wp-image-13281" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes-300x42.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes-1024x143.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes-768x108.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-03-ip-changes-1536x215.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">被刪的 <code>c6rbq</code> 是 <code>10.244.0.4</code>，補回來的 <code>flgj7</code> 拿到 <code>10.244.0.6</code>。<strong>這就是為什麼不能寫死 Pod IP。</strong></p>



<h3 class="wp-block-heading">步驟 4：建一個 ClusterIP Service</h3>



<pre class="wp-block-code"><code>cat &gt; svc.yaml &lt;&lt;'EOF'
apiVersion: v1
kind: Service
metadata:
  name: who
spec:
  type: ClusterIP
  selector:
    app: who
  ports:
  - port: 80
    targetPort: 80
EOF
kubectl apply -f svc.yaml; kubectl get service who</code></pre>



<pre class="wp-block-code"><code>service/who created
NAME   TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
who    ClusterIP   10.101.20.235   &lt;none&gt;        80/TCP    0s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1541" height="896" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip.png" alt="建立 ClusterIP 類型的 Service who，CLUSTER-IP 是 10.101.20.235、Port 80" class="wp-image-13282" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip.png 1541w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip-300x174.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip-1024x595.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip-768x447.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-04-clusterip-1536x893.png 1536w" sizes="(max-width: 1541px) 100vw, 1541px" /></figure>


<ul class="wp-block-list">
<li><code>type: ClusterIP</code>：類型（不寫也是 ClusterIP，這裡寫出來比較清楚）</li>

<li><code>selector: app: who</code>：把流量送給標籤 <code>app=who</code> 的 Pod</li>

<li><code>port: 80</code>：Service 自己的 Port；<code>targetPort: 80</code>：送到 Pod 的哪個 Port</li>
</ul>



<p class="wp-block-paragraph">Service 拿到一個固定的 IP <code>10.101.20.235</code>。注意它跟 Pod 的 <code>10.244.x.x</code> 是不同的網段。</p>



<h3 class="wp-block-heading">步驟 5：看 Service 背後是哪些 Pod</h3>



<pre class="wp-block-code"><code>kubectl get endpointslices -l kubernetes.io/service-name=who; kubectl get endpoints who</code></pre>



<pre class="wp-block-code"><code>NAME        ADDRESSTYPE   PORTS   ENDPOINTS                          AGE
who-b6pvs   IPv4          80      10.244.0.5,10.244.0.6,10.244.0.2   6s
Warning: v1 Endpoints is deprecated in v1.33+; use discovery.k8s.io/v1 EndpointSlice
NAME   ENDPOINTS                                   AGE
who    10.244.0.2:80,10.244.0.5:80,10.244.0.6:80   6s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="259" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints.png" alt="EndpointSlice 列出 3 個 Pod 的 IP；kubectl get endpoints 跳出 v1 Endpoints is deprecated in v1.33+ 的警告" class="wp-image-13283" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints-1024x166.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints-768x124.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-05-endpoints-1536x249.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">兩個指令看到的是同一件事：Service 背後就是那 3 個 Pod 的 IP（包括新的 <code>10.244.0.6</code>）。</p>



<p class="wp-block-paragraph">注意第二個指令的警告：<strong>舊的 Endpoints 從 Kubernetes 1.33 起標為棄用，改用 EndpointSlice</strong>。網路上的舊教學幾乎都教 <code>kubectl get endpoints</code>，現在還能用但會跳警告，建議改看 EndpointSlice（<a href="https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/">Kubernetes 官方說明：EndpointSlices</a>）。</p>



<h3 class="wp-block-heading">步驟 6：從另一個 Pod 用名字連 Service</h3>



<p class="wp-block-paragraph">開一個臨時的 busybox Pod，在裡面查 DNS、連 6 次 <code>http://who</code>：</p>



<pre class="wp-block-code"><code>kubectl run tmp --image=busybox:1.37 --rm -i --restart=Never -- sh -c 'sleep 2; nslookup who.default.svc.cluster.local. | grep -A1 Name; for i in 1 2 3 4 5 6; do wget -qO- http://who | grep Hostname; done'</code></pre>



<pre class="wp-block-code"><code>All commands and output from this session will be recorded in container logs, including credentials and sensitive information passed through the command prompt.
If you don't see a command prompt, try pressing enter.
Name:   who.default.svc.cluster.local
Address: 10.101.20.235
Hostname: who-7bb7b9cb67-nsxsk
Hostname: who-7bb7b9cb67-nsxsk
Hostname: who-7bb7b9cb67-nsxsk
Hostname: who-7bb7b9cb67-nsxsk
Hostname: who-7bb7b9cb67-dx4j4
Hostname: who-7bb7b9cb67-dx4j4
pod "tmp" deleted from default namespace</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="358" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod.png" alt="臨時 Pod 裡 nslookup 查到 who.default.svc.cluster.local 是 10.101.20.235，連 6 次 http://who 分別由 nsxsk 和 dx4j4 回應" class="wp-image-13284" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod-300x67.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod-1024x229.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod-768x172.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06-from-pod-1536x344.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--rm -i</code>：跑完就自動刪掉這個臨時 Pod，<code>-i</code> 是把輸出接回你的畫面；最上面兩行英文是 kubectl 的固定提醒，不用理</li>

<li><code>nslookup</code> 查到 <code>who.default.svc.cluster.local</code> 的 IP 就是 Service 的 <code>10.101.20.235</code></li>

<li>連 6 次，回應的 Pod 有 <code>nsxsk</code>（4 次）和 <code>dx4j4</code>（2 次）</li>
</ul>



<p class="wp-block-paragraph"><strong>流量不是輪流分配的</strong>。Minikube 的 kube-proxy 用的是隨機挑選，次數少時會看到某個 Pod 被挑到比較多次，連的次數夠多才會接近平均。</p>



<h3 class="wp-block-heading">步驟 7：從 Cloud Shell 連 ClusterIP，連不到</h3>



<pre class="wp-block-code"><code>curl -s --max-time 5 $(kubectl get svc who -o jsonpath='{.spec.clusterIP}') || echo 'cannot reach ClusterIP from Cloud Shell'</code></pre>



<pre class="wp-block-code"><code>cannot reach ClusterIP from Cloud Shell</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="100" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside.png" alt="從 Cloud Shell 用 curl 連 ClusterIP 等 5 秒失敗，印出 cannot reach ClusterIP from Cloud Shell" class="wp-image-13285" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside-300x19.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside-1024x64.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside-768x48.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-07-clusterip-outside-1536x96.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>--max-time 5</code> 是最多等 5 秒；<code>||</code> 是「前面失敗才執行後面」。Cloud Shell 是叢集外面，ClusterIP 只在叢集裡有效，所以連不到。<strong>這正是 ClusterIP 的用意：不讓外面的人碰。</strong></p>



<h3 class="wp-block-heading">步驟 8：NodePort，從節點的 IP 連進去</h3>



<p class="wp-block-paragraph"><code>kubectl expose</code> 可以直接幫 Deployment 開 Service，這次指定 <code>--type=NodePort</code>：</p>



<pre class="wp-block-code"><code>kubectl expose deployment who --name=who-np --type=NodePort --port=80; sleep 3; kubectl get service who-np; NP=$(kubectl get svc who-np -o jsonpath='{.spec.ports[0].nodePort}'); echo node IP $(minikube ip), nodePort $NP; for i in 1 2 3; do curl -s $(minikube ip):$NP | grep Hostname; done</code></pre>



<pre class="wp-block-code"><code>service/who-np exposed
NAME     TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
who-np   NodePort   10.111.59.228   &lt;none&gt;        80:31194/TCP   3s
node IP 192.168.49.2, nodePort 31194
Hostname: who-7bb7b9cb67-flgj7
Hostname: who-7bb7b9cb67-flgj7
Hostname: who-7bb7b9cb67-nsxsk</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="271" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport.png" alt="建立 NodePort 類型的 who-np，PORT(S) 80:31194；從 Cloud Shell curl 192.168.49.2:31194 拿到 flgj7 和 nsxsk 的回應" class="wp-image-13286" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport-300x51.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport-1024x173.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport-768x130.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-08-nodeport-1536x260.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>80:31194/TCP</code>：Kubernetes 從 30000～32767 隨機挑了 <strong>31194</strong></li>

<li><code>minikube ip</code> 是節點的 IP <code>192.168.49.2</code></li>

<li>從 Cloud Shell 連 <code>192.168.49.2:31194</code>，連得到了，而且也是分給不同 Pod</li>
</ul>



<p class="wp-block-paragraph"><strong>指令中的 <code>sleep 3</code> 不能省</strong>：實測第一次沒等，Service 一建好就 curl，什麼都沒拿到；節點上的網路規則要一兩秒才會設好。</p>



<h3 class="wp-block-heading">步驟 9：LoadBalancer，EXTERNAL-IP 一直 pending</h3>



<pre class="wp-block-code"><code>kubectl expose deployment who --name=who-lb --type=LoadBalancer --port=80; sleep 5; kubectl get service who-lb</code></pre>



<pre class="wp-block-code"><code>service/who-lb exposed
NAME     TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
who-lb   LoadBalancer   10.99.243.69   &lt;pending&gt;     80:30815/TCP   5s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="161" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending.png" alt="建立 LoadBalancer 類型的 who-lb，EXTERNAL-IP 顯示 pending，PORT(S) 80:30815" class="wp-image-13287" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending-300x30.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending-1024x103.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending-768x77.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-09-lb-pending-1536x155.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>EXTERNAL-IP &lt;pending&gt;</code>（等待中）：Kubernetes 在等雲端給它一個負載平衡器，但 Minikube 不在雲端上，所以會一直等。<code>80:30815/TCP</code> 也證明 LoadBalancer 自帶一個 NodePort。</p>



<h3 class="wp-block-heading">步驟 10：開 minikube tunnel，拿到 IP</h3>



<p class="wp-block-paragraph"><strong><code>minikube tunnel</code> 是 Minikube 用來模擬雲端負載平衡器的工具</strong>：它在背景執行，幫 LoadBalancer Service 填上 IP，並把 Cloud Shell 的網路接過去：</p>



<pre class="wp-block-code"><code>minikube tunnel &gt; /tmp/tunnel.log 2&gt;&amp;1 &amp; sleep 15; kubectl get service who-lb; LB=$(kubectl get svc who-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}'); for i in 1 2 3; do curl -s --max-time 5 $LB | grep Hostname; done</code></pre>



<pre class="wp-block-code"><code>[1] 65899
NAME     TYPE           CLUSTER-IP     EXTERNAL-IP    PORT(S)        AGE
who-lb   LoadBalancer   10.99.243.69   10.99.243.69   80:30815/TCP   26s
Hostname: who-7bb7b9cb67-dx4j4
Hostname: who-7bb7b9cb67-dx4j4
Hostname: who-7bb7b9cb67-flgj7</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="228" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel.png" alt="開 minikube tunnel 後 who-lb 的 EXTERNAL-IP 變成 10.99.243.69，curl 拿到 dx4j4 和 flgj7 的回應" class="wp-image-13288" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel-300x43.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel-1024x146.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel-768x109.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-10-lb-tunnel-1536x219.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>EXTERNAL-IP</code> 從 <code>&lt;pending&gt;</code> 變成 <code>10.99.243.69</code>，curl 這個 IP 就連到 Pod 了。Minikube 的做法是直接把 ClusterIP 當成對外 IP，所以兩個欄位一樣；<strong>在 GKE 上會是一個真正的公開 IP</strong>，兩個欄位不會一樣。</p>



<h3 class="wp-block-heading">步驟 11：三種 Service 一起看</h3>



<pre class="wp-block-code"><code>kubectl get services</code></pre>



<pre class="wp-block-code"><code>NAME         TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)        AGE
kubernetes   ClusterIP      10.96.0.1       &lt;none&gt;         443/TCP        2m20s
who          ClusterIP      10.101.20.235   &lt;none&gt;         80/TCP         89s
who-lb       LoadBalancer   10.99.243.69    10.99.243.69   80:30815/TCP   37s
who-np       NodePort       10.111.59.228   &lt;none&gt;         80:31194/TCP   48s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="320" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services.png" alt="kubectl get services 同時列出 ClusterIP、NodePort、LoadBalancer 三種 Service 和內建的 kubernetes" class="wp-image-13289" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services-300x60.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services-1024x205.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services-768x154.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-11-all-services-1536x307.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">三個 Service 都指向同一群 Pod（標籤 <code>app=who</code>），只是開放的範圍不同：<code>who</code> 只給叢集內、<code>who-np</code> 多開了節點的 31194、<code>who-lb</code> 再多一個對外 IP。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. Cloud Shell 的 Minikube 預設設定，Pod 連 Service 會不通</h3>



<p class="wp-block-paragraph">第一次照預設的 <code>minikube start</code> 做，步驟 6 的結果是這樣：</p>



<pre class="wp-block-code"><code>;; connection timed out; no servers could be reached

wget: bad address 'who'
wget: bad address 'who'
（共 6 行）
pod "tmp" deleted from default namespace
pod default/tmp terminated (Error)</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="379" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail.png" alt="用預設網路設定時，臨時 Pod 的 nslookup 逾時、wget 回報 bad address who" class="wp-image-13290" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail-300x71.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail-1024x243.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail-768x182.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-06x-bridge-fail-1536x364.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">DNS 查不到、名字找不到。一步一步查下去，發現：</p>


<ul class="wp-block-list">
<li><strong>Pod 直接連另一個 Pod 的 IP：通</strong></li>

<li><strong>Pod 連 Service 的 IP（10.x.x.x）：逾時</strong></li>

<li>CoreDNS 的日誌一直出現 <code>Failed to watch</code>：連 CoreDNS 自己都連不到 API 伺服器的 Service，所以查不到任何名字</li>
</ul>



<p class="wp-block-paragraph">原因是 Minikube 預設的網路外掛是 bridge（網路橋接），它要讓「Pod → Service → 同一台機器上的 Pod」的封包正確繞回來，需要 Linux 核心的 <code>br_netfilter</code> 模組。在 Minikube 節點裡試著載入，回應是 <code>modprobe: FATAL: Module br_netfilter not found in directory /lib/modules/6.18.55+</code>，<strong>Cloud Shell 的系統核心沒有這個模組</strong>，自己也裝不了。</p>



<p class="wp-block-paragraph">解法是開叢集時加 <code>--cni=kindnet</code>，換一個不靠 bridge 的網路外掛。換完之後 DNS、Pod 連 Service 都正常，就是這篇的步驟 6。本系列之後的 K8s 篇都會用這個方式開叢集。在你自己的電腦或 GKE 上通常不會遇到這個問題。</p>



<h3 class="wp-block-heading">2. Service 剛建好就連，會連不到</h3>



<p class="wp-block-paragraph">步驟 8 第一次沒加 <code>sleep 3</code>，NodePort Service 建好的同一秒就 curl，三次都沒回應；等幾秒再連就通了。Service 建立後，每個節點上的 kube-proxy 要花一點時間把轉送規則設好。寫自動化腳本時記得等一下或重試。</p>



<h3 class="wp-block-heading">3. LoadBalancer 的 EXTERNAL-IP 跟 ClusterIP 一樣</h3>



<p class="wp-block-paragraph">開了 <code>minikube tunnel</code> 之後，EXTERNAL-IP 直接用 ClusterIP 的 <code>10.99.243.69</code>，這是 Minikube 模擬的做法。這個 IP 只有 Cloud Shell 自己連得到，不是真的公開 IP；GKE 才會給真正的公開 IP。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<p class="wp-block-paragraph">先關掉背景的 tunnel（<code>kill %1</code>），再刪 Service、Deployment 和叢集：</p>



<pre class="wp-block-code"><code>kill %1; sleep 2; kubectl delete service who who-np who-lb; kubectl delete -f who.yaml; kubectl get all; minikube delete | tail -1</code></pre>



<pre class="wp-block-code"><code>[1]+  Terminated              minikube tunnel &gt; /tmp/tunnel.log 2&gt;&amp;1
service "who" deleted from default namespace
service "who-np" deleted from default namespace
service "who-lb" deleted from default namespace
deployment.apps "who" deleted from default namespace
NAME                       READY   STATUS        RESTARTS   AGE
pod/who-7bb7b9cb67-dx4j4   1/1     Terminating   0          2m18s
pod/who-7bb7b9cb67-flgj7   1/1     Terminating   0          106s
pod/who-7bb7b9cb67-nsxsk   1/1     Terminating   0          2m18s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    &lt;none&gt;        443/TCP   2m28s
💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="382" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup.png" alt="關掉 minikube tunnel、刪掉三個 Service 和 Deployment，最後 minikube delete" class="wp-image-13291" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup-300x72.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup-1024x244.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup-768x183.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct13-shots-12-cleanup-1536x367.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Cloud Shell 和 Minikube 都不收費。<code>~/k8s-svc</code> 資料夾的 <code>who.yaml</code>、<code>svc.yaml</code> 會留著，第 14 篇講 Ingress 可以接著用。</p>



<p class="wp-block-paragraph"><strong>在 GKE 上不刪會怎樣</strong>：LoadBalancer 類型的 Service 會建一個 Google Cloud 的負載平衡器，Service 留著它就一直計費，練習完一定要 <code>kubectl delete service</code>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>Minikube</th><th>GKE</th></tr></thead><tbody><tr><td>ClusterIP</td><td>一樣</td><td>一樣</td></tr><tr><td>NodePort</td><td><code>minikube ip</code>:Port</td><td>節點 VM 的 IP:Port，還要開防火牆規則才連得到</td></tr><tr><td>LoadBalancer</td><td>要開 <code>minikube tunnel</code>，IP 只有本機連得到</td><td>自動建立 Google Cloud 的<strong>直通式網路負載平衡器</strong>，給一個公開 IP，<strong>會收費</strong></td></tr><tr><td>多個服務共用一個入口</td><td>Ingress（第 14 篇）</td><td>Ingress 或 Gateway，會建立應用程式負載平衡器</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">GKE 的 LoadBalancer Service 細節和收費，會在第 25 篇：<a href="https://dongdonggcp.com/2026/11/21/gke-deploy-artifact-registry-gateway-hpa/">GKE 部署教學：把 Minikube 的應用搬上 GKE（映像檔、Gateway、HPA）</a>實際做。防火牆的觀念可以先看<a href="https://dongdonggcp.com/2026/03/25/gcp-firewall-rules-how-to-setup/">GCP 防火牆規則怎麼設</a>。</p>



<p class="wp-block-paragraph"><strong>Cloud Run</strong> 不用 Service 這一層：部署完就直接給你一個 <code>https://</code> 開頭的網址，負載平衡和憑證都幫你處理好（<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">第 20 篇</a>）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「ClusterIP、NodePort、LoadBalancer 差在哪？」</strong>：開放範圍一層比一層大；ClusterIP 只給叢集內、NodePort 在每個節點開 30000～32767 的 Port、LoadBalancer 跟雲端要一個對外 IP；後者包含前者</li>

<li><strong>「為什麼不直接連 Pod IP？」</strong>：Pod 重建 IP 就換（實測 <code>.4</code> 換成 <code>.6</code>），Service 給一個固定的名字和 IP</li>

<li><strong>「Service 怎麼知道要送給哪些 Pod？」</strong>：selector 比對標籤，結果記在 EndpointSlice，Pod 變動會自動更新</li>

<li><strong>「Pod 裡怎麼找到別的服務？」</strong>：用 DNS 名字 <code>服務名.命名空間.svc.cluster.local</code>，同命名空間可以只寫服務名</li>

<li><strong>「服務很多，每個都開 LoadBalancer 有什麼問題？」</strong>：每個都是一個要收費的負載平衡器，改用 Ingress 共用入口</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKA、CKAD）</h3>



<p class="wp-block-paragraph">上機實作考（445 美元、2 小時；CKA 的「服務與網路」佔 20%，2026 年 11 月查 Linux Foundation 官方頁）。常見題型：</p>


<ul class="wp-block-list">
<li>幫某個 Deployment 開一個指定類型、指定 Port 的 Service（<code>kubectl expose</code>，最快）</li>

<li>指定 NodePort 的號碼（要改 YAML 的 <code>nodePort</code> 欄位）</li>

<li>用臨時 Pod 測試 Service 連不連得到，或查 DNS 名稱（步驟 6 的做法）</li>

<li>Service 連不到 Pod 時找原因：最常見是 selector 的標籤跟 Pod 對不上，EndpointSlice 會是空的</li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「只給叢集內部用」「資料庫」</td><td>ClusterIP</td></tr><tr><td>「30000～32767」「節點 IP 加 Port」</td><td>NodePort</td></tr><tr><td>「對外 IP」「雲端負載平衡器」</td><td>LoadBalancer</td></tr><tr><td>「Service 後面有哪些 Pod」</td><td>EndpointSlice（舊的 Endpoints 已棄用）</td></tr><tr><td>「服務名稱解析」</td><td>CoreDNS、<code>.svc.cluster.local</code></td></tr><tr><td>「多個服務共用一個 IP、用網址路徑分流」</td><td>Ingress（第 14 篇）</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">ClusterIP、NodePort、LoadBalancer 要怎麼選？</h3>



<p class="wp-block-paragraph">叢集內部互連（網站連資料庫、服務互叫）用 ClusterIP；練習或沒有雲端負載平衡器時，用 NodePort 從節點 IP 加 30000～32767 的 Port 連；正式環境要給外面的人連，在雲端用 LoadBalancer 拿一個對外 IP。服務多時，改用 Ingress 讓多個服務共用一個 LoadBalancer。</p>



<h3 class="wp-block-heading">為什麼 LoadBalancer 的 EXTERNAL-IP 一直是 pending？</h3>



<p class="wp-block-paragraph">LoadBalancer 需要雲端服務商幫忙建負載平衡器。Minikube、自己機房的叢集沒有這個功能，所以會一直顯示 <code>&lt;pending&gt;</code>。Minikube 可以開 <code>minikube tunnel</code> 模擬，實測開了 15 秒後就拿到 IP；在 GKE 上則會由 Google Cloud 建立負載平衡器，配一個真正的公開 IP。</p>



<h3 class="wp-block-heading">在叢集外面可以連 ClusterIP 嗎？</h3>



<p class="wp-block-paragraph">不行。ClusterIP 只在叢集內部有效，實測從 Cloud Shell curl ClusterIP 等 5 秒失敗。要從外面連，可以改用 NodePort、LoadBalancer，或臨時用 <code>kubectl port-forward svc/名字 本機Port:服務Port</code>（第 10 篇）。</p>



<h3 class="wp-block-heading">kubectl get endpoints 跳出 deprecated 警告怎麼辦？</h3>



<p class="wp-block-paragraph">v1 的 Endpoints 從 Kubernetes 1.33 起標為棄用，建議改用 EndpointSlice。實測 Kubernetes v1.35.1 執行 <code>kubectl get endpoints</code> 會出現 <code>Warning: v1 Endpoints is deprecated in v1.33+</code>。改用 <code>kubectl get endpointslices -l kubernetes.io/service-name=服務名</code> 就能看到同樣的 Pod IP 清單。</p>



<h3 class="wp-block-heading">Minikube 裡 Pod 用名字連不到 Service，nslookup 逾時怎麼辦？</h3>



<p class="wp-block-paragraph">如果你在 Cloud Shell 用預設的 <code>minikube start</code>，可能會遇到 Pod 連 Service 的 IP 逾時、CoreDNS 日誌出現 <code>Failed to watch</code>。原因是 Cloud Shell 核心沒有 <code>br_netfilter</code> 模組，預設的 bridge 網路外掛不能正常轉送。<code>minikube delete</code> 之後改用 <code>minikube start --cni=kindnet</code> 重開就會正常。</p>



<h3 class="wp-block-heading">Service 的流量是輪流分給每個 Pod 嗎？</h3>



<p class="wp-block-paragraph">不一定。Minikube 預設的 kube-proxy 是隨機挑選，實測連 6 次，4 次落在同一個 Pod、2 次在另一個。連線次數夠多時會接近平均分配，但不是嚴格的輪流。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>Service 給一群 Pod 一個固定名字和 IP</strong>：Pod 重建 IP 會換（實測 <code>.4</code> → <code>.6</code>），Service 透過 selector 和 EndpointSlice 自動追蹤</li>

<li><strong>三種類型一層包一層</strong>：ClusterIP（只給叢集內）→ NodePort（節點 IP＋30000～32767）→ LoadBalancer（對外 IP，雲端會收費）</li>

<li><strong>叢集內用 DNS 名字連</strong>：<code>who</code> 或 <code>who.default.svc.cluster.local</code></li>

<li><strong>Cloud Shell 的 Minikube 要加 <code>--cni=kindnet</code></strong>：預設 bridge 外掛因為核心缺 <code>br_netfilter</code>，Pod 連 Service 會不通</li>

<li><strong>舊的 <code>kubectl get endpoints</code> 已棄用</strong>，改看 EndpointSlice</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 6 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-network-container-communication-flask-mysql/">容器之間怎麼連線？Docker Network 與 Port 對應實作</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></li>

<li>上一篇：第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>

<li>下一篇：第 14 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-ingress-gateway-api/">Ingress 是什麼？用網址路徑把流量分給不同服務（含 Gateway API）</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2025/11/19/what-is-dns-domain-name-system-guide/">DNS 是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2026/03/25/gcp-firewall-rules-how-to-setup/">GCP 防火牆規則怎麼設</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">Service 讓 Pod 有了固定的入口，下一步是讓好幾個服務共用同一個對外網址。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "ClusterIP、NodePort、LoadBalancer 要怎麼選？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "叢集內部互連（網站連資料庫、服務互叫）用 ClusterIP；練習或沒有雲端負載平衡器時，用 NodePort 從節點 IP 加 30000～32767 的 Port 連；正式環境要給外面的人連，在雲端用 LoadBalancer 拿一個對外 IP。服務多時，改用 Ingress 讓多個服務共用一個 LoadBalancer。"
      }
    },
    {
      "@type": "Question",
      "name": "為什麼 LoadBalancer 的 EXTERNAL-IP 一直是 pending？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "LoadBalancer 需要雲端服務商幫忙建負載平衡器。Minikube、自己機房的叢集沒有這個功能，所以會一直顯示 `<pending>`。Minikube 可以開 `minikube tunnel` 模擬，實測開了 15 秒後就拿到 IP；在 GKE 上則會由 Google Cloud 建立負載平衡器，配一個真正的公開 IP。"
      }
    },
    {
      "@type": "Question",
      "name": "在叢集外面可以連 ClusterIP 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不行。ClusterIP 只在叢集內部有效，實測從 Cloud Shell curl ClusterIP 等 5 秒失敗。要從外面連，可以改用 NodePort、LoadBalancer，或臨時用 `kubectl port-forward svc/名字 本機Port:服務Port`（第 10 篇）。"
      }
    },
    {
      "@type": "Question",
      "name": "kubectl get endpoints 跳出 deprecated 警告怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "v1 的 Endpoints 從 Kubernetes 1.33 起標為棄用，建議改用 EndpointSlice。實測 Kubernetes v1.35.1 執行 `kubectl get endpoints` 會出現 `Warning: v1 Endpoints is deprecated in v1.33+`。改用 `kubectl get endpointslices -l kubernetes.io/service-name=服務名` 就能看到同樣的 Pod IP 清單。"
      }
    },
    {
      "@type": "Question",
      "name": "Minikube 裡 Pod 用名字連不到 Service，nslookup 逾時怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "如果你在 Cloud Shell 用預設的 `minikube start`，可能會遇到 Pod 連 Service 的 IP 逾時、CoreDNS 日誌出現 `Failed to watch`。原因是 Cloud Shell 核心沒有 `br_netfilter` 模組，預設的 bridge 網路外掛不能正常轉送。`minikube delete` 之後改用 `minikube start --cni=kindnet` 重開就會正常。"
      }
    },
    {
      "@type": "Question",
      "name": "Service 的流量是輪流分給每個 Pod 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定。Minikube 預設的 kube-proxy 是隨機挑選，實測連 6 次，4 次落在同一個 Pod、2 次在另一個。連線次數夠多時會接近平均分配，但不是嚴格的輪流。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">K8s Service 怎麼選？ClusterIP、NodePort、LoadBalancer 差在哪</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-pod-yaml-tutorial</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:33:30 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13257</guid>

					<description><![CDATA[<p>K8s Pod 是什麼？Cloud Shell 實測寫第一份 Pod YAML、kubectl apply 跑起 nginx；兩個容器共用 localhost、改 Port 被 Forbidden、刪 Pod 為什麼等 30 秒。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Pod 是 K8s 最小的部署單位，裝一個或幾個容器、共用同一個 IP；寫一份 YAML 再 kubectl apply 就建出來。</strong></p>



<p class="wp-block-paragraph">用 Docker 時，你直接跑「容器」；到了 Kubernetes，你跑的是「Pod」。很多人卡在這一步：Pod 到底跟容器差在哪？為什麼要多包一層？這篇用 Cloud Shell 實際做給你看：寫第一份 Pod 的 YAML、把 nginx 跑起來；做一個「兩個容器住同一個 Pod」，證明它們共用網路；再試著改 Pod 的設定，看 Kubernetes 什麼能改、什麼會被擋下來。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 11 篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。Minikube 怎麼開、kubectl 基本指令請先看第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a>。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-01-pod.png" alt="Pod 是一份套餐、容器是裡面的菜：實測的 two 這個 Pod 裡有 nginx 和 helper 兩個容器，共用同一個 IP 和主機名稱" class="wp-image-13239" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-01-pod.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-01-pod-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-01-pod-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-01-pod-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>Kubernetes 的一切都繞著 Pod 轉</strong>：Deployment 管的是 Pod、Service 把流量送給 Pod、自動擴展加的也是 Pod。Pod 沒搞懂，後面每一篇都會卡</li>

<li><strong>YAML 是 Kubernetes 的語言</strong>：正式環境幾乎不會用指令一個一個建，而是把設定寫成 YAML 檔、放進 Git 管理。看不懂 YAML，就看不懂同事寫的設定</li>

<li><strong>排錯要看 Pod 的狀態</strong>：<code>Pending</code>、<code>ContainerCreating</code>、<code>Completed</code>、<code>CrashLoopBackOff</code> 這些字代表什麼，決定你下一步去哪裡找問題</li>

<li><strong>證照的基本題</strong>：CKAD、CKA 都是上機考，「寫一個 Pod 的 YAML、用指定的映像檔和標籤」是最基本的題型</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Pod 是什麼</h2>



<p class="wp-block-paragraph"><strong>Pod 是 Kubernetes 裡最小的部署單位，裡面裝一個或幾個容器，這些容器共用同一個網路位址和儲存空間。</strong> Kubernetes 不直接管容器，它排程、重開、刪除的對象都是 Pod（<a href="https://kubernetes.io/docs/concepts/workloads/pods/">Kubernetes 官方說明：Pods</a>）。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳出餐是以「一份套餐」為單位，不是一道一道菜分開送。套餐裡可能只有主餐，也可能附一杯飲料；不管幾道菜，都放在同一個托盤、送到同一桌</li>

<li><strong>來龍去脈</strong>：pod 是英文的「豆莢」，一個豆莢裡有幾顆豆子；一群鯨魚英文也叫 pod，而 Docker 的標誌是鯨魚。Kubernetes 設計 Pod，是因為有些程式要「緊緊綁在一起」，例如網站和幫它收日誌的小程式，要在同一台機器、能用 localhost 互相連線</li>

<li><strong>為什麼要學</strong>：你在 K8s 看到的狀態幾乎都是 Pod 的狀態；面試問「Pod 和容器差在哪」是送分題，答不出來就是扣分題</li>
</ul>



<h3 class="wp-block-heading">Pod 和容器差在哪</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>容器（Container）</th><th>Pod</th></tr></thead><tbody><tr><td>誰在管</td><td>容器執行環境（Docker、containerd）</td><td>Kubernetes</td></tr><tr><td>裝什麼</td><td>一個程式和它需要的檔案</td><td>一個或幾個容器</td></tr><tr><td>網路</td><td>Docker 預設每個容器自己一個 IP</td><td>同一個 Pod 裡的容器<strong>共用一個 IP</strong>，用 localhost 互連</td></tr><tr><td>被排程到哪</td><td>你自己決定在哪台機器跑</td><td>排程器決定放哪個節點，<strong>同一個 Pod 的容器一定在同一個節點</strong></td></tr></tbody></table></figure>



<h3 class="wp-block-heading">一個 Pod 放一個容器，還是好幾個？</h3>



<p class="wp-block-paragraph"><strong>大部分情況一個 Pod 只放一個容器。</strong> 只有「必須在同一台機器、要共用網路或檔案、一起生一起死」的容器才放一起，例如主程式旁邊放一個負責轉送日誌或更新設定的小幫手。這種小幫手有個名字叫 <strong>sidecar（邊車）</strong>，就像機車旁邊掛的那個座位，跟著主車走。</p>



<p class="wp-block-paragraph">判斷方法：問自己「這兩個程式可以分開擴展嗎？」網站要 10 份、資料庫只要 1 份，就<strong>不能</strong>放同一個 Pod；不然擴展網站時資料庫也會跟著變 10 份。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">YAML 是什麼</h2>



<p class="wp-block-paragraph"><strong>YAML 是一種用「縮排」表示層次的設定檔格式</strong>，Kubernetes 的設定幾乎都用它寫。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：像用條列式寫的購物清單，大項下面縮排寫小項，一眼就看得出誰屬於誰</li>

<li><strong>來龍去脈</strong>：YAML 最早是「Yet Another Markup Language」（又一種標記語言）的縮寫，後來改成「YAML Ain&#8217;t Markup Language」（YAML 不是標記語言），強調它是拿來放資料的，不是拿來排版的。它比 JSON 少了大括號和引號，人比較好讀</li>

<li><strong>為什麼要學</strong>：Kubernetes、Docker Compose（<a href="https://dongdonggcp.com/2026/11/18/docker-compose-tutorial-flask-mysql/">第 7 篇</a>）、Cloud Build、GitHub Actions 的設定都是 YAML，學一次到處用</li>
</ul>



<p class="wp-block-paragraph">YAML 只要記住四條規則：</p>


<ol class="wp-block-list">
<li><strong><code>名字: 值</code></strong>：冒號後面一定要有一個空白</li>

<li><strong>縮排代表層次</strong>：一律用空白（通常 2 格），<strong>不能用 Tab 鍵</strong></li>

<li><strong><code>-</code> 開頭是清單的一項</strong>：像 <code>containers:</code> 底下的 <code>- name: nginx</code>，代表「容器清單的第一個」</li>

<li><strong>大小寫有差</strong>：<code>containerPort</code> 寫成 <code>containerport</code> 就不認得</li>
</ol>



<h3 class="wp-block-heading">Kubernetes 的 YAML 都有這 4 塊</h3>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-02-yaml.png" alt="K8s YAML 的骨架：apiVersion 是規格版本、kind 是要建什麼、metadata 是名字和標籤、spec 是想要的樣子；縮排一律用空白不能用 Tab" class="wp-image-13240" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-02-yaml.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-02-yaml-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-02-yaml-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-02-yaml-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>欄位</th><th>白話</th><th>這篇的例子</th></tr></thead><tbody><tr><td><code>apiVersion</code></td><td>用哪一版的規格寫的</td><td><code>v1</code>（Pod 屬於最核心的那組，版本就叫 v1）</td></tr><tr><td><code>kind</code></td><td>要建什麼東西</td><td><code>Pod</code></td></tr><tr><td><code>metadata</code></td><td>名字、標籤這類「身分資料」</td><td><code>name: web</code>、<code>labels: app: web</code></td></tr><tr><td><code>spec</code></td><td>你想要它長什麼樣子（規格）</td><td>用哪個映像檔、開哪個 Port</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">還有第 5 塊 <code>status</code>（狀態）是 Kubernetes 自己填的，記錄「現在實際長什麼樣子」，你不用寫。</p>



<p class="wp-block-paragraph"><strong>標籤（label）是貼在東西上的「鍵＝值」小貼紙</strong>，例如 <code>app=web</code>。Kubernetes 很多功能靠標籤找東西：Service 用標籤找它要送流量的 Pod、Deployment 用標籤認哪些 Pod 歸它管。所以第一份 YAML 就養成貼標籤的習慣。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Pod 的一生：phase 和 STATUS</h2>



<p class="wp-block-paragraph"><strong>phase（階段）是 Pod 目前在生命週期的哪一段</strong>，官方只有 5 種（<a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/">Pod Lifecycle</a>）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>phase</th><th>白話</th></tr></thead><tbody><tr><td><code>Pending</code></td><td>已經被接受，但還沒全部跑起來：可能在等排程器挑節點、或還在下載映像檔</td></tr><tr><td><code>Running</code></td><td>已經分到節點，至少有一個容器正在跑</td></tr><tr><td><code>Succeeded</code></td><td>所有容器都正常結束了，而且不會再重開</td></tr><tr><td><code>Failed</code></td><td>所有容器都結束了，至少一個是失敗結束</td></tr><tr><td><code>Unknown</code></td><td>叢集聯絡不上 Pod 所在的節點，不知道它的狀況</td></tr></tbody></table></figure>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-03-lifecycle.png" alt="Pod 的一生：Pending 排節點拉映像檔、Running 至少一個容器在跑、最後 Succeeded 或 Failed；STATUS 欄的 ContainerCreating、Completed 是更細的狀態" class="wp-image-13241" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-03-lifecycle.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-03-lifecycle-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-03-lifecycle-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-cards-03-lifecycle-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">但 <code>kubectl get pods</code> 的 <code>STATUS</code> 欄常常顯示別的字，例如 <code>ContainerCreating</code>、<code>Completed</code>、<code>CrashLoopBackOff</code>。這些是<strong>更細的原因</strong>，不是 phase。例如 <code>ContainerCreating</code> 的 phase 其實還是 <code>Pending</code>；<code>Completed</code> 的 phase 是 <code>Succeeded</code>。實作會用 <code>-o jsonpath</code> 直接把 phase 印出來對照。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：寫第一個 Pod，再做一個兩個容器的 Pod</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 20 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>，跳出「授權 Cloud Shell」按「拒絕」就好。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~$」。</p>



<h3 class="wp-block-heading">步驟 1：開叢集</h3>



<pre class="wp-block-code"><code>minikube start | tail -2</code></pre>



<pre class="wp-block-code"><code>（前面省略：版本提醒和硬碟空間警告）
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="364" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start.png" alt="minikube start 完成，kubectl 已經設定好連到 minikube 叢集" class="wp-image-13242" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start-300x68.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start-1024x233.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start-768x175.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-01-start-1536x349.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>| tail -2</code> 是只看最後 2 行。看到 <code>Done!</code> 就是好了。硬碟空間警告可以先不理，第 10 篇的「實測時的意外」有說明。</p>



<h3 class="wp-block-heading">步驟 2：讓 kubectl 幫你產生 YAML 草稿</h3>



<p class="wp-block-paragraph">自己從零寫 YAML 很容易漏欄位。kubectl 可以先「假裝建立」，把它會送出的 YAML 印給你看：</p>



<pre class="wp-block-code"><code>kubectl run web --image=nginx:1.31 --dry-run=client -o yaml</code></pre>



<pre class="wp-block-code"><code>apiVersion: v1
kind: Pod
metadata:
  labels:
    run: web
  name: web
spec:
  containers:
  - image: nginx:1.31
    name: web
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1540" height="804" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run.png" alt="kubectl run --dry-run=client -o yaml 印出一份 Pod 的 YAML 草稿，有 apiVersion、kind、metadata、spec" class="wp-image-13243" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run.png 1540w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run-300x157.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run-1024x535.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run-768x401.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-02-dry-run-1536x802.png 1536w" sizes="(max-width: 1540px) 100vw, 1540px" /></figure>


<ul class="wp-block-list">
<li><code>kubectl run</code>：用指令建一個 Pod</li>

<li><code>--dry-run=client</code>：<strong>只在你這邊模擬，不真的送到叢集</strong>（dry run 是「空跑、預演」的意思）</li>

<li><code>-o yaml</code>：把結果用 YAML 印出來</li>
</ul>



<p class="wp-block-paragraph">4 塊骨架都有了。注意 kubectl 自動貼的標籤是 <code>run: web</code>、容器名字也叫 <code>web</code>，跟我們等一下自己寫的不一樣。想存成檔案，可以在後面加 <code>&gt; pod.yaml</code>，這是 CKAD、CKA 考試很常用的省時技巧。</p>



<h3 class="wp-block-heading">步驟 3：自己寫一份 Pod 的 YAML</h3>



<p class="wp-block-paragraph">建一個資料夾，用 <code>cat &gt; 檔名 &lt;&lt;'EOF'</code> 把整段內容貼進檔案（從這行貼到 <code>EOF</code> 那行，一次全部貼上就好，不用一行一行打）：</p>



<pre class="wp-block-code"><code>mkdir -p ~/k8s-pod &amp;&amp; cd ~/k8s-pod
cat &gt; pod.yaml &lt;&lt;'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: web
  labels:
    app: web
spec:
  containers:
  - name: nginx
    image: nginx:1.31
    ports:
    - containerPort: 80
EOF
cat pod.yaml</code></pre>



<pre class="wp-block-code"><code>apiVersion: v1
kind: Pod
metadata:
  name: web
  labels:
    app: web
spec:
  containers:
  - name: nginx
    image: nginx:1.31
    ports:
    - containerPort: 80</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="943" height="1402" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-03-pod-yaml.png" alt="用 cat 和 EOF 建立 pod.yaml，內容是一個叫 web 的 Pod，容器用 nginx:1.31、開 80 Port" class="wp-image-13244" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-03-pod-yaml.png 943w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-03-pod-yaml-202x300.png 202w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-03-pod-yaml-689x1024.png 689w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-03-pod-yaml-768x1142.png 768w" sizes="(max-width: 943px) 100vw, 943px" /></figure>



<p class="wp-block-paragraph">逐行看：</p>


<ul class="wp-block-list">
<li><code>name: web</code>：這個 Pod 叫 web</li>

<li><code>labels: app: web</code>：貼一張 <code>app=web</code> 的標籤</li>

<li><code>containers:</code> 底下 <code>- name: nginx</code>：容器清單的第一個，叫 nginx</li>

<li><code>image: nginx:1.31</code>：用 nginx 的 1.31 版。<strong>不寫版本號就是 <code>latest</code></strong>，哪天官方更新了，你的 Pod 重建時就會換版本，<a href="https://dongdonggcp.com/2026/11/18/docker-image-vs-container-layer-tag/">第 3 篇</a>講過這個坑</li>

<li><code>containerPort: 80</code>：說明這個容器在 80 Port 提供服務（Port 是同一台機器上不同服務的分機號碼）。這行比較像「說明書」，不寫也連得到，但寫清楚比較好維護</li>
</ul>



<p class="wp-block-paragraph"><code>mkdir -p ~/k8s-pod &amp;&amp; cd ~/k8s-pod</code> 是建資料夾再走進去，所以提示字元變成 <code>~/k8s-pod$</code>。</p>



<h3 class="wp-block-heading">步驟 4：kubectl apply，把 YAML 交給叢集</h3>



<pre class="wp-block-code"><code>kubectl apply -f pod.yaml; kubectl get pod web -o wide; sleep 15; kubectl get pod web -o wide</code></pre>



<pre class="wp-block-code"><code>pod/web created
NAME   READY   STATUS              RESTARTS   AGE   IP       NODE       NOMINATED NODE   READINESS GATES
web    0/1     ContainerCreating   0          0s    &lt;none&gt;   minikube   &lt;none&gt;           &lt;none&gt;
NAME   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
web    1/1     Running   0          15s   10.244.0.3   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="245" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply.png" alt="kubectl apply -f pod.yaml 建立 web，剛建好是 ContainerCreating、15 秒後變成 Running，IP 10.244.0.3" class="wp-image-13245" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply-300x46.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply-1024x157.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply-768x118.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-04-apply-1536x235.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong><code>kubectl apply -f 檔案</code> 是「照這份檔案，讓叢集變成這個樣子」</strong>：沒有就建立、有就更新。同一個指令跑兩次不會建出兩個 Pod，這就是第 9 篇講的「宣告式」。</p>



<p class="wp-block-paragraph">剛建好的那一刻：<code>STATUS ContainerCreating</code>（容器建立中）、<code>IP &lt;none&gt;</code>，但 <code>NODE</code> 已經是 minikube，代表排程器已經挑好節點，kubelet 正在拉映像檔。15 秒後變成 <code>Running</code>，拿到 IP <code>10.244.0.3</code>。<code>READY 1/1</code> 是「1 個容器裡有 1 個準備好了」。</p>



<h3 class="wp-block-heading">步驟 5：看標籤和 phase</h3>



<pre class="wp-block-code"><code>kubectl get pod web --show-labels; kubectl get pod web -o jsonpath='{.status.phase} {.status.podIP} {.spec.nodeName}{"\n"}'</code></pre>



<pre class="wp-block-code"><code>NAME   READY   STATUS    RESTARTS   AGE   LABELS
web    1/1     Running   0          22s   app=web
Running 10.244.0.3 minikube</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="146" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels.png" alt="kubectl get pod --show-labels 顯示標籤 app=web，jsonpath 印出 phase Running、IP 和節點名稱" class="wp-image-13246" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels-300x27.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels-1024x93.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels-768x70.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-05-labels-1536x140.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--show-labels</code>：多一欄 LABELS，看得到我們貼的 <code>app=web</code></li>

<li><code>-o jsonpath='{...}'</code>：只挑 YAML 裡的某幾個欄位印出來。<code>.status.phase</code> 是 phase、<code>.status.podIP</code> 是 Pod 的 IP、<code>.spec.nodeName</code> 是被排到哪個節點</li>
</ul>



<p class="wp-block-paragraph">phase 是 <code>Running</code>，跟 STATUS 欄一樣；等一下會看到兩者不一樣的情況。</p>



<h3 class="wp-block-heading">步驟 6：用 describe 看重點</h3>



<p class="wp-block-paragraph"><code>kubectl describe</code> 印出來很長，用 <code>grep -E</code> 只挑我們要的幾行：</p>



<pre class="wp-block-code"><code>kubectl describe pod web | grep -E '^(Name|Namespace|Node|Status|IP):|Image:|Port:|State:|Started:|Restart Count'</code></pre>



<pre class="wp-block-code"><code>Name:             web
Namespace:        default
Node:             minikube/192.168.49.2
Status:           Running
IP:               10.244.0.3
    Image:          nginx:1.31
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Fri, 20 Nov 2026 15:13:29 +0000
    Restart Count:  0</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="352" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe.png" alt="kubectl describe pod web 的重點欄位：節點 minikube、IP 10.244.0.3、映像檔 nginx:1.31、Port 80、重啟 0 次" class="wp-image-13247" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe-300x66.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe-1024x225.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe-768x169.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-06-describe-1536x338.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>Node: minikube/192.168.49.2</code> 是「節點名稱／節點 IP」；<code>IP: 10.244.0.3</code> 是 Pod 自己的 IP。兩個不一樣：<strong>節點有節點的 IP，每個 Pod 另外再拿一個</strong>。<code>Started</code> 的時間是 UTC（<code>+0000</code>），台灣時間要加 8 小時，也就是 23:13。<code>Restart Count: 0</code> 等一下會變。</p>



<h3 class="wp-block-heading">步驟 7：連進 Pod 看網頁</h3>



<pre class="wp-block-code"><code>kubectl port-forward pod/web 8080:80 &gt;/dev/null 2&gt;&amp;1 &amp; sleep 3; curl -sI localhost:8080 | head -3; kill %1</code></pre>



<pre class="wp-block-code"><code>[1] 33242
HTTP/1.1 200 OK
Server: nginx/1.31.9
Date: Fri, 20 Nov 2026 15:13:59 GMT</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="192" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward.png" alt="port-forward 到 web 這個 Pod 的 80 Port，curl 回傳 HTTP 200 OK、Server 是 nginx/1.31.9" class="wp-image-13248" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward-300x36.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward-1024x123.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward-768x92.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-07-port-forward-1536x184.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>port-forward pod/web 8080:80</code> 把 Cloud Shell 的 8080 接到 Pod 的 80；<code>curl -sI</code> 只看回應的標頭（header）。<code>200 OK</code> 代表成功，<code>Server: nginx/1.31.9</code> 代表我們指定的 <code>1.31</code> 實際拿到的是 1.31.9。最後 <code>kill %1</code> 關掉背景的 port-forward。想用瀏覽器看，按 Cloud Shell 的「網頁預覽」選 8080 就好。</p>



<h3 class="wp-block-heading">步驟 8：試著改 Port，被擋下來</h3>



<p class="wp-block-paragraph">把 YAML 裡的 <code>containerPort: 80</code> 改成 8080，再 apply 一次。<code>sed -i 's/舊/新/' 檔案</code> 是「在檔案裡把舊字換成新字」的指令：</p>



<pre class="wp-block-code"><code>sed -i 's/containerPort: 80/containerPort: 8080/' pod.yaml; kubectl apply -f pod.yaml</code></pre>



<pre class="wp-block-code"><code>The Pod "web" is invalid: spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`,`spec.initContainers[*].image`,`spec.activeDeadlineSeconds`,`spec.tolerations` (only additions to existing tolerations),`spec.terminationGracePeriodSeconds` (allow it to be set to 1 if it was previously negative)
@@ -100,7 +100,7 @@
     {
      "Name": "",
      "HostPort": 0,
-     "ContainerPort": 80,
+     "ContainerPort": 8080,
      "Protocol": "TCP",
      "HostIP": ""
     }</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="379" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable.png" alt="改 containerPort 後 kubectl apply 失敗：Forbidden，pod updates may not change fields other than spec.containers[*].image 等少數欄位" class="wp-image-13249" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable-300x71.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable-1024x243.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable-768x182.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-08-immutable-1536x364.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>Forbidden</code>（禁止）：<strong>Pod 建好之後，大部分欄位都不能改</strong>。錯誤訊息直接列出能改的只有幾個：容器的映像檔（<code>image</code>）、<code>activeDeadlineSeconds</code>、<code>tolerations</code>（只能加）、<code>terminationGracePeriodSeconds</code>。下面的 <code>-</code> 和 <code>+</code> 是在告訴你哪裡不一樣：<code>-</code> 是原本的 80，<code>+</code> 是你想改的 8080。</p>



<p class="wp-block-paragraph">想改 Port 怎麼辦？刪掉 Pod 重建。這也是正式環境不直接管 Pod、改用 Deployment 的原因之一：<strong>Deployment 會幫你「建新的、刪舊的」</strong>，第 12 篇會示範。</p>



<h3 class="wp-block-heading">步驟 9：改映像檔版本，可以</h3>



<p class="wp-block-paragraph">把 Port 改回 80，同時把映像檔從 <code>nginx:1.31</code> 換成 <code>nginx:1.30</code>：</p>



<pre class="wp-block-code"><code>sed -i 's/containerPort: 8080/containerPort: 80/; s/nginx:1.31/nginx:1.30/' pod.yaml; kubectl apply -f pod.yaml; sleep 15; kubectl get pod web; kubectl describe pod web | grep -E 'Image:|Restart Count'</code></pre>



<pre class="wp-block-code"><code>pod/web configured
NAME   READY   STATUS    RESTARTS      AGE
web    1/1     Running   1 (15s ago)   64s
    Image:          nginx:1.30
    Restart Count:  1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="206" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change.png" alt="改映像檔版本後 apply 成功 pod/web configured，RESTARTS 變成 1、Image 變成 nginx:1.30，Pod 的 AGE 沒有歸零" class="wp-image-13250" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change-300x39.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change-1024x132.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change-768x99.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-09-image-change-1536x198.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這次 <code>pod/web configured</code>（已更新）。注意三個數字：</p>


<ul class="wp-block-list">
<li><code>Image: nginx:1.30</code>：換成功了</li>

<li><code>RESTARTS 1 (15s ago)</code>：<strong>容器重開了一次</strong>，舊版容器停掉、用新版映像檔再開一個</li>

<li><code>AGE 64s</code>：Pod 的年齡沒有歸零，<strong>還是同一個 Pod</strong>，只有裡面的容器換新</li>
</ul>



<p class="wp-block-paragraph">所以「改映像檔」是在同一個 Pod 裡原地換容器，換的那幾秒網站會斷。正式環境的不停機更新，要交給 Deployment 的「滾動更新」（第 12 篇）。</p>



<h3 class="wp-block-heading">步驟 10：一個 Pod 放兩個容器</h3>



<p class="wp-block-paragraph">再寫一份 <code>two.yaml</code>：一個 nginx，加一個用 busybox 映像檔的小幫手。<strong>busybox 是一個只有幾 MB 的迷你 Linux 工具箱</strong>，常拿來當測試用的容器；<code>command: ["sleep", "3600"]</code> 是叫它睡 3600 秒（1 小時），讓容器一直活著：</p>



<pre class="wp-block-code"><code>cat &gt; two.yaml &lt;&lt;'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: two
spec:
  containers:
  - name: nginx
    image: nginx:1.31
  - name: helper
    image: busybox:1.37
    command: ["sleep", "3600"]
EOF
kubectl apply -f two.yaml; sleep 20; kubectl get pod two</code></pre>



<pre class="wp-block-code"><code>pod/two created
NAME   READY   STATUS    RESTARTS   AGE
two    2/2     Running   0          20s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1397" height="896" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-10-two-containers.png" alt="建立有 nginx 和 helper 兩個容器的 Pod two，READY 顯示 2/2" class="wp-image-13251" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-10-two-containers.png 1397w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-10-two-containers-300x192.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-10-two-containers-1024x657.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-10-two-containers-768x493.png 768w" sizes="(max-width: 1397px) 100vw, 1397px" /></figure>



<p class="wp-block-paragraph"><code>containers:</code> 底下有兩個 <code>-</code>，就是兩個容器。<code>READY 2/2</code>：這個 Pod 有 2 個容器，2 個都準備好了。</p>



<h3 class="wp-block-heading">步驟 11：證明兩個容器共用網路</h3>



<p class="wp-block-paragraph">從 helper 容器裡，用 <code>localhost</code> 去連 nginx：</p>



<pre class="wp-block-code"><code>kubectl exec two -c helper -- wget -qO- localhost:80 | grep title; kubectl exec two -c helper -- hostname; kubectl exec two -c nginx -- hostname</code></pre>



<pre class="wp-block-code"><code>&lt;title&gt;Welcome to nginx!&lt;/title&gt;
two
two</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="162" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network.png" alt="從 helper 容器用 localhost:80 連到 nginx 拿到 Welcome to nginx!，兩個容器的 hostname 都是 two" class="wp-image-13252" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network-300x30.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network-1024x104.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network-768x78.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-11-shared-network-1536x156.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>-c helper</code>：Pod 裡有兩個容器時，要用 <code>-c</code> 指定進哪一個</li>

<li><code>wget -qO- localhost:80</code>：busybox 裡沒有 curl，用 wget 抓網頁，<code>-qO-</code> 是安靜模式、印在畫面上</li>

<li><strong>localhost 是「這台機器自己」</strong>。helper 用 localhost 就連到了 nginx，代表兩個容器在網路上就像同一台機器</li>

<li>兩個容器的主機名稱（hostname）都是 <code>two</code>，也就是 Pod 的名字</li>
</ul>



<p class="wp-block-paragraph">如果是兩個不同的 Pod，就不能用 localhost 互連，要靠 Pod IP 或 Service（<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">第 13 篇</a>）。</p>



<h3 class="wp-block-heading">步驟 12：跑完就結束的 Pod</h3>



<p class="wp-block-paragraph">不是每個 Pod 都要一直跑。這個 Pod 只印一行字就結束：</p>



<pre class="wp-block-code"><code>kubectl run once --image=busybox:1.37 --restart=Never -- echo 'hello from a pod'; sleep 10; kubectl get pod once; kubectl logs once</code></pre>



<pre class="wp-block-code"><code>pod/once created
NAME   READY   STATUS      RESTARTS   AGE
once   0/1     Completed   0          10s
hello from a pod</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="184" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed.png" alt="kubectl run once 用 busybox 印出 hello from a pod，Pod 狀態是 Completed、READY 0/1" class="wp-image-13253" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed-1024x118.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed-768x88.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-12-completed-1536x177.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>--restart=Never</code>：容器結束後<strong>不要重開</strong>。Pod 預設的 <code>restartPolicy</code> 是 <code>Always</code>（步驟 2 的草稿裡看得到），一般網站要一直開著；這種跑一次就好的工作要改成 Never</li>

<li><code>--</code> 後面是要在容器裡執行的指令</li>

<li><code>STATUS Completed</code>、<code>READY 0/1</code>：容器已經做完收工了，phase 是 <code>Succeeded</code></li>

<li><code>kubectl logs once</code> 還是看得到它印的字，Pod 刪掉之前紀錄都會留著</li>
</ul>



<p class="wp-block-paragraph">這種「跑一次就結束」的工作，正式環境會交給 Job 來管（失敗會重試、可以設定跑幾次）。</p>



<h3 class="wp-block-heading">步驟 13：刪掉單獨的 Pod，不會被補回來</h3>



<pre class="wp-block-code"><code>kubectl get pods; time kubectl delete pod web; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>NAME   READY   STATUS      RESTARTS      AGE
once   0/1     Completed   0             16s
two    2/2     Running     0             49s
web    1/1     Running     1 (70s ago)   119s
pod "web" deleted from default namespace

real    0m0.720s
user    0m0.059s
sys     0m0.031s
NAME   READY   STATUS      RESTARTS   AGE
once   0/1     Completed   0          17s
two    2/2     Running     0          50s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="623" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare.png" alt="刪除 web 這個 Pod 花 0.72 秒，刪完 web 就消失了，沒有被自動補回來" class="wp-image-13254" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare-300x117.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare-1024x399.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare-768x299.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-13-delete-bare-1536x598.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪 <code>web</code> 花了 <strong>0.72 秒</strong>，刪完它就不見了，<strong>沒有新的 Pod 冒出來</strong>。</p>



<p class="wp-block-paragraph">這跟第 9 篇、第 10 篇刪 Deployment 底下的 Pod 完全不同：那時 1 秒內就補了一個新的。差別在於<strong>用 YAML 直接建的 Pod 沒有人在管</strong>，沒有控制器幫它對帳。所以正式環境幾乎不會直接建 Pod，而是建 Deployment，讓它來管 Pod。</p>



<h3 class="wp-block-heading">步驟 14：刪兩個容器的 Pod，等了 30 秒</h3>



<pre class="wp-block-code"><code>time kubectl delete -f two.yaml</code></pre>



<pre class="wp-block-code"><code>pod "two" deleted from default namespace

real    0m30.919s
user    0m0.055s
sys     0m0.025s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1060" height="390" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-14-delete-slow.png" alt="kubectl delete -f two.yaml 花了 30.9 秒才刪完" class="wp-image-13255" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-14-delete-slow.png 1060w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-14-delete-slow-300x110.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-14-delete-slow-1024x377.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-14-delete-slow-768x283.png 768w" sizes="(max-width: 1060px) 100vw, 1060px" /></figure>



<p class="wp-block-paragraph">同樣是刪一個 Pod，<code>web</code> 只要 0.72 秒，<code>two</code> 卻花了 <strong>30.9 秒</strong>。原因在下面「實測時的意外」第 2 點。<code>delete -f 檔案</code> 是「刪掉這份檔案描述的東西」，跟 <code>apply -f</code> 是一對。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. 改 Port 被擋，改映像檔卻可以</h3>



<p class="wp-block-paragraph">很多人以為 <code>kubectl apply</code> 什麼都能改。實測改 <code>containerPort</code> 直接 <code>Forbidden</code>，錯誤訊息列出 Pod 建好後能改的只有映像檔、<code>activeDeadlineSeconds</code>、<code>tolerations</code>（只能加）、<code>terminationGracePeriodSeconds</code> 這幾個欄位。改映像檔可以，但容器會原地重開一次（<code>RESTARTS 1</code>），Pod 本身還是同一個（<code>AGE</code> 沒歸零）。</p>



<h3 class="wp-block-heading">2. busybox 的 sleep 讓刪除等了 30 秒</h3>



<p class="wp-block-paragraph"><strong>刪除 Pod 時，Kubernetes 會先送一個「請結束」的訊號（SIGTERM）給每個容器，等它們自己收工；最多等 30 秒</strong>，時間到了才強制關掉。這個 30 秒就是 Pod 預設的 <code>terminationGracePeriodSeconds: 30</code>（寬限期），第 10 篇用 <code>-o yaml</code> 看 Deployment 時就有這一行。</p>



<p class="wp-block-paragraph">nginx 收到 SIGTERM 會馬上收工，所以 <code>web</code> 0.72 秒就刪完；<code>two</code> 裡的 helper 跑的是 <code>sleep</code>，而且是容器裡的第一個程式（編號 1 的程序），Linux 對編號 1 的程序有特別規則：它沒有自己寫好處理方式的訊號會被忽略，所以 <code>sleep</code> 對 SIGTERM 不理不睬，Kubernetes 只好等滿 30 秒才強制關掉。結果 30.9 秒＝30 秒寬限期＋零點幾秒的收尾。</p>



<p class="wp-block-paragraph">這跟<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">第 2 篇</a>的 <code>docker stop</code> 一樣，只是 Docker 預設等 10 秒、Kubernetes 預設等 30 秒。自己寫的程式要記得處理 SIGTERM，<a href="https://dongdonggcp.com/2026/11/21/k8s-probe-resources-hpa-autoscaling/">第 17 篇</a>講健康檢查時會再提。</p>



<h3 class="wp-block-heading">3. kubectl 產生的草稿和手寫的不一樣</h3>



<p class="wp-block-paragraph"><code>kubectl run --dry-run=client</code> 產生的 YAML，標籤是 <code>run: web</code>、容器名稱跟 Pod 一樣叫 <code>web</code>，還多了 <code>resources: {}</code>、<code>status: {}</code> 這些空欄位。拿來當草稿很方便，但要記得把標籤改成你團隊慣用的（常見是 <code>app:</code>），空欄位可以刪掉。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<p class="wp-block-paragraph"><code>web</code>、<code>two</code> 已經在步驟 13、14 刪掉了，再把 <code>once</code> 刪掉、關掉叢集：</p>



<pre class="wp-block-code"><code>kubectl delete pod once; kubectl get pods; minikube delete | tail -1</code></pre>



<pre class="wp-block-code"><code>pod "once" deleted from default namespace
No resources found in default namespace.
💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="245" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup.png" alt="刪除 once 之後 default 命名空間沒有任何 Pod，minikube delete 刪掉整個叢集" class="wp-image-13256" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup-300x46.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup-1024x157.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup-768x118.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct11-shots-15-cleanup-1536x235.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>No resources found</code> 代表 default 命名空間已經沒有 Pod 了。家目錄的 <code>~/k8s-pod</code> 資料夾（<code>pod.yaml</code>、<code>two.yaml</code>）會留著，第 12 篇可以接著用；Cloud Shell 和 Minikube 都不收費。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>


<ul class="wp-block-list">
<li><strong>GKE</strong>：Pod 的 YAML 一模一樣，這篇的 <code>pod.yaml</code> 不用改就能 <code>kubectl apply</code> 到 GKE。差別在收費：GKE Autopilot 模式是<strong>照 Pod 要求的資源計費</strong>（<a href="https://cloud.google.com/kubernetes-engine/pricing">GKE 定價頁</a>，2026 年 11 月查），所以第 17 篇會教的 CPU、記憶體設定，在 Autopilot 上直接影響帳單</li>

<li><strong>Cloud Run</strong>：沒有 Pod 這個名詞，你給它一個容器映像檔，它幫你處理一切。第 20 篇：<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a>會實際部署</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「Pod 和容器差在哪？」</strong>：Pod 是 Kubernetes 管理的最小單位，裡面可以有一個或多個容器，它們共用網路（同一個 IP、localhost 互連）和儲存，而且一定在同一個節點</li>

<li><strong>「什麼時候一個 Pod 放多個容器？」</strong>：要緊密合作、必須在同一台機器、一起擴展的才放一起（sidecar），例如日誌收集；能分開擴展的就分成不同 Pod</li>

<li><strong>「Pod 刪了為什麼沒有自動補？」</strong>：直接建的 Pod 沒有控制器在管；要自動補位用 Deployment</li>

<li><strong>「Pod 卡在 Terminating 很久是為什麼？」</strong>：容器沒處理 SIGTERM，Kubernetes 要等滿寬限期（預設 30 秒）才強制關掉</li>

<li><strong>「Pod 的 phase 有哪些？」</strong>：Pending、Running、Succeeded、Failed、Unknown</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKAD、CKA）</h3>



<p class="wp-block-paragraph">兩張都是上機實作考（445 美元、2 小時，2026 年 11 月查 Linux Foundation 官方頁）。Pod 相關的常見題型：</p>


<ul class="wp-block-list">
<li><strong>照規格寫 Pod</strong>：指定名字、映像檔、標籤、Port。最快的做法就是步驟 2：<code>kubectl run --dry-run=client -o yaml &gt; 檔案</code>，再改幾行</li>

<li><strong>多容器 Pod</strong>：題目給兩個映像檔，要求放在同一個 Pod，用 <code>-c</code> 指定容器查日誌或執行指令</li>

<li><strong>用 jsonpath 取值</strong>：題目要你把某個 Pod 的 IP、所在節點寫進檔案，就是步驟 5 的 <code>-o jsonpath</code></li>
</ul>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「最小部署單位」</td><td>Pod</td></tr><tr><td>「同一個 Pod 的容器怎麼互連」</td><td>localhost</td></tr><tr><td>「sidecar」「日誌收集小幫手」</td><td>多容器 Pod</td></tr><tr><td>「產生 YAML 不要真的建立」</td><td><code>--dry-run=client -o yaml</code></td></tr><tr><td>「Pod 欄位不能改」</td><td>刪掉重建，或改用 Deployment</td></tr><tr><td>「跑一次就結束的工作」</td><td><code>restartPolicy: Never</code>、Job</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">Pod 和容器有什麼不同？</h3>



<p class="wp-block-paragraph">容器是跑一個程式的單位，由 Docker、containerd 這類容器執行環境管理；Pod 是 Kubernetes 管理的最小單位，裡面裝一個或多個容器。同一個 Pod 的容器共用 IP 和主機名稱、可以用 localhost 互連，而且一定被排到同一個節點。實測兩個容器的 hostname 都是 Pod 名稱 <code>two</code>。</p>



<h3 class="wp-block-heading">一個 Pod 可以放幾個容器？</h3>



<p class="wp-block-paragraph">沒有硬性的小數量限制，但大部分情況一個 Pod 只放一個容器。只有必須在同一台機器、共用網路或檔案、要一起擴展的才放一起，例如主程式加一個收日誌的 sidecar。網站和資料庫不要放同一個 Pod，因為它們擴展的需求不一樣。</p>



<h3 class="wp-block-heading">我刪掉 Pod，為什麼它沒有自動長回來？</h3>



<p class="wp-block-paragraph">因為那個 Pod 是你直接用 YAML 或 <code>kubectl run</code> 建的，沒有控制器在管它。由 Deployment 建出來的 Pod，刪掉後 ReplicaSet 控制器會在 1 秒內補一個新的。實測直接建的 <code>web</code> 刪掉 0.72 秒後就消失，沒有被補回來。</p>



<h3 class="wp-block-heading">Pod 建好後可以修改設定嗎？</h3>



<p class="wp-block-paragraph">大部分不行。實測把 <code>containerPort</code> 從 80 改成 8080，<code>kubectl apply</code> 回 <code>Forbidden</code>，能改的只有容器映像檔、<code>activeDeadlineSeconds</code>、<code>tolerations</code>（只能加）、<code>terminationGracePeriodSeconds</code>。改映像檔會讓容器原地重開一次。其他欄位要改，就刪掉 Pod 重建，或交給 Deployment 處理。</p>



<h3 class="wp-block-heading">刪 Pod 為什麼要等 30 秒？</h3>



<p class="wp-block-paragraph">Kubernetes 刪 Pod 時會先送 SIGTERM 請容器自己結束，最多等 <code>terminationGracePeriodSeconds</code>（預設 30 秒）。如果容器裡的程式不理會 SIGTERM（實測 busybox 的 <code>sleep</code> 就是），就要等滿 30 秒才被強制關掉。實測 nginx 的 Pod 0.72 秒刪完，有 sleep 的 Pod 要 30.9 秒。</p>



<h3 class="wp-block-heading">kubectl run 以前不是會建 Deployment 嗎？</h3>



<p class="wp-block-paragraph">舊版是。很早期的 kubectl，<code>kubectl run</code> 預設會建一個 Deployment；Kubernetes 1.18 起改成只建 Pod。網路上舊教學用 <code>kubectl run</code> 示範擴展、滾動更新，照做會發現行不通。現在要建 Deployment，請用 <code>kubectl create deployment</code> 或 YAML。</p>



<h3 class="wp-block-heading">PodPreset 還能用嗎？</h3>



<p class="wp-block-paragraph">不能。PodPreset 是早期用來「自動幫 Pod 塞入共用設定」的功能，一直停在測試階段（alpha），已經在 Kubernetes 1.20 移除。有些 2018 年前後的中文教學還會介紹它，現在共用設定改用 ConfigMap、Secret（<a href="https://dongdonggcp.com/2026/11/21/k8s-configmap-secret/">第 15 篇</a>會教）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>Pod 是 Kubernetes 最小的部署單位</strong>：一個或多個容器，共用 IP 和主機名稱、用 localhost 互連、一定在同一個節點；大部分情況一個 Pod 一個容器</li>

<li><strong>K8s YAML 有 4 塊</strong>：apiVersion、kind、metadata、spec；縮排用空白不用 Tab；<code>kubectl run --dry-run=client -o yaml</code> 可以產生草稿</li>

<li><strong><code>kubectl apply -f</code> 是宣告式</strong>：沒有就建、有就更新；但 Pod 建好後大部分欄位不能改（實測改 Port 被 Forbidden），改映像檔會原地重開容器</li>

<li><strong>直接建的 Pod 刪了不會補</strong>，刪除時要等容器收工，預設最多 30 秒（實測 nginx 0.72 秒、sleep 30.9 秒）</li>

<li><strong>所以正式環境用 Deployment 管 Pod</strong>，下一篇就教</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 2 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">Docker 常用指令一次看懂：run、ps、logs、exec、stop、rm</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-image-vs-container-layer-tag/">Docker 映像檔和容器差在哪？Image、Layer、Tag 白話解釋</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-compose-tutorial-flask-mysql/">Docker Compose 教學：一個 YAML 開起網站＋資料庫</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a></li>

<li>上一篇：第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></li>

<li>下一篇：第 12 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">Deployment 教學：自動補位、擴縮、滾動更新與回滾</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器 (Container) 技術是什麼？從零開始看懂 Docker 與容器化應用</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">會寫 Pod 的 YAML 之後，下一步就是讓 Kubernetes 幫你管一整群 Pod。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Pod 和容器有什麼不同？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "容器是跑一個程式的單位，由 Docker、containerd 這類容器執行環境管理；Pod 是 Kubernetes 管理的最小單位，裡面裝一個或多個容器。同一個 Pod 的容器共用 IP 和主機名稱、可以用 localhost 互連，而且一定被排到同一個節點。實測兩個容器的 hostname 都是 Pod 名稱 `two`。"
      }
    },
    {
      "@type": "Question",
      "name": "一個 Pod 可以放幾個容器？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "沒有硬性的小數量限制，但大部分情況一個 Pod 只放一個容器。只有必須在同一台機器、共用網路或檔案、要一起擴展的才放一起，例如主程式加一個收日誌的 sidecar。網站和資料庫不要放同一個 Pod，因為它們擴展的需求不一樣。"
      }
    },
    {
      "@type": "Question",
      "name": "我刪掉 Pod，為什麼它沒有自動長回來？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "因為那個 Pod 是你直接用 YAML 或 `kubectl run` 建的，沒有控制器在管它。由 Deployment 建出來的 Pod，刪掉後 ReplicaSet 控制器會在 1 秒內補一個新的。實測直接建的 `web` 刪掉 0.72 秒後就消失，沒有被補回來。"
      }
    },
    {
      "@type": "Question",
      "name": "Pod 建好後可以修改設定嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "大部分不行。實測把 `containerPort` 從 80 改成 8080，`kubectl apply` 回 `Forbidden`，能改的只有容器映像檔、`activeDeadlineSeconds`、`tolerations`（只能加）、`terminationGracePeriodSeconds`。改映像檔會讓容器原地重開一次。其他欄位要改，就刪掉 Pod 重建，或交給 Deployment 處理。"
      }
    },
    {
      "@type": "Question",
      "name": "刪 Pod 為什麼要等 30 秒？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Kubernetes 刪 Pod 時會先送 SIGTERM 請容器自己結束，最多等 `terminationGracePeriodSeconds`（預設 30 秒）。如果容器裡的程式不理會 SIGTERM（實測 busybox 的 `sleep` 就是），就要等滿 30 秒才被強制關掉。實測 nginx 的 Pod 0.72 秒刪完，有 sleep 的 Pod 要 30.9 秒。"
      }
    },
    {
      "@type": "Question",
      "name": "kubectl run 以前不是會建 Deployment 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "舊版是。很早期的 kubectl，`kubectl run` 預設會建一個 Deployment；Kubernetes 1.18 起改成只建 Pod。網路上舊教學用 `kubectl run` 示範擴展、滾動更新，照做會發現行不通。現在要建 Deployment，請用 `kubectl create deployment` 或 YAML。"
      }
    },
    {
      "@type": "Question",
      "name": "PodPreset 還能用嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不能。PodPreset 是早期用來「自動幫 Pod 塞入共用設定」的功能，一直停在測試階段（alpha），已經在 Kubernetes 1.20 移除。有些 2018 年前後的中文教學還會介紹它，現在共用設定改用 ConfigMap、Secret（第 15 篇會教）。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</title>
		<link>https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=k8s-architecture-control-plane-node-pod</link>
					<comments>https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 10:33:23 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Google Kubernetes Engine]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[K8s]]></category>
		<category><![CDATA[Kubernetes]]></category>
		<category><![CDATA[容器編排]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=13214</guid>

					<description><![CDATA[<p>K8s 架構白話：控制平面的 kube-apiserver、etcd、scheduler、controller-manager 和節點的 kubelet 怎麼分工；Minikube 實測拿掉排程器，新 Pod 卡在 Pending。</p>
<p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>K8s 架構分成兩半：控制平面負責做決定（記帳、派工、盯進度），節點負責把容器跑起來，Pod 是被派到節點上的最小工作單位。</strong></p>



<p class="wp-block-paragraph">這篇不只畫架構圖。我們在免費的 Cloud Shell 用 Minikube 開一個真的 Kubernetes 叢集，把控制平面的 7 個系統 Pod 一個一個點名，再做一個網路教學很少做的實驗：<strong>把負責派工的排程器拿掉</strong>，看看新的 Pod 會怎樣。結果是：舊的網站照跑，新的 2 個 Pod 全部卡在 <code>Pending</code>，把排程器放回去之後才排進節點。</p>



<p class="wp-block-paragraph">這是「容器系列」的第 9 篇，也是 Kubernetes 段落的第一篇。全部在 Cloud Shell 實際跑過，輸出都是真實結果（2026 年 11 月實測，Minikube v1.38.1、Kubernetes v1.35.1）。如果你還不確定自己需不需要 Kubernetes，可以先看<a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a>，那篇講「要不要用」，這篇講「裡面怎麼分工」。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-01-architecture.png" alt="K8s 架構一張圖：左邊控制平面有 kube-apiserver、etcd、kube-scheduler、controller-manager，右邊節點有 kubelet、容器執行環境、kube-proxy 和 Pod" class="wp-image-13194" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-01-architecture.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-01-architecture-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-01-architecture-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-01-architecture-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>排錯時才知道要找誰</strong>：Pod 卡在 <code>Pending</code> 通常是排程器找不到節點；卡在 <code>ImagePullBackOff</code> 是節點上的 kubelet 拉不到映像檔。知道誰負責哪一段，才不會亂槍打鳥</li>

<li><strong>面試幾乎一定問</strong>：「你下 <code>kubectl apply</code> 之後，叢集裡發生了什麼事？」這題答得出來，面試官就知道你不是只會背指令</li>

<li><strong>證照的大比重</strong>：Kubernetes 管理員證照 CKA 的考試範圍裡，「叢集架構、安裝與設定」佔 25%、「排錯」佔 30%（2026 年 11 月查 Linux Foundation 官方頁），兩塊都要懂架構</li>

<li><strong>用雲端服務時才知道自己付錢買了什麼</strong>：Google 的 GKE 幫你管控制平面，你在叢集裡看不到 <code>kube-apiserver</code>；不懂架構，就不知道每小時 0.10 美元的叢集管理費到底在付什麼</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">先把三個大名詞講清楚</h2>



<h3 class="wp-block-heading">Kubernetes（K8s）是什麼</h3>



<p class="wp-block-paragraph"><strong>Kubernetes 是一套幫你管理很多容器的系統</strong>：你告訴它「我要 3 個網站容器」，它負責挑機器放、壞了重開、流量變大時加開。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：Docker 是一個廚師會做菜；Kubernetes 是整間餐廳的管理制度，決定哪個廚師做哪張單、誰請假了誰補上</li>

<li><strong>來龍去脈</strong>：Kubernetes 是希臘文的「舵手」，K8s 是因為 K 和 s 中間有 8 個字母。Google 在 2014 年把它開源，裡面放了 Google 內部跑大量服務十幾年的經驗（<a href="https://kubernetes.io/docs/concepts/overview/">Kubernetes 官方介紹</a>）</li>

<li><strong>為什麼要學</strong>：容器一多，手動 <code>docker run</code> 管不過來；GKE、EKS、AKS 這些雲端服務底下都是 Kubernetes</li>
</ul>



<p class="wp-block-paragraph">想先了解容器本身，可以看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇：Docker 入門教學</a>。</p>



<h3 class="wp-block-heading">叢集（Cluster）是什麼</h3>



<p class="wp-block-paragraph"><strong>叢集是一群被 Kubernetes 統一管理的機器</strong>，對你來說它像一台很大的電腦。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：一間餐廳，有外場辦公室，也有好幾個廚房工作檯</li>

<li><strong>來龍去脈</strong>：英文 cluster 是「一串、一群」，像一串葡萄。一台機器會壞、會不夠用，所以把很多台綁在一起，壞一台還有別台</li>

<li><strong>為什麼要學</strong>：GKE 計費、權限、網路設定都以「叢集」為單位</li>
</ul>



<h3 class="wp-block-heading">節點（Node）是什麼</h3>



<p class="wp-block-paragraph"><strong>節點是叢集裡的一台機器</strong>，可以是實體主機，也可以是雲端的虛擬機器（Virtual Machine，用軟體切出來的一台電腦）。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳裡的一個廚房工作檯</li>

<li><strong>來龍去脈</strong>：node 原本是網路圖上「一個點」的意思，叢集畫成圖時，每台機器就是一個點</li>

<li><strong>為什麼要學</strong>：Pod 最後一定要落在某個節點上跑；節點不夠力，Pod 就排不進去</li>
</ul>



<h3 class="wp-block-heading">Pod 是什麼</h3>



<p class="wp-block-paragraph"><strong>Pod 是 Kubernetes 裡最小的部署單位，裡面裝一個或幾個容器</strong>。Kubernetes 不直接管容器，它管的是 Pod。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：一份餐點。客人點的是「一份套餐」，裡面可能只有主餐，也可能附一杯飲料（多個容器）</li>

<li><strong>來龍去脈</strong>：pod 是英文的「豆莢」，一個豆莢裡裝幾顆豆子；Docker 的標誌是鯨魚，一群鯨魚英文也叫 pod</li>

<li><strong>為什麼要學</strong>：你在 K8s 看到的狀態（Running、Pending、CrashLoopBackOff）幾乎都是 Pod 的狀態。Pod 的寫法會在第 11 篇：<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-yaml-tutorial/">Pod 是什麼？寫第一個 YAML 把容器跑進 K8s</a>細講，這篇先知道「Pod 是被派工的那一份工作」就好</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">控制平面：負責做決定的 4 個元件</h2>



<p class="wp-block-paragraph"><strong>控制平面（Control Plane）是 Kubernetes 的大腦</strong>：它不跑你的網站，只負責記住「應該要有什麼」、決定「放哪裡」、盯著「有沒有照做」。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳的外場辦公室，有櫃檯、訂單本、派單領班、巡場經理</li>

<li><strong>來龍去脈</strong>：舊文章常叫它 <strong>Master（主節點）</strong>。Kubernetes 社群後來改稱 control plane，kubeadm（官方的叢集安裝工具）已經不再使用 <code>node-role.kubernetes.io/master</code> 這個舊標記，改用 <code>node-role.kubernetes.io/control-plane</code>（<a href="https://kubernetes.io/docs/reference/labels-annotations-taints/">Kubernetes 官方標籤說明</a>，2026 年 11 月查）。你在下面實作會看到節點的角色寫的是 <code>control-plane</code></li>

<li><strong>為什麼要學</strong>：控制平面掛了，叢集就「不能改」；但已經在跑的 Pod 不一定會停。這個差別是面試常考題，實作段落會實際證明</li>
</ul>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元件</th><th>白話</th><th>餐廳比喻</th><th>壞掉會怎樣</th></tr></thead><tbody><tr><td><code>kube-apiserver</code></td><td>唯一的窗口，所有人（包括你的 kubectl）都只跟它講話</td><td>點餐櫃檯</td><td>什麼都查不到、改不了</td></tr><tr><td><code>etcd</code></td><td>存放叢集所有設定和狀態的資料庫</td><td>訂單本</td><td>資料沒了＝整個叢集失憶</td></tr><tr><td><code>kube-scheduler</code></td><td>看到還沒分配節點的 Pod，幫它挑一個節點</td><td>派單領班</td><td>新 Pod 卡在 <code>Pending</code></td></tr><tr><td><code>kube-controller-manager</code></td><td>一直比對「應該有幾個」和「實際有幾個」，不一樣就修正</td><td>巡場經理</td><td>刪掉的 Pod 不會自動補</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">kube-apiserver：唯一的窗口</h3>



<p class="wp-block-paragraph"><strong>kube-apiserver 是控制平面的前門</strong>，它提供一組 HTTP 介面（API，Application Programming Interface，程式之間講話的固定格式），你打的每一個 <code>kubectl</code> 指令，其實都是送一個 HTTPS 請求給它。</p>



<p class="wp-block-paragraph">它會先檢查你是誰、有沒有權限、格式對不對，通過了才把資料寫進 etcd。其他元件（排程器、控制器、每個節點的 kubelet）也都是透過它讀寫資料，彼此不直接講話。</p>



<h3 class="wp-block-heading">etcd：叢集的帳本</h3>



<p class="wp-block-paragraph"><strong>etcd 是一個「鍵值資料庫」（key-value store）</strong>：每筆資料就是「名字＝內容」，像「pod/web-xxx＝這個 Pod 的完整設定」。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：餐廳的訂單本，寫下每一張單「應該要做什麼」</li>

<li><strong>來龍去脈</strong>：名字來自 Linux 的 <code>/etc</code> 資料夾（放設定檔的地方）加上 d（distributed，分散式），意思是「分散在好幾台機器上的設定資料夾」</li>

<li><strong>為什麼要學</strong>：etcd 壞了又沒備份，叢集裡所有 Deployment、Service、Secret 的定義就都沒了。CKA 考試常考 etcd 的備份與還原</li>
</ul>



<h3 class="wp-block-heading">kube-scheduler：派工的領班</h3>



<p class="wp-block-paragraph"><strong>kube-scheduler 只做一件事：幫還沒有節點的 Pod 挑一個節點</strong>。它會先篩掉不合格的節點（例如記憶體不夠），再幫剩下的打分數，挑最高分的那台。</p>



<p class="wp-block-paragraph">它只負責「填上節點名字」，不負責把容器跑起來。真正啟動容器的是那個節點上的 kubelet。</p>



<h3 class="wp-block-heading">kube-controller-manager：一直對帳的經理</h3>



<p class="wp-block-paragraph"><strong>kube-controller-manager 是一個程式裡面裝了很多「控制器」（controller）</strong>，每個控制器盯一種東西：Deployment 控制器盯 Deployment、ReplicaSet 控制器盯「Pod 數量對不對」、Node 控制器盯「節點還活著嗎」。</p>



<p class="wp-block-paragraph">它們的工作方式都一樣：<strong>看期望狀態（你要的）→ 看實際狀態（現在有的）→ 不一樣就動手修</strong>，一直重複。這個不停對帳的迴圈，就是 Kubernetes 會「自我修復」的原因。</p>



<p class="wp-block-paragraph">另外還有一個選配的 <code>cloud-controller-manager</code>，負責跟雲端服務商溝通（例如幫你在 Google Cloud 建一個負載平衡器）。Minikube 這種本機叢集沒有它。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">節點：真的跑容器的 3 個元件</h2>



<p class="wp-block-paragraph"><strong>節點是叢集裡實際跑你應用程式的機器</strong>，每個節點上都有這三個元件（<a href="https://kubernetes.io/docs/concepts/overview/components/">Kubernetes Components 官方頁</a>）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元件</th><th>白話</th><th>餐廳比喻</th></tr></thead><tbody><tr><td><code>kubelet</code></td><td>節點上的組長：接到分配給自己的 Pod，就叫執行環境把容器跑起來，並且一直回報狀態</td><td>工作檯組長</td></tr><tr><td>容器執行環境（Container Runtime）</td><td>真的去拉映像檔、建立和啟動容器的軟體，例如 containerd、CRI-O</td><td>爐子和廚師</td></tr><tr><td><code>kube-proxy</code>（選配）</td><td>在節點上設定網路規則，讓「打到某個 Service 的流量」被送到正確的 Pod</td><td>傳菜動線</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">kubelet：每個節點的組長</h3>



<p class="wp-block-paragraph"><strong>kubelet 是每個節點上都會跑的一個程式</strong>，它會一直問 API 伺服器：「有沒有 Pod 分配給我？」有的話就照著 Pod 的設定，叫容器執行環境把容器跑起來，跑起來之後再定期回報「我這裡的 Pod 都還活著」。</p>



<p class="wp-block-paragraph">kubelet 很特別：<strong>它本身不是 Pod</strong>，是直接裝在節點作業系統上的服務（作業系統是管理電腦硬體、讓其他程式能跑的底層軟體，像 Windows、Ubuntu）。所以你用 <code>kubectl get pods</code> 永遠看不到 kubelet，實作段落會證明這件事。</p>



<h3 class="wp-block-heading">容器執行環境：真的煮菜的人</h3>



<p class="wp-block-paragraph"><strong>容器執行環境（Container Runtime）是真正負責建立、啟動、停止容器的軟體</strong>。Kubernetes 透過一個叫 CRI（Container Runtime Interface，容器執行環境介面）的標準接口跟它講話，所以可以換不同的實作。</p>



<p class="wp-block-paragraph">來龍去脈：Kubernetes 早期直接支援 Docker，後來在 1.24 版移除了這段專門給 Docker 的程式（dockershim），現在主流是 containerd。Minikube 預設還是用 Docker，是透過一個叫 cri-dockerd 的轉接器接上 CRI；它啟動時也提醒「從 v1.39.0 起預設會改用 containerd」，你在實作會看到這行字。</p>



<h3 class="wp-block-heading">kube-proxy：傳菜動線</h3>



<p class="wp-block-paragraph"><strong>kube-proxy 負責節點上的網路轉送規則</strong>，讓同一個服務名稱可以把流量平均分給背後好幾個 Pod。這部分會在<a href="https://dongdonggcp.com/2026/11/21/k8s-service-clusterip-nodeport-loadbalancer/">第 13 篇</a>講 Service 時細講。官方文件把它標成「選配」，因為有些網路外掛會自己做這件事。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">一個 Pod 是怎麼被建出來的？</h2>



<p class="wp-block-paragraph">你下 <code>kubectl create deployment web --image=nginx</code>，叢集裡會依序發生這 7 件事：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-02-pod-flow.png" alt="一個 Pod 被建出來的 7 個步驟：kubectl 送給 API 伺服器、寫進 etcd、控制器建 Pod、排程器挑節點、kubelet 叫執行環境拉映像檔、啟動容器、回報 Running" class="wp-image-13195" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-02-pod-flow.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-02-pod-flow-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-02-pod-flow-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-02-pod-flow-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>


<ol class="wp-block-list">
<li><strong>kubectl</strong> 把「我要一個叫 web 的 Deployment，用 nginx 映像檔」送給 kube-apiserver</li>

<li><strong>kube-apiserver</strong> 檢查權限和格式，通過後寫進 etcd</li>

<li><strong>Deployment 控制器</strong>看到新的 Deployment，建立一個 ReplicaSet；<strong>ReplicaSet 控制器</strong>發現「要 1 個 Pod、現在 0 個」，建立一個 Pod（這時 Pod 還沒有節點）</li>

<li><strong>kube-scheduler</strong> 看到這個沒分配節點的 Pod，挑一個節點填進去</li>

<li><strong>那個節點的 kubelet</strong> 發現有 Pod 分配給自己，叫容器執行環境去拉 nginx 映像檔</li>

<li><strong>容器執行環境</strong>建立並啟動容器</li>

<li><strong>kubelet</strong> 回報 Pod 狀態是 <code>Running</code>，API 伺服器再寫回 etcd</li>
</ol>



<p class="wp-block-paragraph">重點是：<strong>每個元件都只做自己那一小段，彼此透過 API 伺服器交接</strong>。實作的步驟 10 會用 <code>kubectl get events</code> 看到這幾個元件留下的紀錄，順序跟這張圖一模一樣。</p>



<h3 class="wp-block-heading">宣告式：你寫「要什麼」，不是寫「怎麼做」</h3>



<p class="wp-block-paragraph"><strong>宣告式（Declarative）是指你只描述想要的結果</strong>，例如「我要 3 個 nginx」，不用寫「先開第 1 個、再開第 2 個」。</p>


<ul class="wp-block-list">
<li><strong>比喻</strong>：你跟餐廳說「這桌要 3 份套餐」，不用教廚師怎麼煮；少上一份，經理會自己追</li>

<li><strong>來龍去脈</strong>：相反的叫命令式（Imperative），像<a href="https://dongdonggcp.com/2026/11/18/docker-commands-run-ps-logs-exec-stop-rm/">第 2 篇</a>的 <code>docker run</code>，你下一個指令它做一個動作，容器掛了它不會管。Kubernetes 存的是「期望狀態」，控制器一直把現實拉回期望狀態</li>

<li><strong>為什麼要學</strong>：這是 Kubernetes 會自我修復、可以用 YAML 檔管理一切的根本原因；面試問「K8s 跟 Docker 差在哪」，講出這點就有分</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-03-restaurant.png" alt="用一間餐廳記 K8s 架構：kube-apiserver 是點餐櫃檯、etcd 是訂單本、kube-scheduler 是派單領班、controller-manager 是巡場經理、kubelet 是工作檯組長、容器執行環境是爐子和廚師、Pod 是一份餐點" class="wp-image-13196" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-03-restaurant.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-03-restaurant-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-03-restaurant-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-cards-03-restaurant-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：在 Cloud Shell 開一個 K8s 叢集，看看裡面住了誰</h2>



<p class="wp-block-paragraph">這段在 <strong>Cloud Shell（不用設專案）</strong> 做，<strong>不會花錢</strong>，大約 15 分鐘。怎麼打開 Cloud Shell 請看<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">第 1 篇的步驟</a>；如果跳出「授權 Cloud Shell」，這篇用不到 gcloud，按「拒絕」就好。</p>



<p class="wp-block-paragraph">截圖裡的提示字元有縮短（跑過 <code>export PS1='\w\$ '</code>），你的畫面會是「你的帳號@cloudshell:~$」，不影響操作。</p>



<p class="wp-block-paragraph"><strong>Minikube 是什麼？</strong> Minikube 是一個在單一台電腦上開出「迷你 Kubernetes 叢集」的工具，Kubernetes 官方社群維護（<a href="https://minikube.sigs.k8s.io/docs/">Minikube 官方文件</a>），Cloud Shell 已經預裝。完整介紹和 kubectl 必學指令放在下一篇：第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a>。這篇只用它來「看」架構。</p>



<p class="wp-block-paragraph"><strong>kubectl 是什麼？</strong> kubectl 是跟 Kubernetes 講話的指令工具，唸法有人唸「kube control」、有人唸「kube C T L」。它做的事就是把你的指令變成 HTTPS 請求送給 kube-apiserver。</p>



<h3 class="wp-block-heading">步驟 1：確認工具版本</h3>



<p class="wp-block-paragraph">先看 Cloud Shell 裡的 Minikube 和 kubectl 是哪一版：</p>



<pre class="wp-block-code"><code>minikube version; kubectl version --client</code></pre>



<pre class="wp-block-code"><code>minikube version: v1.38.1
commit: c93a4cb9311efc66b90d33ea03f75f2c4120e9b0
Client Version: v1.35.9-dispatcher
Kustomize Version: v5.7.1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1203" height="344" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-01-versions.png" alt="Cloud Shell 執行 minikube version 和 kubectl version，顯示 Minikube v1.38.1、kubectl v1.35.9" class="wp-image-13197" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-01-versions.png 1203w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-01-versions-300x86.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-01-versions-1024x293.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-01-versions-768x220.png 768w" sizes="(max-width: 1203px) 100vw, 1203px" /></figure>



<p class="wp-block-paragraph">Minikube 是 v1.38.1，kubectl 是 v1.35.9（後面的 <code>-dispatcher</code> 是 Google Cloud 打包的版本標記）。Kustomize 那行是 kubectl 內建的另一個工具，這系列用不到。</p>



<h3 class="wp-block-heading">步驟 2：開一個 Kubernetes 叢集</h3>



<pre class="wp-block-code"><code>minikube start</code></pre>



<pre class="wp-block-code"><code>😄  minikube v1.38.1 on Ubuntu 24.04 (amd64)
    ▪ MINIKUBE_FORCE_SYSTEMD=true
    ▪ MINIKUBE_HOME=/google/minikube
    ▪ MINIKUBE_WANTUPDATENOTIFICATION=false
✨  Automatically selected the docker driver. Other choices: none, ssh
❗  Starting v1.39.0, minikube will default to "containerd" container runtime. See #21973 for more info.
📌  Using Docker driver with root privileges
👍  Starting "minikube" primary control-plane node in "minikube" cluster
🚜  Pulling base image v0.0.50 ...
💾  Downloading Kubernetes v1.35.1 preload ...
    &gt; preloaded-images-k8s-v18-v1...:  272.45 MiB / 272.45 MiB  100.00% 20.73 M
    &gt; gcr.io/k8s-minikube/kicbase...:  519.58 MiB / 519.58 MiB  100.00% 24.93 M
🔥  Creating docker container (CPUs=2, Memory=3072MB) ...
🧯  Docker is nearly out of disk space, which may cause deployments to fail! (95% of capacity). You can pass '--force' to skip this check.
（中間省略：清理硬碟的建議）
🐳  Preparing Kubernetes v1.35.1 on Docker 29.2.1 ...
    ▪ kubelet.cgroups-per-qos=false
    ▪ kubelet.enforce-node-allocatable=""
🔗  Configuring bridge CNI (Container Networking Interface) ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="805" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start.png" alt="minikube start 的完整輸出：下載 Kubernetes v1.35.1、建立 2 顆 CPU 3072MB 記憶體的 docker 容器、啟動控制平面節點" class="wp-image-13198" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start-300x151.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start-1024x515.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start-768x386.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-02-minikube-start-1536x773.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這段輸出可以讀出幾件事：</p>


<ul class="wp-block-list">
<li><code>primary control-plane node</code>：Minikube 建的這個節點<strong>同時是控制平面和工作節點</strong>，一台機器包辦大腦和手腳</li>

<li>第一次要下載兩個檔案，加起來 272.45＋519.58＝<strong>792 MiB</strong>（MiB 是 1024×1024 位元組，約等於 1.05 MB）</li>

<li>這個節點配了 2 顆 CPU、3072MB（3 GB）記憶體</li>

<li><code>Docker is nearly out of disk space</code>：這台 Cloud Shell 的 Docker 空間用到 95%，這只是警告，叢集還是建起來了</li>
</ul>



<h3 class="wp-block-heading">步驟 3：看叢集裡有幾個節點</h3>



<pre class="wp-block-code"><code>kubectl get nodes</code></pre>



<pre class="wp-block-code"><code>NAME       STATUS   ROLES           AGE   VERSION
minikube   Ready    control-plane   11s   v1.35.1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1230" height="252" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-03-get-nodes.png" alt="kubectl get nodes 顯示一個叫 minikube 的節點，STATUS 是 Ready，ROLES 是 control-plane" class="wp-image-13199" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-03-get-nodes.png 1230w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-03-get-nodes-300x61.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-03-get-nodes-1024x210.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-03-get-nodes-768x157.png 768w" sizes="(max-width: 1230px) 100vw, 1230px" /></figure>


<ul class="wp-block-list">
<li><code>NAME minikube</code>：只有一個節點，名字叫 minikube</li>

<li><code>STATUS Ready</code>：kubelet 有正常回報，節點可以接工作</li>

<li><code>ROLES control-plane</code>：這台跑著控制平面，舊文章會寫成 <code>master</code></li>

<li><code>VERSION v1.35.1</code>：這個節點上 kubelet 的版本</li>
</ul>



<p class="wp-block-paragraph">正式環境通常是 3 台控制平面節點（壞一台還有兩台）加上好幾台工作節點；Minikube 為了省資源，全部塞在 1 台裡。</p>



<h3 class="wp-block-heading">步驟 4：這個「節點」其實是一個容器</h3>



<p class="wp-block-paragraph">Minikube 在 Cloud Shell 用的是 Docker 驅動程式，意思是它把「一台機器」做成一個 Docker 容器：</p>



<pre class="wp-block-code"><code>docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'</code></pre>



<pre class="wp-block-code"><code>NAMES      IMAGE                                 STATUS
minikube   gcr.io/k8s-minikube/kicbase:v0.0.50   Up 30 seconds</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="251" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container.png" alt="docker ps 顯示 minikube 節點本身是一個用 kicbase 映像檔跑起來的 Docker 容器" class="wp-image-13200" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container-300x47.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container-1024x161.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container-768x120.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-04-node-is-container-1536x241.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這就是「容器裡跑容器」：Cloud Shell 的 Docker 跑了一個叫 <code>minikube</code> 的容器，這個容器裡面又裝了一整套 Kubernetes，你的 Pod 再跑在它裡面。正式環境的節點是真的虛擬機器，但對 Kubernetes 來說都一樣是「一個節點」。</p>



<h3 class="wp-block-heading">步驟 5：找到控制平面的前門</h3>



<pre class="wp-block-code"><code>kubectl cluster-info</code></pre>



<pre class="wp-block-code"><code>Kubernetes control plane is running at https://192.168.49.2:8443
CoreDNS is running at https://192.168.49.2:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="214" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info.png" alt="kubectl cluster-info 顯示控制平面的位址是 https://192.168.49.2:8443" class="wp-image-13201" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info-300x40.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info-1024x137.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info-768x103.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-05-cluster-info-1536x205.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>https://192.168.49.2:8443</code> 就是 <strong>kube-apiserver 的地址</strong>：</p>


<ul class="wp-block-list">
<li><code>192.168.49.2</code> 是 minikube 節點的 IP（IP 是網路上每台機器的門牌號碼）</li>

<li><code>8443</code> 是 Port（埠號，同一台機器上不同服務的「分機號碼」），Minikube 的 API 伺服器開在 8443</li>

<li><code>https</code> 代表連線有加密，kubectl 每次都帶著憑證去敲這個門</li>
</ul>



<p class="wp-block-paragraph">CoreDNS 那行是叢集內的「電話簿」，讓 Pod 可以用名字找到彼此，第 13 篇講 Service 時會用到。</p>



<h3 class="wp-block-heading">步驟 6：點名控制平面的元件</h3>



<p class="wp-block-paragraph">控制平面的元件在 Minikube 裡都是以 Pod 的形式跑在 <code>kube-system</code> 這個命名空間（Namespace）裡。<strong>命名空間是叢集裡的資料夾</strong>，用來把不同用途的東西分開放；系統元件放 <code>kube-system</code>，你自己建的東西預設放 <code>default</code>。</p>



<pre class="wp-block-code"><code>kubectl get pods -n kube-system -o wide</code></pre>



<pre class="wp-block-code"><code>NAME                               READY   STATUS    RESTARTS   AGE   IP             NODE       NOMINATED NODE   READINESS GATES
coredns-7d764666f9-sz25f           1/1     Running   0          20s   10.244.0.2     minikube   &lt;none&gt;           &lt;none&gt;
etcd-minikube                      1/1     Running   0          27s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;
kube-apiserver-minikube            1/1     Running   0          25s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;
kube-controller-manager-minikube   1/1     Running   0          25s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;
kube-proxy-r55ft                   1/1     Running   0          21s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;
kube-scheduler-minikube            1/1     Running   0          26s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;
storage-provisioner                1/1     Running   0          24s   192.168.49.2   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="270" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods.png" alt="kubectl get pods -n kube-system 列出 7 個系統 Pod：coredns、etcd、kube-apiserver、kube-controller-manager、kube-proxy、kube-scheduler、storage-provisioner" class="wp-image-13202" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods-300x51.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods-1024x173.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods-768x130.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-06-system-pods-1536x259.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">把這 7 個 Pod 對回架構圖：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Pod</th><th>屬於</th><th>角色</th></tr></thead><tbody><tr><td><code>kube-apiserver-minikube</code></td><td>控制平面</td><td>唯一的窗口</td></tr><tr><td><code>etcd-minikube</code></td><td>控制平面</td><td>帳本</td></tr><tr><td><code>kube-scheduler-minikube</code></td><td>控制平面</td><td>派工</td></tr><tr><td><code>kube-controller-manager-minikube</code></td><td>控制平面</td><td>對帳、補位</td></tr><tr><td><code>kube-proxy-r55ft</code></td><td>節點</td><td>網路轉送</td></tr><tr><td><code>coredns-7d764666f9-sz25f</code></td><td>外掛（Addon）</td><td>叢集內的 DNS 電話簿</td></tr><tr><td><code>storage-provisioner</code></td><td>Minikube 外掛</td><td>幫你自動建硬碟空間，<a href="https://dongdonggcp.com/2026/11/21/k8s-volume-pv-pvc/">第 16 篇</a>會用</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">兩個值得注意的地方：</p>


<ul class="wp-block-list">
<li><strong>控制平面 4 個元件的名字都是「元件名-節點名」</strong>（<code>-minikube</code>），而且 IP 都是節點的 <code>192.168.49.2</code>。這代表它們直接用節點的網路，因為它們是 kubelet 直接啟動的「靜態 Pod」（步驟 7 說明）</li>

<li><strong>coredns 的 IP 是 <code>10.244.0.2</code></strong>，這是 Pod 專用的網段，跟節點的 IP 不一樣。一般 Pod 都會拿到這種 IP</li>
</ul>



<h3 class="wp-block-heading">步驟 7：控制平面的設定檔放在節點上</h3>



<p class="wp-block-paragraph">API 伺服器是控制平面的前門，可是它自己也是一個 Pod。那是誰把它跑起來的？答案是<strong>節點上的 kubelet 直接讀一個資料夾裡的 YAML 檔</strong>（YAML 是一種用縮排表示層次的設定檔格式，Kubernetes 的設定幾乎都用它寫）：</p>



<pre class="wp-block-code"><code>minikube ssh -- ls /etc/kubernetes/manifests</code></pre>



<pre class="wp-block-code"><code>etcd.yaml  kube-apiserver.yaml  kube-controller-manager.yaml  kube-scheduler.yaml</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="165" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests.png" alt="minikube ssh 列出 /etc/kubernetes/manifests 資料夾裡的四個 YAML：etcd、kube-apiserver、kube-controller-manager、kube-scheduler" class="wp-image-13203" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests-300x31.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests-1024x106.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests-768x79.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-07-static-manifests-1536x158.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>minikube ssh -- 指令</code> 的意思是「進到 minikube 節點裡執行這個指令」。這個資料夾剛好放著控制平面 4 個元件的設定檔。</p>



<p class="wp-block-paragraph">這種 Pod 叫 <strong>靜態 Pod（Static Pod）</strong>：</p>


<ul class="wp-block-list">
<li><strong>白話</strong>：不是透過 API 伺服器建的，而是 kubelet 直接看資料夾裡的檔案就跑起來的 Pod</li>

<li><strong>比喻</strong>：餐廳開門前，組長照著牆上貼的「開店檢查表」先把櫃檯和訂單本準備好；櫃檯開了之後，客人的單才能進來</li>

<li><strong>來龍去脈</strong>：這是為了解決「雞生蛋」的問題。API 伺服器還沒啟動時，沒有人能透過 API 建 Pod，所以控制平面自己要用這種不經過 API 的方式先跑起來（<a href="https://kubernetes.io/docs/tasks/configure-pod-container/static-pod/">Kubernetes 官方說明：Static Pods</a>）</li>

<li><strong>為什麼要學</strong>：CKA 考試會考「控制平面元件壞了怎麼修」，答案常常就是去改這個資料夾裡的 YAML。kubelet 會盯著這個資料夾，檔案一改、一搬走，Pod 就跟著變，步驟 12 的實驗就是用這招</li>
</ul>



<h3 class="wp-block-heading">步驟 8：kubelet 不是 Pod</h3>



<p class="wp-block-paragraph"><code>kubectl get pods -n kube-system</code> 列出的 7 個系統 Pod 裡<strong>沒有 kubelet</strong>。它在哪？</p>



<pre class="wp-block-code"><code>minikube ssh -- systemctl is-active kubelet docker; minikube ssh -- pgrep -a kubelet | cut -c1-120</code></pre>



<pre class="wp-block-code"><code>active
active
2043 /var/lib/minikube/binaries/v1.35.1/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --cgroups-</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="157" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service.png" alt="minikube ssh 查到 kubelet 和 docker 都是 active 的系統服務，kubelet 是一個一般程式而不是 Pod" class="wp-image-13204" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service-300x29.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service-1024x100.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service-768x75.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-08-kubelet-service-1536x151.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><code>systemctl is-active</code> 是查詢「系統服務」狀態的指令，兩個 <code>active</code> 分別代表 kubelet 和 docker 這兩個服務都在跑</li>

<li><code>pgrep -a kubelet</code> 找到 kubelet 是節點上編號 2043 的一般程式（程式在執行中就叫「程序」，每個程序有一個編號），執行檔在 <code>/var/lib/minikube/binaries/v1.35.1/kubelet</code></li>
</ul>



<p class="wp-block-paragraph">所以 <strong>kubelet 和容器執行環境是直接裝在節點上的服務</strong>，不是 Pod。它們是負責「跑 Pod」的人，自己當然不能是 Pod。</p>



<h3 class="wp-block-heading">步驟 9：建一個網站，看它被派到哪裡</h3>



<pre class="wp-block-code"><code>kubectl create deployment web --image=nginx; sleep 25; kubectl get pods -o wide</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web created
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
web-68d995574f-r885l   1/1     Running   0          25s   10.244.0.3   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="171" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy.png" alt="kubectl create deployment 建立 nginx 網站，Pod 狀態 Running、IP 10.244.0.3、被派到 minikube 節點" class="wp-image-13205" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy-300x32.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy-1024x109.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy-768x82.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-09-create-deploy-1536x164.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>Deployment 是「幫你維持 Pod 數量和版本」的設定</strong>，<a href="https://dongdonggcp.com/2026/11/21/k8s-deployment-rolling-update-rollback/">第 12 篇</a>會完整教，這裡先用它建 1 個 nginx 網站。<code>sleep 25</code> 是等 25 秒再看，讓映像檔有時間下載。</p>



<p class="wp-block-paragraph">Pod 名字 <code>web-68d995574f-r885l</code> 可以拆成三段：<code>web</code> 是 Deployment 的名字、<code>68d995574f</code> 是它底下 ReplicaSet 的代號、<code>r885l</code> 是隨機產生的 5 個字。<code>NODE minikube</code> 就是排程器挑的節點。</p>



<h3 class="wp-block-heading">步驟 10：看事件紀錄，誰做了什麼</h3>



<p class="wp-block-paragraph">每個元件做完事都會留一筆「事件」（Event），照時間排序就能看到分工：</p>



<pre class="wp-block-code"><code>kubectl get events --sort-by=.metadata.creationTimestamp | grep -v -i node</code></pre>



<pre class="wp-block-code"><code>LAST SEEN   TYPE     REASON                    OBJECT                      MESSAGE
32s         Normal   Scheduled                 pod/web-68d995574f-r885l    Successfully assigned default/web-68d995574f-r885l to minikube
32s         Normal   SuccessfulCreate          replicaset/web-68d995574f   Created pod: web-68d995574f-r885l
32s         Normal   ScalingReplicaSet         deployment/web              Scaled up replica set web-68d995574f from 0 to 1
31s         Normal   Pulling                   pod/web-68d995574f-r885l    Pulling image "nginx"
25s         Normal   Pulled                    pod/web-68d995574f-r885l    Successfully pulled image "nginx" in 6.02s (6.02s including waiting). Image size: 163294089 bytes.
24s         Normal   Created                   pod/web-68d995574f-r885l    Container created
24s         Normal   Started                   pod/web-68d995574f-r885l    Container started</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="256" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events.png" alt="kubectl get events 依時間列出 Scheduled、SuccessfulCreate、ScalingReplicaSet、Pulling、Pulled、Created、Started 七筆事件" class="wp-image-13206" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events-300x48.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events-1024x164.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events-768x123.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-10-events-1536x246.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>grep -v -i node</code> 是把跟節點開機有關的事件濾掉，只留這個網站的。把每一行對回元件：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>REASON</th><th>誰寫的</th><th>對應流程圖第幾步</th></tr></thead><tbody><tr><td><code>ScalingReplicaSet</code></td><td>Deployment 控制器</td><td>第 3 步：建 ReplicaSet</td></tr><tr><td><code>SuccessfulCreate</code></td><td>ReplicaSet 控制器</td><td>第 3 步：建 Pod</td></tr><tr><td><code>Scheduled</code></td><td>kube-scheduler（default-scheduler）</td><td>第 4 步：挑節點</td></tr><tr><td><code>Pulling</code>、<code>Pulled</code></td><td>kubelet</td><td>第 5 步：拉映像檔</td></tr><tr><td><code>Created</code>、<code>Started</code></td><td>kubelet</td><td>第 6、7 步：啟動容器</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">前三行都是「32 秒前」，代表控制平面在同一秒內就做完決定；真正花時間的是拉映像檔：nginx 映像檔 163,294,089 位元組，約 <strong>163 MB</strong>，下載用了 <strong>6.02 秒</strong>。映像檔越大，這一步越久，這也是<a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">第 8 篇</a>要把映像檔變小的原因。</p>



<p class="wp-block-paragraph">想看某一個 Pod 的事件，也可以用 <code>kubectl describe pod Pod名字</code>，最下面的 Events 會多一欄 <code>From</code>，直接寫是誰做的。</p>



<h3 class="wp-block-heading">步驟 11：刪掉 Pod，控制器馬上補</h3>



<pre class="wp-block-code"><code>kubectl delete pod -l app=web; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>pod "web-68d995574f-r885l" deleted from default namespace
NAME                   READY   STATUS              RESTARTS   AGE
web-68d995574f-lxbjx   0/1     ContainerCreating   0          1s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="296" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal.png" alt="刪掉 nginx Pod 之後，ReplicaSet 控制器在 1 秒內建出一個新名字的 Pod" class="wp-image-13207" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal-300x56.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal-1024x189.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal-768x142.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-11-self-heal-1536x284.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>-l app=web</code> 是「刪掉所有標籤是 app=web 的 Pod」。刪完立刻看，已經有一個<strong>新名字</strong>（<code>lxbjx</code>）的 Pod 在建立中，<code>AGE 1s</code>。</p>



<p class="wp-block-paragraph">這就是控制器在對帳：帳本上寫要 1 個，實際剩 0 個，於是馬上補一個。你沒有下任何「重開」的指令。</p>



<h3 class="wp-block-heading">步驟 12：實驗，把排程器拿掉</h3>



<p class="wp-block-paragraph">接下來做一個破壞性的小實驗：把排程器的設定檔從 manifests 資料夾搬走，kubelet 就會把排程器的 Pod 停掉。<strong>這只能在練習用的叢集做</strong>，正式環境不要試。</p>



<pre class="wp-block-code"><code>minikube ssh -- sudo mv /etc/kubernetes/manifests/kube-scheduler.yaml /tmp/; sleep 40; kubectl get pods -n kube-system</code></pre>



<pre class="wp-block-code"><code>NAME                               READY   STATUS    RESTARTS      AGE
coredns-7d764666f9-sz25f           1/1     Running   0             2m4s
etcd-minikube                      1/1     Running   0             2m11s
kube-apiserver-minikube            1/1     Running   0             2m9s
kube-controller-manager-minikube   1/1     Running   0             2m9s
kube-proxy-r55ft                   1/1     Running   0             2m5s
storage-provisioner                1/1     Running   1 (94s ago)   2m8s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="261" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone.png" alt="把 kube-scheduler.yaml 搬走 40 秒後，kube-system 裡的 kube-scheduler-minikube 消失了，只剩 6 個系統 Pod" class="wp-image-13208" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone-300x49.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone-1024x167.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone-768x125.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-12-scheduler-gone-1536x251.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>sudo mv</code> 是用管理員權限搬移檔案。40 秒後再看，<code>kube-scheduler-minikube</code> 從清單上消失了，剩 6 個。</p>



<h3 class="wp-block-heading">步驟 13：沒有排程器，新 Pod 卡在 Pending</h3>



<p class="wp-block-paragraph">把網站從 1 個擴成 3 個：</p>



<pre class="wp-block-code"><code>kubectl scale deployment web --replicas=3; sleep 10; kubectl get pods</code></pre>



<pre class="wp-block-code"><code>deployment.apps/web scaled
NAME                   READY   STATUS    RESTARTS   AGE
web-68d995574f-4f5lc   0/1     Pending   0          10s
web-68d995574f-8975t   0/1     Pending   0          10s
web-68d995574f-lxbjx   1/1     Running   0          68s</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="351" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending.png" alt="沒有排程器時擴成 3 個 Pod，新的 2 個卡在 Pending，舊的 1 個照樣 Running" class="wp-image-13209" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending-300x66.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending-1024x225.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending-768x168.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-13-pending-1536x337.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這個結果把分工講得很清楚：</p>


<ul class="wp-block-list">
<li><strong>控制器還在</strong>，所以它照樣建出 2 個新 Pod（帳本上要 3 個）</li>

<li><strong>排程器不在</strong>，沒有人幫這 2 個 Pod 挑節點，它們就一直停在 <code>Pending</code>（等待中）</li>

<li><strong>原本那個 Pod（<code>lxbjx</code>）照樣 <code>Running</code></strong>：控制平面少了一個元件，不會讓已經在跑的網站停掉</li>
</ul>



<p class="wp-block-paragraph">以後你看到 Pod 卡在 <code>Pending</code>，第一個要懷疑的就是「排程器找不到合適的節點」。正式環境的原因通常不是排程器不見，而是節點的 CPU、記憶體不夠，這會在<a href="https://dongdonggcp.com/2026/11/21/k8s-pod-troubleshooting-crashloopbackoff/">第 18 篇</a>排錯時示範。</p>



<h3 class="wp-block-heading">步驟 14：把排程器放回去</h3>



<pre class="wp-block-code"><code>minikube ssh -- sudo mv /tmp/kube-scheduler.yaml /etc/kubernetes/manifests/; sleep 45; kubectl get pods -o wide</code></pre>



<pre class="wp-block-code"><code>NAME                   READY   STATUS    RESTARTS   AGE    IP           NODE       NOMINATED NODE   READINESS GATES
web-68d995574f-4f5lc   1/1     Running   0          68s    10.244.0.5   minikube   &lt;none&gt;           &lt;none&gt;
web-68d995574f-8975t   1/1     Running   0          68s    10.244.0.6   minikube   &lt;none&gt;           &lt;none&gt;
web-68d995574f-lxbjx   1/1     Running   0          2m6s   10.244.0.4   minikube   &lt;none&gt;           &lt;none&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="196" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back.png" alt="把 kube-scheduler.yaml 放回去 45 秒後，原本 Pending 的 2 個 Pod 都被排到 minikube 節點並且 Running" class="wp-image-13210" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back-300x37.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back-1024x125.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back-768x94.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-15-scheduler-back-1536x188.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">檔案放回去，kubelet 看到了就把排程器重新跑起來；排程器一上線，就把那 2 個 Pending 的 Pod 排進節點，45 秒後 3 個都是 <code>Running</code>。順便確認排程器回來了，也看一下 API 伺服器的版本：</p>



<pre class="wp-block-code"><code>kubectl get pods -n kube-system | grep scheduler; kubectl version</code></pre>



<pre class="wp-block-code"><code>kube-scheduler-minikube            1/1     Running   0            54s
Client Version: v1.35.9-dispatcher
Kustomize Version: v5.7.1
Server Version: v1.35.1</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="322" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server.png" alt="kube-scheduler-minikube 重新出現且 Running，kubectl version 顯示 Server Version v1.35.1" class="wp-image-13211" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server-300x60.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server-1024x206.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server-768x155.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-16-version-server-1536x309.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>Server Version</code> 就是 kube-apiserver 的版本 v1.35.1。kubectl（v1.35.9）和它都是 1.35，官方規定 kubectl 可以跟 API 伺服器差一個小版本（例如 1.34～1.36 都能管 1.35 的叢集），差更多就可能有指令不相容（<a href="https://kubernetes.io/releases/version-skew-policy/">Kubernetes 版本差異政策</a>）。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">實測時的意外</h2>



<h3 class="wp-block-heading">1. Cloud Shell 的 Docker 空間只剩 5%</h3>



<p class="wp-block-paragraph"><code>minikube start</code> 跳出 <code>Docker is nearly out of disk space ... (95% of capacity)</code>，叢集最後還是有建起來。同一天寫第 10 篇時用 <code>docker system df</code> 查，這台 Cloud Shell 的 Docker 只有 1 個映像檔（1.936GB），代表空間緊是因為 Cloud Shell 給 Docker 的系統碟本來就小，不是殘留太多東西。</p>



<p class="wp-block-paragraph">練習用不影響，看到可以先不理。如果真的建失敗，再用 <code>docker system prune -a</code> 清掉沒在用的映像檔（它會先問你確定才刪）。</p>



<h3 class="wp-block-heading">2. 控制平面的元件少一個，網站沒停</h3>



<p class="wp-block-paragraph">很多人以為「控制平面掛了，網站就掛了」。實測拿掉排程器時，原本的 nginx Pod 一直是 <code>Running</code>，只有「新的工作」排不進來。原因是容器是 kubelet 和容器執行環境在顧，它們都在節點上，不需要排程器。</p>



<p class="wp-block-paragraph">但這不代表控制平面可以隨便掛：API 伺服器掛了，你就不能部署、不能擴展；控制器掛了，Pod 壞了沒人補。所以正式環境的控制平面通常放 3 份。</p>



<h3 class="wp-block-heading">3. Minikube 預設的不是最新版 Kubernetes</h3>



<p class="wp-block-paragraph">這次叢集是 v1.35.1，但 Kubernetes 官方最新版已經是 1.37.1（2026 年 9 月 15 日發布）。官方同時維護最新的 3 個小版本（目前是 1.37、1.36、1.35），每個大約支援 1 年，所以 1.35 還在支援範圍內（2026 年 11 月查 <a href="https://kubernetes.io/releases/">Kubernetes Releases</a>）。</p>



<p class="wp-block-paragraph">Minikube 每一版會預設它測過的 Kubernetes 版本，想用別版可以加 <code>--kubernetes-version=v1.37.1</code>。學架構用 1.35 完全沒問題。</p>



<h3 class="wp-block-heading">4. kubectl 刪除的訊息變長了</h3>



<p class="wp-block-paragraph">網路舊教學刪 Pod 的輸出是 <code>pod "xxx" deleted</code>，這次是 <code>pod "web-68d995574f-r885l" deleted from default namespace</code>，多寫了是從哪個命名空間刪的。意思一樣，看到不要以為出錯。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<p class="wp-block-paragraph">Cloud Shell 和 Minikube 都不收錢，但 Minikube 會佔用 Cloud Shell 的硬碟和記憶體，用完刪掉比較乾淨：</p>



<pre class="wp-block-code"><code>kubectl delete deployment web; minikube delete</code></pre>



<pre class="wp-block-code"><code>deployment.apps "web" deleted from default namespace
🔥  Deleting "minikube" in docker ...
🔥  Deleting container "minikube" ...
🔥  Removing /google/minikube/.minikube/machines/minikube ...
💀  Removed all traces of the "minikube" cluster.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1487" height="390" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-17-cleanup.png" alt="kubectl delete deployment 刪掉網站，minikube delete 刪掉整個叢集" class="wp-image-13212" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-17-cleanup.png 1487w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-17-cleanup-300x79.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-17-cleanup-1024x269.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-17-cleanup-768x201.png 768w" sizes="(max-width: 1487px) 100vw, 1487px" /></figure>



<p class="wp-block-paragraph">確認叢集和節點容器都不見了：</p>



<pre class="wp-block-code"><code>minikube status; docker ps</code></pre>



<pre class="wp-block-code"><code>🤷  Profile "minikube" not found. Run "minikube profile list" to view all profiles.
👉  To start a cluster, run: "minikube start"
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="237" src="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete.png" alt="minikube status 顯示找不到 minikube，docker ps 沒有任何容器在跑" class="wp-image-13213" srcset="https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete-300x44.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete-1024x152.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete-768x114.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/11/ct09-shots-18-after-delete-1536x228.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>docker ps</code> 是空的，代表當作節點的那個 <code>minikube</code> 容器也刪掉了。下一篇要用時再 <code>minikube start</code> 就好，下載過的檔案有留著，第二次會快一些。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">到了 GCP 上叫什麼</h2>



<p class="wp-block-paragraph">Google Cloud 上跑 Kubernetes 的服務叫 <strong>GKE（Google Kubernetes Engine）</strong>，架構完全一樣，差別在「誰負責管」：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元件</th><th>自己裝（像 Minikube）</th><th>GKE</th></tr></thead><tbody><tr><td>控制平面（API 伺服器、etcd、排程器、控制器）</td><td>自己顧、自己備份、自己升級</td><td>Google 代管，<code>kube-system</code> 裡看不到 <code>kube-apiserver</code> 的 Pod</td></tr><tr><td>節點</td><td>自己準備機器</td><td>Standard 模式：你選 VM 規格、付 VM 的錢；Autopilot 模式：Google 管節點，照 Pod 要求的資源計費</td></tr><tr><td>叢集管理費</td><td>沒有</td><td>每個叢集每小時 0.10 美元</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>算一次叢集管理費</strong>：一個月以 730 小時算，0.10 × 730＝<strong>73 美元</strong>。GKE 每個帳單帳戶每月有 74.40 美元的免費額度，可以抵掉 1 個區域（zonal）Standard 叢集或 1 個 Autopilot 叢集的管理費（2026 年 11 月查 <a href="https://cloud.google.com/kubernetes-engine/pricing">GKE 定價頁</a>）。叢集開越多，管理費就越多；節點和 Pod 用的資源另外算。</p>



<p class="wp-block-paragraph">這部分會在第 24 篇：<a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a>詳細比較。</p>



<p class="wp-block-paragraph">如果連節點都不想管，Google 還有 <strong>Cloud Run</strong>：你只給容器映像檔，連叢集都不用建，後面<a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">第 20 篇</a>會教。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試／證照會怎麼問</h2>



<h3 class="wp-block-heading">面試常見題</h3>


<ul class="wp-block-list">
<li><strong>「你下 <code>kubectl apply</code> 之後發生了什麼？」</strong>：照流程圖講 7 步，重點是「每個元件只做一段，都透過 API 伺服器交接」</li>

<li><strong>「控制平面掛了，應用程式會停嗎？」</strong>：已經在跑的 Pod 不會馬上停（kubelet 在顧），但不能部署、不能擴展，壞掉的 Pod 也沒人補。可以舉「拿掉排程器，新 Pod 卡 Pending、舊 Pod 照跑」的例子</li>

<li><strong>「etcd 是什麼？為什麼要備份？」</strong>：叢集所有狀態都存在 etcd，它壞了又沒備份，等於叢集失憶</li>

<li><strong>「kubelet 是 Pod 嗎？」</strong>：不是，它是節點上的系統服務，負責跑 Pod</li>

<li><strong>「Pod 一直 Pending，你會先查什麼？」</strong>：<code>kubectl describe pod</code> 看 Events，通常是排程器找不到資源夠的節點</li>
</ul>



<h3 class="wp-block-heading">Kubernetes 證照（CKA、CKAD）</h3>



<p class="wp-block-paragraph">Kubernetes 的證照是<strong>上機實作考</strong>，不是選擇題：考試時給你真的叢集，你要在終端機裡把事情做出來。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>CKA（管理員）</th><th>CKAD（應用程式開發者）</th></tr></thead><tbody><tr><td>重點</td><td>建叢集、維護、排錯</td><td>部署和設定應用程式</td></tr><tr><td>跟這篇的關係</td><td>「叢集架構、安裝與設定」25%、「排錯」30%，架構是核心</td><td>架構考得少，但要懂 Pod 怎麼被排程</td></tr><tr><td>費用與形式</td><td>445 美元、2 小時、實作、含 1 次補考、效期 2 年</td><td>445 美元、2 小時、實作、含 1 次補考、效期 2 年</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">（2026 年 11 月查 <a href="https://training.linuxfoundation.org/certification/certified-kubernetes-administrator-cka/">CKA 官方頁</a>，CKA 目前以 Kubernetes v1.37 出題）</p>



<p class="wp-block-paragraph">CKA 常見的操作題：控制平面元件壞了，去 <code>/etc/kubernetes/manifests</code> 修 YAML；備份和還原 etcd；查節點為什麼 <code>NotReady</code>（通常是 kubelet 沒在跑）。</p>



<h3 class="wp-block-heading">看到這些字，就想到這個</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「所有請求的入口」「認證、授權」</td><td>kube-apiserver</td></tr><tr><td>「叢集狀態存在哪」「備份與還原」</td><td>etcd</td></tr><tr><td>「Pod 要放哪個節點」「Pending」</td><td>kube-scheduler</td></tr><tr><td>「Pod 少了自動補」「期望狀態」</td><td>kube-controller-manager</td></tr><tr><td>「節點 NotReady」「節點上負責跑 Pod」</td><td>kubelet</td></tr><tr><td>「Service 的流量轉送規則」</td><td>kube-proxy</td></tr><tr><td>「控制平面元件的 YAML 放哪」</td><td><code>/etc/kubernetes/manifests</code>（靜態 Pod）</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">K8s 架構有哪些元件？</h3>



<p class="wp-block-paragraph">分兩半。控制平面有 kube-apiserver（窗口）、etcd（資料庫）、kube-scheduler（挑節點）、kube-controller-manager（對帳補位），雲端環境再加一個選配的 cloud-controller-manager。每個節點上有 kubelet（跑 Pod 的組長）、容器執行環境（真的啟動容器）、kube-proxy（網路轉送，選配）。</p>



<h3 class="wp-block-heading">Master 節點和控制平面是一樣的東西嗎？</h3>



<p class="wp-block-paragraph">是。Master（主節點）是舊說法，現在 Kubernetes 官方統一叫控制平面（control plane），kubeadm 也已經不再使用 <code>node-role.kubernetes.io/master</code> 這個舊標記，改成 <code>control-plane</code>。網路上舊文章寫 Master，指的就是跑控制平面元件的那台機器。</p>



<h3 class="wp-block-heading">控制平面掛了，網站會停嗎？</h3>



<p class="wp-block-paragraph">已經在跑的 Pod 通常不會馬上停，因為容器是節點上的 kubelet 和容器執行環境在顧。但你不能部署新版本、不能擴展，Pod 壞了也不會自動補。這次實測把排程器拿掉，舊的 nginx Pod 照樣 Running，新的 2 個 Pod 卡在 Pending。</p>



<h3 class="wp-block-heading">為什麼 kubectl get pods 看不到 kubelet？</h3>



<p class="wp-block-paragraph">因為 kubelet 不是 Pod，它是直接裝在節點作業系統上的服務，負責把 Pod 跑起來。用 <code>minikube ssh -- systemctl is-active kubelet</code> 才看得到它是 <code>active</code>。容器執行環境也一樣。</p>



<h3 class="wp-block-heading">控制平面的元件為什麼也是 Pod？誰把它們跑起來的？</h3>



<p class="wp-block-paragraph">它們是「靜態 Pod」：節點上的 kubelet 直接讀 <code>/etc/kubernetes/manifests</code> 資料夾裡的 YAML 檔把它們跑起來，不經過 API 伺服器。這樣才能解決「API 伺服器還沒啟動，就沒人能建 Pod」的雞生蛋問題。</p>



<h3 class="wp-block-heading">Minikube 只有一個節點，跟正式環境差在哪？</h3>



<p class="wp-block-paragraph">Minikube 把控制平面和工作節點塞在同一台（而且那台還是一個 Docker 容器），方便練習。正式環境通常有 3 台控制平面節點加上多台工作節點，任何一台壞掉都不影響整體。元件和運作方式是一樣的，所以用 Minikube 學架構完全夠用。</p>



<h3 class="wp-block-heading">Kubernetes 和 Docker 是什麼關係？</h3>



<p class="wp-block-paragraph">Docker 負責「把程式包成映像檔、在一台機器上跑容器」；Kubernetes 負責「在很多台機器上管理很多容器」。Kubernetes 1.24 起移除了直接支援 Docker 的 dockershim，現在主流的容器執行環境是 containerd；但用 Docker 建出來的映像檔，Kubernetes 照樣可以跑。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>K8s 架構分兩半</strong>：控制平面做決定（kube-apiserver、etcd、kube-scheduler、kube-controller-manager），節點跑容器（kubelet、容器執行環境、kube-proxy）</li>

<li><strong>所有元件都只跟 API 伺服器講話</strong>，叢集狀態存在 etcd；一個 Pod 被建出來要經過 7 步，用 <code>kubectl get events</code> 就看得到誰做了哪一步</li>

<li><strong>控制平面是靜態 Pod，kubelet 不是 Pod</strong>：控制平面的 YAML 放在節點的 <code>/etc/kubernetes/manifests</code>，kubelet 是節點上的系統服務</li>

<li><strong>實測拿掉排程器</strong>：新的 2 個 Pod 卡在 Pending、舊的照跑，放回去 45 秒內全部 Running</li>

<li><strong>GKE 幫你管控制平面</strong>：每個叢集每小時 0.10 美元，一個月約 73 美元，每月 74.40 美元免費額度可以抵 1 個叢集</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/10/27/docker-tutorial-cloud-shell-first-container/">Docker 入門教學：不用安裝，用 Cloud Shell 跑出第一個容器</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-image-vs-container-layer-tag/">Docker 映像檔和容器差在哪？Image、Layer、Tag 白話解釋</a></li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-compose-tutorial-flask-mysql/">Docker Compose 教學：一個 YAML 開起網站＋資料庫</a></li>

<li>上一篇：第 8 篇：<a href="https://dongdonggcp.com/2026/11/18/docker-multi-stage-build-dockerignore/">映像檔太肥怎麼辦？Docker 多階段建置與 .dockerignore</a></li>

<li>下一篇：第 10 篇：<a href="https://dongdonggcp.com/2026/11/21/minikube-tutorial-cloud-shell-kubectl-commands/">Minikube 教學：在 Cloud Shell 免費建 K8s 叢集＋kubectl 必學指令</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/07/21/what-is-kubernetes/">Kubernetes 是什麼？白話解釋＋判斷你是否真的需要它</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/what-is-container-technology-docker-guide/">容器 (Container) 技術是什麼？從零開始看懂 Docker 與容器化應用</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/google-kubernetes-engine-tutorials/">GKE 是什麼？Google Kubernetes Engine 教學：Autopilot 和 Standard 怎麼選</a></li>

<li><a href="https://dongdonggcp.com/2026/07/29/cloud-jobs-comparison/">雲端職缺大解析：雲端工程師、架構師、SRE、DevOps、資料工程師差在哪？</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">Kubernetes 的架構看懂之後，接下來就是實際操作叢集。如果你想有系統地從容器一路學到在 Google Cloud 上部署服務，可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "K8s 架構有哪些元件？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "分兩半。控制平面有 kube-apiserver（窗口）、etcd（資料庫）、kube-scheduler（挑節點）、kube-controller-manager（對帳補位），雲端環境再加一個選配的 cloud-controller-manager。每個節點上有 kubelet（跑 Pod 的組長）、容器執行環境（真的啟動容器）、kube-proxy（網路轉送，選配）。"
      }
    },
    {
      "@type": "Question",
      "name": "Master 節點和控制平面是一樣的東西嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "是。Master（主節點）是舊說法，現在 Kubernetes 官方統一叫控制平面（control plane），kubeadm 也已經不再使用 `node-role.kubernetes.io/master` 這個舊標記，改成 `control-plane`。網路上舊文章寫 Master，指的就是跑控制平面元件的那台機器。"
      }
    },
    {
      "@type": "Question",
      "name": "控制平面掛了，網站會停嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "已經在跑的 Pod 通常不會馬上停，因為容器是節點上的 kubelet 和容器執行環境在顧。但你不能部署新版本、不能擴展，Pod 壞了也不會自動補。這次實測把排程器拿掉，舊的 nginx Pod 照樣 Running，新的 2 個 Pod 卡在 Pending。"
      }
    },
    {
      "@type": "Question",
      "name": "為什麼 kubectl get pods 看不到 kubelet？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "因為 kubelet 不是 Pod，它是直接裝在節點作業系統上的服務，負責把 Pod 跑起來。用 `minikube ssh -- systemctl is-active kubelet` 才看得到它是 `active`。容器執行環境也一樣。"
      }
    },
    {
      "@type": "Question",
      "name": "控制平面的元件為什麼也是 Pod？誰把它們跑起來的？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "它們是「靜態 Pod」：節點上的 kubelet 直接讀 `/etc/kubernetes/manifests` 資料夾裡的 YAML 檔把它們跑起來，不經過 API 伺服器。這樣才能解決「API 伺服器還沒啟動，就沒人能建 Pod」的雞生蛋問題。"
      }
    },
    {
      "@type": "Question",
      "name": "Minikube 只有一個節點，跟正式環境差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Minikube 把控制平面和工作節點塞在同一台（而且那台還是一個 Docker 容器），方便練習。正式環境通常有 3 台控制平面節點加上多台工作節點，任何一台壞掉都不影響整體。元件和運作方式是一樣的，所以用 Minikube 學架構完全夠用。"
      }
    },
    {
      "@type": "Question",
      "name": "Kubernetes 和 Docker 是什麼關係？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Docker 負責「把程式包成映像檔、在一台機器上跑容器」；Kubernetes 負責「在很多台機器上管理很多容器」。Kubernetes 1.24 起移除了直接支援 Docker 的 dockershim，現在主流的容器執行環境是 containerd；但用 Docker 建出來的映像檔，Kubernetes 照樣可以跑。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/">K8s 架構白話：Kubernetes 控制平面、節點、Pod 怎麼分工</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/11/21/k8s-architecture-control-plane-node-pod/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
