有許多方法可以在 Google Cloud 中部署網站,每種解決方案都提供不同的功能、能力和控管程度。Google Compute Engine (簡稱 GCE) 可深入控管用於執行網站的基礎架構,但與 Google Kubernetes Engines (GKE)、Google App Engine (GAE) 和其他解決方案相比,需要進行較多的營運管理作業。只要使用 Compute Engine,即可精細控管基礎架構的內容,包括虛擬機器及負載平衡器等。今天我們將部署範例應用程式 (Fancy Store 電子商務網站),說明如何使用 Compute Engine 輕鬆部署網站及調度資源。
課程內容
- 如何建立 Compute Engine 執行個體
- 如何從來源執行個體建立執行個體範本
- 如何建立代管執行個體群組
- 如何建立及測試代管執行個體群組健康狀態檢查
- 如何建立 HTTP(S) 負載平衡器
- 如何建立負載平衡器健康檢查
- 如何使用內容傳遞網路 (CDN) 進行快取作業
完成本程式碼研究室的各項操作後,您將擁有位於代管執行個體群組中的執行個體,可為您的網站提供自動修復、負載平衡、自動調度資源及滾動式更新功能。
必要條件
- 如要初步瞭解本實驗室中使用的概念,請參閱下列資料:
- 歡迎使用 Google Cloud Platform - GCP 基礎知識
- 開始使用 Google Cloud Compute Engine
- Google Cloud Storage 入門指南
- 開始使用:Cloud Shell
自行設定環境
如果您還沒有 Google 帳戶 (Gmail 或 Google 應用程式),請先建立帳戶。登入 Google Cloud Platform 主控台 (console.cloud.google.com),然後建立新專案:
請記住專案 ID,這是所有 Google Cloud 專案中不重複的名稱 (上述名稱已遭占用,因此不適用於您,抱歉!)。本程式碼研究室稍後會將其稱為 PROJECT_ID。
接著,您必須在 Cloud 控制台中啟用帳單,才能使用 Google Cloud 資源。
完成本程式碼研究室的費用不應超過數美元,但如果您決定使用更多資源,或是將資源繼續執行 (請參閱本文件結尾的「清除」一節),則可能會增加費用。
Google Cloud Platform 新使用者享有價值 $300 美元的免費試用期。
啟用 Compute Engine API
接著,您需要啟用 Compute Engine API。啟用 API 時,您必須接受服務條款,並承擔 API 的帳單責任。
Google Cloud Shell
雖然您可以透過筆電遠端操作 Google Cloud 和 Kubernetes,但在本程式碼研究室中,我們將使用 Google Cloud Shell,也就是在雲端執行的指令列環境。
這種以 Debian 為基礎的虛擬機器,搭載各種您需要的開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,可大幅提升網路效能和驗證。也就是說,您只需要瀏覽器 (Chromebook 也可以) 就能完成本程式碼研究室。
如要啟用 Google Cloud Shell,只要在開發人員控制台中按一下右上方的按鈕即可 (系統應該只需要幾分鐘就能佈建及連線至環境):
按一下「Start Cloud Shell」(啟動 Cloud Shell) 按鈕:
連線至 Cloud Shell 後,您應會發現自己通過驗證,且專案已設為您的 PROJECT_ID:
gcloud auth list
指令輸出
Credentialed accounts: - <myaccount>@<mydomain>.com (active)
gcloud config list project
指令輸出
[core] project = <PROJECT_ID>
Cloud Shell 也會預設設定一些環境變數,這些變數在您執行後續指令時可能很有用。
echo $GOOGLE_CLOUD_PROJECT
指令輸出
<PROJECT_ID>
如果專案未設定,請發出下列指令:
gcloud config set project <PROJECT_ID>
要尋找 PROJECT_ID 嗎?請檢查您在設定步驟中使用的 ID,或在控制台資訊主頁中查詢:
重要事項:最後,請設定預設可用區和專案:
gcloud config set compute/zone us-central1-f
您可以選擇各種不同區域。詳情請參閱區域和可用區說明文件。
可建立 GCS 值區
我們將使用 Google Cloud Storage bucket 來儲存建構的程式碼及開機指令碼。在 Cloud Shell 執行下列指令,建立新的 GCS bucket:
gsutil mb gs://fancy-store-$DEVSHELL_PROJECT_ID
我們將使用 monolith-to-microservices 存放區的現有 Fancy Store 電子商務網站,做為網站基礎。我們會從 git 存放區複製原始碼,以便專心將應用程式部署至 GCE。在本程式碼研究室的後續章節,我們將稍微修改一下程式碼,看看在 GCE 更新內容有多簡單。
按一下下方按鈕,將程式碼存放區複製到專案,並開啟 Cloud Shell 和內建的程式碼編輯器。

