GCP 雲端實戰攻略 開箱 GCE、Cloud Run、BigQuery、Dialogflow

me
林彥成
2021-06-29 | 5 min.
文章目錄
  1. 1. 什麼是 Google Cloud Platform (GCP)?
  2. 2. 網站服務架設的三種方法
    1. 2.1. Google Compute Engine
      1. 2.1.1. 設定監控 health-checks
    2. 2.2. Kubernetes (K8S)
    3. 2.3. Cloud Run
  3. 3. Google Assistant
    1. 3.1. Cloud Function
  4. 4. Big Query
  5. 5. Firestore Native Mode
  6. 6. FAQ:GCP 雲端架站常見問題
    1. 6.1. Q1:GCE 與 Cloud Run 該如何選擇?
    2. 6.2. Q2:使用 BigQuery 會不會產生天價帳單?
    3. 6.3. Q3:K8S 的「滾動式更新」有什麼實務優點?

什麼是 Google Cloud Platform (GCP)?

Google Cloud Platform (GCP) 是 Google 提供的雲端運算服務套件,其核心價值在於提供與 Google 內部相同的強大基礎設施。針對網站架設,GCP 提供三種高品質路徑:1. Google Compute Engine (GCE):提供高度自定義的虛擬機服務;2. Google Kubernetes Engine (GKE):業界領先的容器編排平台,支援滾動式更新與自動擴展;3. Cloud Run:基於 Knative 的 Serverless 容器服務,讓開發者只需準備 Image 即可快速上線。此外,GCP 整合了 BigQuery(分散式資料倉儲)與 Dialogflow(AI 對話引擎),讓企業能輕鬆構建具備大數據分析與智慧語音助理能力的現代化雲端應用。


本文分享 Google Cloud Study Jam 2021 的實作體驗。GCP 雖然提供圖形化介面,但其強大的 Cloud Shell 指令行工具讓配置能透過程式碼控管,大幅降低錯誤率。

一個 Cloud Shell 介面可以完成八成的事情。
GCP Cloud Shell 介面


網站服務架設的三種方法

目前在 GCP 架設網站服務主要有三種方法:

  1. Google Compute Engine: 開虛擬機 (instances),剩下導流、防火牆等都如同本機設定
  2. Kubernetes (K8S): 管理容器的工具
  3. Cloud Run: 用 Knative 來簡化 K8S 流程

Google Compute Engine

  1. 設定 region 和 zone: gcloud config set compute/zone us-central1-f
  2. 透過控制台或是下指令: 設定機台 n1-standard-1 後,手動部屬並啟動前後端程式
1
2
3
4
5
6
7
8
9
gcloud compute instances create backend \
--machine-type=n1-standard-1 \
--tags=backend \
--metadata=startup-script-url=https://storage.googleapis.com/fancy-store-$DEVSHELL_PROJECT_ID/startup-script.sh

gcloud compute instances create frontend \
--machine-type=n1-standard-1 \
--tags=frontend \
--metadata=startup-script-url=https://storage.googleapis.com/fancy-store-$DEVSHELL_PROJECT_ID/startup-script.sh
  1. 防火牆: 前端 8080 後端 8081-8082
1
2
3
4
5
6
gcloud compute firewall-rules create fw-fe \
--allow tcp:8080 \
--target-tags=frontend
gcloud compute firewall-rules create fw-be \
--allow tcp:8081-8082 \
--target-tags=backend
  1. 建立樣板,方便之後做水平擴展
1
2
3
4
gcloud compute instance-templates create fancy-fe \
--source-instance=frontend
gcloud compute instance-templates create fancy-be \
--source-instance=backend
  1. 群組管理,前端 8080 後端 8081 orders、8082 products
1
2
3
4
5
6
7
8
9
10
11
12
13
gcloud compute instance-groups managed create fancy-fe-mig \
--base-instance-name fancy-fe \
--size 2 \
--template fancy-fe
gcloud compute instance-groups managed create fancy-be-mig \
--base-instance-name fancy-be \
--size 2 \
--template fancy-be

gcloud compute instance-groups set-named-ports fancy-fe-mig \
--named-ports frontend:8080
gcloud compute instance-groups set-named-ports fancy-be-mig \
--named-ports orders:8081,products:8082

各步驟中會常用的指令:

  • 列出
    • 主機: gcloud compute instances list
    • 樣板: gcloud compute instance-templates list
  • 停機: gcloud compute instances stop frontend

設定監控 health-checks

