iT邦幫忙

2026 iThome 鐵人賽

0
Build on Google AI

將考國際證照的應用程式變成開源系列 第 77 篇

Google Cloud 的全代管無伺服器(Serverless)運算平台

  • 分享至 

  • xImage
  •  

1. 核心概念與架構

  • Cloud Run:Google Cloud 的全代管無伺服器(Serverless)運算平台。它負責自動管理底層基礎架構,支援將任意 Stateless(無狀態)容器透過 HTTP 請求進行觸發與調用。具備自動水平擴展(Auto-scaling)與縮容至零(Scale to Zero)的特性,計費僅以處理請求期間的 CPU、記憶體與網路資源計算。
  • Artifact Registry:Google Cloud 存放容器映像檔(Container Images)與套件的代管倉庫(前身為 Container Registry / GCR),提供精細的 IAM 權限控管與安全掃描。
  • Cloud Build:Google Cloud 上的無伺服器建置服務,直接在雲端拉取程式碼、執行 Dockerfile 建置,並將產出的 Image 推送到 Artifact Registry,本機或 Cloud Shell 不需要常駐高資源的 Docker daemon。

2. 實作流程架構圖

[原始碼 (Node.js + Dockerfile)]
              │
              ▼ (gcloud builds submit)
   [Cloud Build 雲端建置]
              │
              ▼ (Push)
[Artifact Registry 映像檔存放庫]
              │
              ▼ (gcloud run deploy)
      [Cloud Run 服務] ─── (公開 HTTPS 端點)


3. 全程 CLI 步驟與指令詳解

Task 1. 啟用服務 API 與環境變數設定

啟用 Cloud Run 與 Artifact Registry 的 API 介面,並配置預設區域。

# 1. 啟用專案對應的 Cloud Run 與 Artifact Registry API
gcloud services enable run.googleapis.com artifactregistry.googleapis.com

# 2. 設定預設計算區域 (Compute Region)
gcloud config set compute/region us-west1

# 3. 匯出 Shell 環境變數,方便後續指令重複引用
export LOCATION="us-west1"

  • 參數說明:
  • gcloud services enable:在 GCP 專案內啟用特定 API 服務。
  • gcloud config set compute/region:設定本機 gcloud CLI 的預設地理區域。

Task 2. 編寫 Node.js 應用程式碼

建立一個標準的 Express.js 輕量 HTTP 服務。此服務會監聽由環境變數 PORT(預設為 8080)傳入的埠號,並在根路徑 / 回應 Hello World!。

# 1. 建立專案目錄並切換路徑
mkdir helloworld && cd helloworld

# 2. 建立 package.json 定義專案相依性
cat << 'EOF' > package.json
{
  "name": "helloworld",
  "description": "Simple hello world sample in Node",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Google LLC",
  "license": "Apache-2.0",
  "dependencies": {
    "express": "^4.17.1"
  }
}
EOF

# 3. 建立服務主程式 index.js
cat << 'EOF' > index.js
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

app.get('/', (req, res) => {
  const name = process.env.NAME || 'World';
  res.send(`Hello ${name}!`);
});

app.listen(port, () => {
  console.log(`helloworld: listening on port ${port}`);
});
EOF

  • 重點說明:
  • Cloud Run 容器必須在由容器執行階段注入的 PORT 環境變數上監聽 HTTP 請求(預設值為 8080)。

Task 3. 建立 Artifact Registry 存放庫

建立專門存放 Docker 容器映像檔的 Repository,並配置本機認證輔助工具。

# 1. 建立格式為 Docker 的儲存庫
gcloud artifacts repositories create my-repository \
  --repository-format=docker \
  --location=$LOCATION \
  --description="Docker repository"

# 2. 為該區域的 Registry 網域設定 Docker 授權憑證輔助程式
gcloud auth configure-docker $LOCATION-docker.pkg.dev --quiet

  • 參數說明:
  • --repository-format=docker:指定倉庫類型為 Docker / OCI 容器標準。
  • configure-docker:註冊認證小幫手,使本機 Docker CLI 具備推拉該區域映像檔的 Google 憑證。