在 Cloud Shell 命令提示字元中,執行程式碼的初始版本,讓應用程式可在本機執行。這項指令碼可能需要幾分鐘的時間才能執行完畢。
./setup.sh
讓我們盡責地測試應用程式,執行下列指令來啟動網路伺服器:
cd microservices npm start
輸出:
Products microservice listening on port 8092! Frontend microservice listening on port 8090! Orders microservice listening on port 8091!
如要預覽應用程式,請按一下網頁預覽圖示,然後選取「變更通訊埠」,並輸入前端微服務的通訊埠:8090。選取「變更並預覽」。


系統應會開啟新視窗,顯示 Fancy Store 的前端運作情形!

看完網站後請關閉視窗,接著在終端機視窗中按下 CTRL+C 鍵,停止網路伺服器程序。
現在您已擁有可正常運作的開發人員環境,該開始部署一些 Compute Engine 執行個體了!下列步驟將:
- 建立開機指令碼以設定執行個體
- 複製原始碼並上傳至 Google Cloud Storage
- 部署用於託管後端微服務的 Compute Engine 執行個體
- 重新設定前端程式碼,以便利用後端微服務執行個體
- 部署用於託管前端微服務的 Compute Engine 執行個體
- 設定網路來允許通訊
建立開機指令碼
為了讓執行個體自動設定為我們想要的方式,我們會使用開機指令碼,在每次啟動時指示執行個體應採取何種行動,在 Cloud Shell 的程式碼編輯器中,前往「monolith-to-microservices」資料夾,然後建立名為「startup-script.sh」的檔案。