設定監控的方式理論上各個服務都相同,就是針對 port 或是路徑去做監控,這裡就只貼上 Google Compute Engine 的案例。

  1. 設定 health-checks
1
2
3
4
5
6
7
8
9
10
11
12
13
gcloud compute health-checks create http fancy-fe-hc \
--port 8080 \
--check-interval 30s \
--healthy-threshold 1 \
--timeout 10s \
--unhealthy-threshold 3
gcloud compute health-checks create http fancy-be-hc \
--port 8081 \
--request-path=/api/orders \
--check-interval 30s \
--healthy-threshold 1 \
--timeout 10s \
--unhealthy-threshold 3
  1. 開啟 health-checks 防火牆權限
1
2
3
4
gcloud compute firewall-rules create allow-health-check \
--allow tcp:8080-8081 \
--source-ranges 130.211.0.0/22,35.191.0.0/16 \
--network default
  1. 開始監控
1
2
3
4
5
6
gcloud compute instance-groups managed update fancy-fe-mig \
--health-check fancy-fe-hc \
--initial-delay 300
gcloud compute instance-groups managed update fancy-be-mig \
--health-check fancy-be-hc \
--initial-delay 300
  1. 針對後端服務的 URL 做監控
1
2
3
4
5
6
7
8
9
gcloud compute http-health-checks create fancy-fe-frontend-hc \
--request-path / \
--port 8080
gcloud compute http-health-checks create fancy-be-orders-hc \
--request-path /api/orders \
--port 8081
gcloud compute http-health-checks create fancy-be-products-hc \
--request-path /api/products \
--port 8082
1
2
3
4
5
6
7
8
9
10
11
12
gcloud compute backend-services create fancy-fe-frontend \
--http-health-checks fancy-fe-frontend-hc \
--port-name frontend \
--global
gcloud compute backend-services create fancy-be-orders \
--http-health-checks fancy-be-orders-hc \
--port-name orders \
--global
gcloud compute backend-services create fancy-be-products \
--http-health-checks fancy-be-products-hc \
--port-name products \
--global

Kubernetes (K8S)

  1. 設定地區: gcloud config set compute/zone us-east1-b
  2. 建立 Cluster: gcloud container clusters create nucleus-webserver1
  3. gcloud container clusters get-credentials nucleus-webserver1
  4. 用 image 建立服務 kubectl create deployment hello-app --image=gcr.io/google-samples/hello-app:2.0
  5. 把 port 轉出來 kubectl expose deployment hello-app --type=LoadBalancer --port 8080

Kubernetes 中最小運算單位是 Pod,一個 Pod 可以包含多個容器共用 IP 和資源,多個 Pod 組成一個完整的 Service 方便做水平的擴充和附載平衡等等。

圖片來源: https://google.qwiklabs.com/

Pod
Kubernetes Pods 概念示意圖

Service
Kubernetes Service 概念示意圖

不同的 Services 間的非同步協作可透過第三方 Firebase 的 Pub/Sub 來取代直接叫用,會讓整個系統能夠更彈性,在升版的過程能夠因為這樣的架構達到滾動式更新的效果。

動式更新
Kubernetes 滾動式更新示意圖

各步驟中常用的指令:

  • kubectl get pods
  • kubectl get services

Cloud Run

Cloud Run 是最簡單的一種,透過 Knative 將 Kubernetes 的配置包進來,可以更簡單地把網站部屬到 Cloud Run,使用者只要先準備好 Image 就好了。

  1. 建立一個 Image gcloud builds submit --tag gcr.io/${GOOGLE_CLOUD_PROJECT}/monolith:1.0.0 .
  2. 發布容器 gcloud run deploy --image=gcr.io/${GOOGLE_CLOUD_PROJECT}/monolith:1.0.0 --platform managed

需要更新版本的話,就只要推一版新的上去就搞定
gcloud builds submit --tag gcr.io/${GOOGLE_CLOUD_PROJECT}/monolith:2.0.0 .

官方教學: https://cloud.google.com/run/docs/quickstarts/prebuilt-deploy?hl=zh-TW

Google Cloud Run 服務建置流程圖

Google Cloud Run 執行細節介面截圖

各步驟中常用的指令:

  • gcloud run services list
    • Google Cloud Run 服務列表截圖

  • gcloud run services describe monolith –platform managed
    • Google Cloud Run 服務描述截圖

Google Assistant