Task 4. 容器化 (Docker) 並使用 Cloud Build 建置

撰寫標準的多階段/精簡 Dockerfile,並使用 gcloud builds submit 將原始碼打包至雲端建置並推送。

# 1. 建立 Dockerfile 容器建置腳本
cat << 'EOF' > Dockerfile
FROM node:22-slim
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . ./
CMD [ "npm", "start" ]
EOF

# 2. 將當前目錄原始碼打包送交 Cloud Build 建置,並自動 Push 到 Artifact Registry
gcloud builds submit --tag $LOCATION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/my-repository/helloworld

  • Dockerfile 最佳實踐解析:

  • FROM node:22-slim:選用精簡版 Linux 映像檔,大幅縮小容器體積與攻擊面。

  • COPY package*.json ./ 接 RUN npm install:善用 Docker 映像檔分層快取機制(Layer Caching)。當業務原始碼修改但相依套件未變動時,建置將直接複用快取。

  • 本地測試容器(選用步驟):

# 背景執行本機容器,將 Container Port 8080 對映至本機 8080
docker run -d -p 8080:8080 $LOCATION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/my-repository/helloworld

# 驗證本機回應(剛啟動需等待 1~2 秒服務初始化)
sleep 2
curl http://localhost:8080


Task 5. 部署應用程式至 Cloud Run

將 Artifact Registry 內的映像檔部署為可對外公開存取的 Cloud Run 服務。

# 1. 執行部署
gcloud run deploy helloworld \
  --image $LOCATION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/my-repository/helloworld \
  --allow-unauthenticated \
  --region=$LOCATION \
  --quiet

# 2. 獲取 Cloud Run 自動配發的 HTTPS 服務網址並驗證
SERVICE_URL=$(gcloud run services describe helloworld --region=$LOCATION --format='value(status.url)')
echo "Service URL: $SERVICE_URL"
curl $SERVICE_URL

  • 參數說明:
  • helloworld:Cloud Run 服務名稱。
  • --image:指定要執行的完整容器映像檔路徑 ({區域}-docker.pkg.dev/{專案ID}/{儲存庫名稱}/{映像檔名稱})。
  • --allow-unauthenticated:允許未經身份驗證的公開存取(預設會要求帶有 GCP IAM 身份 Token 才能呼叫)。
  • --format='value(status.url)':使用 gcloud 的格式過濾功能,僅擷取輸出結果中的對外 HTTPS URL。

Task 6. 資源清理 (Clean Up)

為避免持續佔用儲存空間而產生費用,實作完成後刪除產出的映像檔與 Cloud Run 服務。

# 1. 刪除 Artifact Registry 中的容器映像檔及其所有 tag 與 digest
gcloud artifacts docker images delete $LOCATION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/my-repository/helloworld --quiet

# 2. 刪除 Cloud Run 服務實例
gcloud run services delete helloworld --region=$LOCATION --quiet

  • 參數說明:
  • --quiet:停用互動式確認提示,直接執行刪除。

4. 關鍵指令速查表

目的 指令摘要
啟用服務 API gcloud services enable <API_NAME>
建立 Artifact 倉庫 gcloud artifacts repositories create <REPO> --repository-format=docker --location=<LOC>
雲端建置並推送映像檔 gcloud builds submit --tag <IMAGE_PATH>
部署 Cloud Run 服務 gcloud run deploy <SERVICE> --image <IMAGE_PATH> --allow-unauthenticated --region=<LOC>
查詢服務 URL gcloud run services describe <SERVICE> --format='value(status.url)'
刪除映像檔 gcloud artifacts docker images delete <IMAGE_PATH>
刪除 Cloud Run gcloud run services delete <SERVICE> --region=<LOC>

上一篇
GCP 實戰筆記:Cloud Storage 與 Cloud SQL 整合應用
系列文
將考國際證照的應用程式變成開源 共 77 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言