在這個新檔案中,貼上下列程式碼。貼上後,請修改部分程式碼。
#!/bin/bash
# Install logging monitor. The monitor will automatically pick up logs sent to
# syslog.
curl -s "https://storage.googleapis.com/signals-agents/logging/google-fluentd-install.sh" | bash
service google-fluentd restart &
# Install dependencies from apt
apt-get update
apt-get install -yq ca-certificates git build-essential supervisor psmisc
# Install nodejs
mkdir /opt/nodejs
curl https://nodejs.org/dist/v8.12.0/node-v8.12.0-linux-x64.tar.gz | tar xvzf - -C /opt/nodejs --strip-components=1
ln -s /opt/nodejs/bin/node /usr/bin/node
ln -s /opt/nodejs/bin/npm /usr/bin/npm
# Get the application source code from the Google Cloud Storage bucket.
mkdir /fancy-store
gsutil -m cp -r gs://fancy-store-[DEVSHELL_PROJECT_ID]/monolith-to-microservices/microservices/* /fancy-store/
# Install app dependencies.
cd /fancy-store/
npm install
# Create a nodeapp user. The application will run as this user.
useradd -m -d /home/nodeapp nodeapp
chown -R nodeapp:nodeapp /opt/app
# Configure supervisor to run the node app.
cat >/etc/supervisor/conf.d/node-app.conf << EOF
[program:nodeapp]
directory=/fancy-store
command=npm start
autostart=true
autorestart=true
user=nodeapp
environment=HOME="/home/nodeapp",USER="nodeapp",NODE_ENV="production"
stdout_logfile=syslog
stderr_logfile=syslog
EOF
supervisorctl reread
supervisorctl update現在,請在編輯器中找出 [DEVSHELL_PROJECT_ID],然後將這個部分改為下列指令的輸出內容:
echo $DEVSHELL_PROJECT_ID
輸出內容範例:
my-gce-codelab-253520
此時 startup-script.sh 中的程式碼應類似下列內容:
gs://fancy-store-my-gce-codelab-253520/monolith-to-microservices/microservices/* /fancy-store/開機指令碼會執行下列工作:
- 安裝 Logging 代理程式。代理程式會自動收集 Syslog 記錄。
- 安裝 Node.js 與 Supervisor。Supervisor 會將應用程式以 Daemon 形式執行。
- 從 GCS Bucket 複製應用程式的原始碼,並安裝依附元件。
- 設定 Supervisor 以執行應用程式。如果應用程式非正常結束,或遭系統管理員或處理程序終止,Supervisor 會重新啟動應用程式。Supervisor 也會傳送應用程式的 stdout 和 stderr 至 syslog,再由 Logging 代理程式收集這些資料。
現在,將建立的 startup-script.sh 檔案複製到先前建立的 GCS bucket:
gsutil cp startup-script.sh gs://fancy-store-$DEVSHELL_PROJECT_ID
該檔案目前可透過下列網址取得:https://storage.googleapis.com/[BUCKET_NAME]/startup-script.sh。[BUCKET_NAME] 代表 Cloud Storage bucket 的名稱。這項資訊預設為只有獲得授權的使用者和服務帳戶能查看,因此無法透過網路瀏覽器存取。Google Compute Engine 執行個體會自動透過服務帳戶存取這個名稱。
將程式碼複製到 GCS bucket
執行個體啟動後,會從 GCS bucket 提取程式碼,因此我們可以在程式碼的「.env」檔案中儲存一些設定變數。
將複製的程式碼複製到 GCS bucket:
cd ~ rm -rf monolith-to-microservices/*/node_modules gsutil -m cp -r monolith-to-microservices gs://fancy-store-$DEVSHELL_PROJECT_ID/
部署後端執行個體
首先要部署的是後端執行個體,用於儲存「Orders」和「Products」微服務。
在 Cloud Shell 中執行下列指令,建立設為使用先前建立的開機指令碼的 f1-micro 執行個體,並將其標為「backend」執行個體,以便稍後為這個執行個體套用特定防火牆規則:
gcloud compute instances create backend \
--machine-type=f1-micro \
--image=debian-9-stretch-v20190905 \
--image-project=debian-cloud \
--tags=backend \
--metadata=startup-script-url=https://storage.googleapis.com/fancy-store-$DEVSHELL_PROJECT_ID/startup-script.sh設定與後端的連線
部署應用程式前端之前,我們需要先更新設定,指向您剛才部署的後端。
擷取後端的外部 IP 位址,這項資訊可透過下列指令查看後端執行個體的 EXTERNAL_IP 分頁:
gcloud compute instances list
輸出內容範例:
NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS backend us-central1-a f1-micro 10.128.0.2 34.68.223.88 RUNNING
返回 Cloud Shell 的程式碼編輯器,然後前往 monolith-to-microservices → react-app 資料夾。從程式碼編輯器選單中,選取「View」→「Toggle Hidden Files」,即可查看「.env」檔案。

編輯「.env」檔案,指向後端的外部 IP。下方的 [BACKEND_ADDRESS] 代表後端執行個體的外部 IP 位址 (執行前述的 gcloud 指令後即可判斷)。
REACT_APP_ORDERS_URL=http://[BACKEND_ADDRESS]:8091/api/orders
REACT_APP_PRODUCTS_URL=http://[BACKEND_ADDRESS]:8092/api/products重新建構 react-app,更新前端程式碼:
npm install && npm run-script build
將應用程式程式碼複製回 GCS bucket:
cd ~ rm -rf monolith-to-microservices/*/node_modules gsutil -m cp -r monolith-to-microservices gs://fancy-store-$DEVSHELL_PROJECT_ID/
部署前端執行個體
程式碼設定完畢後,我們就可以部署前端執行個體。執行下列指令,透過與先前類似的指令來部署前端執行個體,但基於防火牆用途,此執行個體會標記為「frontend」。
gcloud compute instances create frontend \
--machine-type=f1-micro \
--image=debian-9-stretch-v20190905 \
--image-project=debian-cloud \
--tags=frontend \
--metadata=startup-script-url=https://storage.googleapis.com/fancy-store-$DEVSHELL_PROJECT_ID/startup-script.sh 設定網路
建立防火牆規則,允許前端存取通訊埠 8090,而允許後端存取 8091 至 8092 通訊埠。這些防火牆指令會使用為應用程式建立執行個體時所指派的標記。
gcloud compute firewall-rules create fw-fe \
--allow tcp:8090 \
--target-tags=frontendgcloud compute firewall-rules create fw-be \
--allow tcp:8091-8092 \
--target-tags=backend現在網站應該可以正常運作。前往前端的外部 IP。如要判斷這個位址,請找出前端執行個體的 EXTERNAL_IP:
gcloud compute instances list
輸出內容範例:
NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS backend us-central1-a f1-micro 10.128.0.2 104.198.235.171 RUNNING frontend us-central1-a f1-micro 10.128.0.3 34.69.141.9 RUNNING
前往 http://[FRONTEND_ADDRESS]:8090 存取網站,其中的 [FRONTEND_ADDRESS] 是前述步驟中輸出的 EXTERNAL_IP。執行個體會在幾分鐘內啟動及設定完成。
試著前往「Products」和「Orders」頁面,現在網頁應該也會正常運作。
如要允許應用程式調度資源,需建立代管執行個體群組,並使用 frontend 和 backend 執行個體做為執行個體範本。
代管執行個體群組 (MIG) 包含相同的執行個體,可做為單一可用區中的單一實體來管理。這類群組會主動讓執行個體保持可用狀態 (即處於 RUNNING 狀態),以維持應用程式的高可用性。我們會對前端和後端執行個體使用代管執行個體群組,以便提供自動修復、負載平衡、自動調度資源和滾動式更新功能。
根據來源執行個體建立執行個體範本
建立代管執行個體群組前,必須先建立執行個體範本,用來做為群組的基礎。執行個體範本可用於定義建立新 VM 執行個體時要使用的機型、開機磁碟映像檔或容器映像檔、網路,以及其他執行個體屬性。您可以利用執行個體範本建立代管執行個體群組中的執行個體,甚至建立個別的執行個體。
如要建立執行個體範本,請使用先前建立的現有執行個體。首先,我們必須停止前端和後端執行個體:
gcloud compute instances stop frontend
gcloud compute instances stop backend
接著,根據來源執行個體建立執行個體範本:
gcloud compute instance-templates create fancy-fe \
--source-instance=frontend \
--source-instance-zone=us-central1-agcloud compute instance-templates create fancy-be \
--source-instance=backend \
--source-instance-zone=us-central1-a確認執行個體範本已建立完畢:
gcloud compute instance-templates list
輸出內容範例:
NAME MACHINE_TYPE PREEMPTIBLE CREATION_TIMESTAMP fancy-be f1-micro 2019-09-12T07:52:57.544-07:00 fancy-fe f1-micro 2019-09-12T07:52:48.238-07:00
建立代管執行個體群組
我們會建立兩個代管執行個體群組,分別用於前端和後端。這些代管執行個體群組會使用先前建立的執行個體範本,並設為每個群組中有兩個要啟動的執行個體。執行個體的名稱會由「base-instance-name」指定,並附上隨機字串。
gcloud compute instance-groups managed create fancy-fe-mig \
--base-instance-name fancy-fe \
--size 2 \
--template fancy-fegcloud compute instance-groups managed create fancy-be-mig \
--base-instance-name fancy-be \
--size 2 \
--template fancy-be在我們的應用程式中,前端微服務會在通訊埠 8090 上執行,後端微服務則是在通訊埠 8091 上執行,通訊埠 8091 用於 orders,通訊埠 8092 則用於 products。這些是非標準通訊埠,因此請指定具名通訊埠來加以識別。已命名通訊埠為鍵/值組合中繼資料,代表服務名稱和執行中的通訊埠。您可以將已命名通訊埠指派給執行個體群組,表示群組中的所有執行個體皆可使用該服務。HTTP 負載平衡服務會使用這項資訊,我們將在後續章節設定。
gcloud compute instance-groups set-named-ports fancy-fe-mig \
--named-ports frontend:8090gcloud compute instance-groups set-named-ports fancy-be-mig \
--named-ports orders:8091,products:8092設定自動修復功能
如要提高應用程式自身的可用性,以及驗證應用程式是否有回應,您可以為代管執行個體群組設定自動修復政策。
自動修復政策會利用以應用程式為基礎的健康狀態檢查機制,確認應用程式的回應是否正常。系統的預設行為只會確認執行個體是否處於「執行中」狀態,相比之下,檢查應用程式是否有回應的做法更為精確。
建立健康狀態檢查,在前端和後端執行個體連續三次傳回健康狀態不良時,修復執行個體:
gcloud compute health-checks create http fancy-fe-hc \
--port 8090 \
--check-interval 30s \
--healthy-threshold 1 \
--timeout 10s \
--unhealthy-threshold 3gcloud compute health-checks create http fancy-be-hc \
--port 8091 \
--request-path=/api/orders \
--check-interval 30s \
--healthy-threshold 1 \
--timeout 10s \
--unhealthy-threshold 3建立防火牆規則,允許健康狀態檢查探測器連線至通訊埠 8090 至 8091 上的微服務:
gcloud compute firewall-rules create allow-health-check \
--allow tcp:8090-8091 \
--source-ranges 130.211.0.0/22,35.191.0.0/16 \
--network default將健康狀態檢查套用至對應的服務:
gcloud compute instance-groups managed update fancy-fe-mig \
--health-check fancy-fe-hc \
--initial-delay 300gcloud compute instance-groups managed update fancy-be-mig \
--health-check fancy-be-hc \
--initial-delay 300模擬失敗
為了確認健康狀態檢查是否正常運作,請登入執行個體並停止服務。如要找出執行個體名稱,請執行下列指令:
gcloud compute instance-groups list-instances fancy-fe-mig
接著透過安全殼層連線至其中一個執行個體,INSTANCE_NAME 代表清單中的其中一個執行個體:
gcloud compute ssh [INSTANCE_NAME]
在執行個體中,使用 supervisorctl 停止應用程式:
sudo supervisorctl stop nodeapp; sudo killall node
結束執行個體:
exit
監控修復作業:
watch -n 5 gcloud compute operations list \ --filter='operationType~compute.instances.repair.*'
輸出內容應如下列範例所示。
NAME TYPE TARGET HTTP_STATUS STATUS TIMESTAMP repair-1568314034627-5925f90ee238d-fe645bf0-7becce15 compute.instances.repair.recreateInstance us-central1-a/instances/fancy-fe-1vqq 200 DONE 2019-09-12T11:47:14.627-07:00
發現修復作業後,請按 Ctrl+C 結束觀察指令。此時,代管執行個體群組會重新建立執行個體並修復。
為輔助代管執行個體群組,我們將使用 HTTP(S) 負載平衡器將流量提供給前端和後端微服務,並使用對應功能,將流量傳送給符合路徑規則的合適後端服務。這樣所有服務都會使用同一個負載平衡 IP。
https://cloud.google.com/load-balancing/docs/load-balancing-overview.
建立 HTTP(S) 負載平衡器
Google Cloud Platform 提供多種類型的負載平衡器,但我們將使用 HTTP(S) 負載平衡器來處理流量。HTTP 負載平衡器的結構如下:
- 轉送規則將傳入要求導向至目標 HTTP Proxy。
- 目標 HTTP Proxy 會根據網址對應檢查每個要求,以決定適合要求的後端服務。
- 後端服務會根據已連接後端的服務規模、可用區和執行個體健康狀態,將每個要求導向合適的後端。系統會使用 HTTP 健康狀態檢查,驗證每個後端執行個體的健康狀態。如果將後端服務設定為使用 HTTPS 或 HTTP/2 健康狀態檢查,則要求會在前往後端執行個體的途中加密。
- 負載平衡器和執行個體之間的工作階段可以使用 HTTP、HTTPS 或 HTTP/2 通訊協定。如果您使用 HTTPS 或 HTTP/2,後端服務中的每個執行個體都必須具備 SSL 憑證。
建立健康狀態檢查,用於決定要使用哪個執行個體為各服務提供流量。
gcloud compute http-health-checks create fancy-fe-frontend-hc \ --request-path / \ --port 8090
gcloud compute http-health-checks create fancy-be-orders-hc \ --request-path /api/orders \ --port 8091
gcloud compute http-health-checks create fancy-be-products-hc \ --request-path /api/products \ --port 8092
建立後端服務,做為負載平衡流量的目標。這個後端服務會使用我們建立的健康檢查和已命名通訊埠。
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
新增後端服務:
gcloud compute backend-services add-backend fancy-fe-frontend \ --instance-group fancy-fe-mig \ --instance-group-zone us-central1-a \ --global
gcloud compute backend-services add-backend fancy-be-orders \ --instance-group fancy-be-mig \ --instance-group-zone us-central1-a \ --global
gcloud compute backend-services add-backend fancy-be-products \ --instance-group fancy-be-mig \ --instance-group-zone us-central1-a \ --global
建立網址對應。網址對應定義了應將哪些網址導向至哪些後端服務。
gcloud compute url-maps create fancy-map \ --default-service fancy-fe-frontend
建立路徑比對器,允許「/api/orders」和「/api/products」路徑轉送個別服務:
gcloud compute url-maps add-path-matcher fancy-map \ --default-service fancy-fe-frontend \ --path-matcher-name orders \ --path-rules "/api/orders=fancy-be-orders,/api/products=fancy-be-products"
建立要與所建網址對應繫結的 Proxy。
gcloud compute target-http-proxies create fancy-proxy \ --url-map fancy-map
建立全域轉送規則,將公開 IP 位址及通訊埠與 Proxy 繫結在一起。
gcloud compute forwarding-rules create fancy-http-rule \ --global \ --target-http-proxy fancy-proxy \ --ports 80
更新設定
現在我們有新的靜態 IP 位址,需要更新前端的程式碼,指向這個新位址,不要使用先前指向 backend 執行個體的臨時 IP 位址。
在 Cloud Shell 中,切換到儲存「.env」檔案的 react-app 資料夾,該檔案內含相關設定:
cd ~/monolith-to-microservices/react-app/
找出負載平衡器的 IP 位址:
gcloud compute forwarding-rules list --global
輸出內容範例:
NAME REGION IP_ADDRESS IP_PROTOCOL TARGET fancy-http-rule 34.102.237.51 TCP fancy-proxy
使用您慣用的文字編輯器 (例如 nano) 編輯 .env,指向負載平衡器的公開 IP。[LB_IP] 代表之前決定的後端執行個體外部 IP 位址。
REACT_APP_ORDERS_URL=http://[LB_IP]/api/orders
REACT_APP_PRODUCTS_URL=http://[LB_IP]/api/products重新建構 react-app,更新前端程式碼:
npm install && npm run-script build
將應用程式程式碼複製回 GCS bucket:
cd ~ rm -rf monolith-to-microservices/*/node_modules gsutil -m cp -r monolith-to-microservices gs://fancy-store-$DEVSHELL_PROJECT_ID/
更新前端執行個體
現在有了新程式碼及設定,我們希望代管執行個體群組中的前端執行個體提取這段新程式碼。執行個體會在啟動時提取程式碼,因此我們可以發出滾動式重新啟動指令:
gcloud compute instance-groups managed rolling-action restart fancy-fe-mig \
--max-unavailable 100%測試網站
等執行個體出現在清單中後,再檢查代管執行個體群組的狀態:
watch -n 5 gcloud compute instance-groups list-instances fancy-fe-mig
待執行個體出現在清單後,按下 Ctrl+C 鍵,結束 watch 指令。
確認服務顯示的狀態為良好:
gcloud compute backend-services get-health fancy-fe-frontend --global
輸出內容範例:
---
backend: https://www.googleapis.com/compute/v1/projects/my-gce-codelab/zones/us-central1-a/instanceGroups/fancy-fe-mig
status:
healthStatus:
- healthState: HEALTHY
instance: https://www.googleapis.com/compute/v1/projects/my-gce-codelab/zones/us-central1-a/instances/fancy-fe-x151
ipAddress: 10.128.0.7
port: 8090
- healthState: HEALTHY
instance: https://www.googleapis.com/compute/v1/projects/my-gce-codelab/zones/us-central1-a/instances/fancy-fe-cgrt
ipAddress: 10.128.0.11
port: 8090
kind: compute#backendServiceGroupHealth
應用程式將可透過 http://[LB_IP] 存取,[LB_IP] 是系統為負載平衡器指定的 IP_ADDRESS,您可使用下列指令找出該位址:
gcloud compute forwarding-rules list --global
目前我們已建立兩個代管執行個體群組,且每個群組皆含有兩個執行個體。這項配置可以正常運作,但無論負載狀況如何,都不會變動。接下來,我們要根據使用率建立自動調度資源政策,讓每個代管執行個體群組自動調整資源配置。
根據使用率自動調整大小
如要建立自動調度資源政策,請在 Cloud Shell 中執行下列指令。這些指令會在代管執行個體群組建立自動調度器。這項工具會在使用率高於 60% 時,自動新增執行個體,如果負載平衡器的使用率低於 60%,則會移除執行個體。
gcloud compute instance-groups managed set-autoscaling \ fancy-fe-mig \ --max-num-replicas 5 \ --target-load-balancing-utilization 0.60
gcloud compute instance-groups managed set-autoscaling \ fancy-be-mig \ --max-num-replicas 5 \ --target-load-balancing-utilization 0.60
啟用內容傳遞網路
內容傳遞網路服務也有助於資源調度,啟用 Cloud CDN 後即可為前端提供快取。如要這麼做,我們可以在前端服務上執行下列指令:
gcloud compute backend-services update fancy-fe-frontend \
--enable-cdn --global當使用者向 HTTP(S) 負載平衡器要求內容,系統會將要求傳送到 Google Front End (GFE)。GFE 首先會在 Cloud CDN 快取中尋找使用者要求的回應。如果 GFE 找到快取的回應,就會將其傳送給使用者。這便稱為快取命中。
假如 GFE 找不到要求的快取回應,GFE 會向後端直接提出要求。如果此要求的回應可快取,GFE 會將回應儲存在 Cloud CDN 快取中,以便將快取用於後續要求。
更新執行個體範本
現有的執行個體範本無法編輯,不過,由於我們的執行個體為無狀態,且已透過開機指令碼完成所有設定,若我們想要變更核心映像檔本身,只需要變更執行個體範本即可。為了示範這個程序,我們要稍做調整,然後將這項變更推送出去。
在本節中,我們將更新 frontend 執行個體,做為執行個體範本的基礎。更新時,我們會將檔案儲存在更新版執行個體範本映像檔,接著更新執行個體範本、推出新的範本,然後確認代管執行個體群組的執行個體中確實有該檔案。
啟動 frontend 執行個體 (如果尚未啟動):
gcloud compute instances start frontend
透過安全殼層連線至執行個體:
gcloud compute ssh frontend
在執行個體中,建立檔案來證明已更新:
echo "Updated" > ~/updated_proof
結束執行個體:
exit
關閉執行個體:
gcloud compute instances stop frontend
建立新的執行個體範本:
gcloud compute instance-templates create fancy-fe-new \
--source-instance=frontend \
--source-instance-zone=us-central1-a將更新後的執行個體範本推出至代管執行個體群組:
gcloud compute instance-groups managed rolling-action start-update fancy-fe-mig \
--version template=fancy-fe-new監控更新狀態:
gcloud compute instance-groups managed list-instances fancy-fe-mig
執行個體狀態為 RUNNING,且 INSTANCE_TEMPLATE 設為 fancy-fe-new 後,請登入新建立的執行個體,並檢查是否有「updated_proof」檔案,其中 [VM_NAME] 是新建立的執行個體:
gcloud compute ssh [VM_NAME]
如果代管群組執行個體現在有「updated_proof」檔案,表示更新已成功推送。
變更網站
您的行銷團隊想請您變更網站首頁,希望其中包含更多公司簡介與銷售產品等資訊。在本節中,我們會在首頁加入一些文字,讓行銷團隊高興一下!看來有某位開發人員已經進行變更了,檔案名稱為 index.js.new。我們可以將這個檔案複製到 index.js,系統應該會反映變更。按照下方說明操作,進行適當變更。
執行下列指令,將更新後的檔案複製到正確的檔案名稱,然後顯示檔案內容來確認變更情形:
cd ~/monolith-to-microservices/react-app/src/pages/Home mv index.js.new index.js cat ~/monolith-to-microservices/react-app/src/pages/Home/index.js
顯示的程式碼應如下所示:
/*
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
paper: {
width: "800px",
margin: "0 auto",
padding: theme.spacing(3, 2)
}
}));
export default function Home() {
const classes = useStyles();
return (
<div className={classes.root}>
<Paper className={classes.paper}>
<Typography variant="h5">
Fancy Fashion & Style Online
</Typography>
<br />
<Typography variant="body1">
Tired of mainstream fashion ideas, popular trends and societal norms?
This line of lifestyle products will help you catch up with the Fancy trend and express your personal style.
Start shopping Fancy items now!
</Typography>
</Paper>
</div>
);
}您已更新 React 元件,但還得建構 React 應用程式,才能產生靜態檔案。執行下列指令即可建構 React 應用程式,並將其複製到單體公開目錄:
cd ~/monolith-to-microservices/react-app npm install && npm run-script build
接著,重新將此程式碼推送至 GCS bucket:
cd ~ rm -rf monolith-to-microservices/*/node_modules gsutil -m cp -r monolith-to-microservices gs://fancy-store-$DEVSHELL_PROJECT_ID/
透過滾動式更新推送變更
接下來,強制重新啟動所有執行個體,以便提取更新內容:
gcloud compute instance-groups managed rolling-action restart fancy-fe-mig
現在,系統會執行滾動式重新啟動,在重新啟動執行個體時保留緩衝區,確保存取作業不受影響。透過控制台監控執行個體的循環。更新期間,狀態會顯示為轉換中;完成後,代管執行個體群組會在 Compute Engine -> 執行個體群組下方顯示為就緒:

準備就緒後,如要清除所有活動,最簡單的方法就是刪除專案。刪除專案會一併刪除這個 Codelab 中建立的所有負載平衡器、執行個體、範本等,確保不會產生非預期的週期性費用。在 Cloud Shell 中執行下列指令,其中 PROJECT_ID 是完整的專案 ID,而非專案名稱。
gcloud projects delete [PROJECT_ID]
系統提示時,輸入「Y」確認刪除。
您已成功在 GCE 部署、調度資源及更新網站。現在您已具備使用 Compute Engine、代管執行個體群組、負載平衡器和健康狀態檢查的經驗!