在基礎關卡中 GCP 也提供了 Google 助理的實作教學,過程中主要會使用 Dialogflow 來做相關的設定,其實就很像常見的狀態機聊天機器人,只是 Google 這裡可以跟其他 GCP 相關的服務整合,也提供了基本的 AI 整合。

請助理幫忙查詢資料
Google Assistant 與 Dialogflow 整合示意圖

先輸入一些使用者回應,像是各種地址格式
Google Assistant 訓練語句設定介面截圖

針對剛才的輸入設定格式
Google Assistant Dialogflow Intent 設定介面截圖

調整相關參數後 Google 就能夠自動辨識出使用者打的字是想回答什麼問題
Google Assistant Action 與參數設定介面截圖

Cloud Function

在沒有架設後端服務的情況下,可以透過撰寫 Cloud Function 來提供服務。底下是在實作 Google Assistant 時官方提供的例子,當我們收到一個 any 的歌手名稱時,會透過 YouTube 的 API 協助查詢結果並回傳。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"use strict";

const { dialogflow, Image, Suggestions } = require("actions-on-google");

const functions = require("firebase-functions");
const app = dialogflow({ debug: true });

const API_KEY = "AIzaSyDegdgDtKnYGeuhT7FBMhJXqmRbYWtFWRc";

app.intent("youtube", (conv, { any }) => {
var url =
"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q=" +
encodeURIComponent(any) +
"&type=video&order=viewCount&videoCategoryId=10&key=" +
API_KEY;
const axios = require("axios");
return axios
.get(url)
.then((response) => {
var output = JSON.stringify(response.data);
var song_fields = response.data.items[1];
return song_fields;
})
.then((output) => {
var song_title = output.snippet.title;
song_title = song_title.replace(/&/g, "&");
song_title = song_title.replace(/"/g, '"');
var song_link = JSON.stringify(output.id.videoId);
var song_thumbnail = output.snippet.thumbnails.high.url;
conv.ask(`Fetching your request...`);
conv.ask(
new Image({
url: song_thumbnail,
alt: "Song thumbnail",
})
);
conv.close(
`The most popular song is: ` +
song_title +
`. The link to this song is: https://www.youtube.com/watch?v=` +
song_link.slice(1, -1) +
`. See you next time.`
);
});
});

exports.youtube = functions.https.onRequest(app);

Big Query

使用起來的方式就是寫 SQL,但資料匯入方式就更多元,最神奇的是可以排程匯入,匯入後還可以透過 DataStudio 做視覺化。

  • csv
  • Cloud Storage
  • Google Sheet
  • Query 回來的資料

    BigQuery 資料匯入與查詢介面截圖

  • 排程定時 Query 回來的資料

    BigQuery 排程查詢設定介面截圖

在把資料匯進來之後,還可以透過 DataStudio 做相關視覺化報表,神奇的是表格還會依照自己覺得最佳的方式自動畫出來。

  1. DataStudio 資料來源選擇 Big Query

    BigQuery Data Studio 資料來源選擇介面截圖

  2. 選擇相關的資料表

    BigQuery Data Studio 添加至資料來源介面截圖

  3. 加入圖表,收工!

    BigQuery Data Studio 添加圖表至報表介面截圖

Firestore Native Mode

破關的過程中常常會需要使用 Firestore Native Mode 但按照官方教學在 Firestore 中是找不到這個設定的,最後經過我多次爬文後才發現原來新版本搬到 DataStore 中了。

Firestore Native Mode 在 DataStore 中的設定介面截圖


FAQ:GCP 雲端架站常見問題

Q1:GCE 與 Cloud Run 該如何選擇?

A:如果您需要安裝特殊的系統層級套件或長時間跑背景程式,選 GCE;如果您是開發 Web API 或 Frontend 應用,且希望「有流量才付費」,Cloud Run 是更高品質且低維運成本的首選。

Q2:使用 BigQuery 會不會產生天價帳單?

A:BigQuery 是按「掃描量」計費。若資料量極大,請務必在 SQL 中指定 WHERE 時間範圍,避免執行全表掃描。另外,善用「預覽」功能預估掃描量,是控制預算的高效習慣。

Q3:K8S 的「滾動式更新」有什麼實務優點?

A:它能讓您的網站「一邊換零件一邊跑」。K8S 會先啟動一個新版 Pod,確認健康檢查 (Health Check) 通過後,才關閉一個舊版 Pod。這樣即使新版程式有 Bug 啟動失敗,舊版仍能維持運作,實現真正的零停機部署。



喜歡這篇文章,請幫忙拍拍手喔 🤣