使用 GCE 在 Google Cloud 上托管 Web 应用

您可以通过多种方式在 Google Cloud 中部署网站,每种解决方案的特性、功能和控制级别各不相同。Google Compute Engine(也称为 GCE)可用于对运行网站所用的基础设施进行深层控制,但与 Google Kubernetes Engine (GKE)、Google App Engine (GAE) 等其他解决方案相比,采用 Compute Engine 还需要进行更多的运营管理工作。利用 Compute Engine,我们可以精细地全面控制基础设施,包括虚拟机、负载平衡器等。今天,我们将部署一个示例应用,即 Fancy Store 电子商务网站,演示如何使用 Compute Engine 轻松部署和扩缩网站。

学习内容

Codelab 结束时,您的托管式实例组中将会有多个实例,可为网站提供自动修复、负载均衡、自动扩缩和滚动更新功能。

前提条件

自定进度的环境设置

如果您还没有 Google 账号(Gmail 或 Google Apps),则必须创建一个。登录 Google Cloud Platform Console (console.cloud.google.com) 并创建一个新项目:

2016-02-10 12:45:26 的屏幕截图.png

请记住项目 ID,它在所有 Google Cloud 项目中都是唯一名称(很抱歉,上述名称已被占用,您无法使用!)。它稍后将在此 Codelab 中被称为 PROJECT_ID。

接下来,您需要在 Cloud Console 中启用结算功能,才能使用 Google Cloud 资源。

在此 Codelab 中运行仅花费几美元,但是如果您决定使用更多资源或继续让它们运行,费用可能更高(请参阅本文档末尾的“清理”部分)。

Google Cloud Platform 的新用户有资格获享 $300 免费试用。

启用 Compute Engine API

接下来,您需要启用 Compute Engine API。启用 API 需要您接受 API 的服务条款和结算责任。

Google Cloud Shell

虽然 Google Cloud 和 Kubernetes 可以从笔记本电脑远程操作,但在此 Codelab 中,我们将使用 Google Cloud Shell,这是一个在云端运行的命令行环境。

基于 Debian 的这个虚拟机已加载了您需要的所有开发工具。它提供了一个持久的 5 GB 主目录,并且在 Google Cloud 中运行,大大增强了网络性能和身份验证功能。这意味着在本 Codelab 中,您只需要一个浏览器(没错,它适用于 Chromebook)。

如需激活 Google Cloud Shell,只需在开发者控制台中点击右上角的按钮(预配和连接到环境仅需花费一些时间):

activateCloudShell.png

点击“启动 Cloud Shell”按钮:

Screen Shot 2017-06-14 at 10.13.43 PM.png

连接到 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,或在控制台信息中心查找该 ID:

Project_ID.png

重要提示:最后,设置默认可用区和项目配置:

gcloud config set compute/zone us-central1-f

您可以选择各种不同的可用区。如需了解详情,请参阅“区域和地区”说明文档。

创建 GCS 存储桶

我们将使用 Google Cloud Storage 存储分区来存储构建的代码以及启动脚本。在 Cloud Shell 中执行以下命令,创建新的 GCS 存储分区:

gsutil mb gs://fancy-store-$DEVSHELL_PROJECT_ID

我们将基于 monolith-to-microservices 代码库的现有 Fancy Store 电子商务网站作为我们网站的基础。我们将从 Git 代码库中克隆源代码,以便专注于将网站部署到 GCE。在本 Codelab 的后面部分,我们将对代码进行细微更新,从而验证在 GCE 上进行更新是多么简单。

点击下方按钮,将代码库克隆到项目中,并打开 Cloud Shell 和内置的代码编辑器。

在 Cloud Shell 命令提示符处,运行代码的初始 build,让应用在本地运行。此脚本可能需要几分钟才能运行完毕。

./setup.sh

让我们尽职尽责地测试一下应用,运行以下命令来启动 Web 服务器:

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 停止 Web 服务器进程。

现在您已拥有可正常运行的开发者环境,接下来可以开始部署一些 Compute Engine 实例了!以下步骤将:

  1. 创建启动脚本以配置实例
  2. 克隆源代码并将其上传至 Google Cloud Storage
  3. 部署 Compute Engine 实例,用于托管后端微服务
  4. 重新配置前端代码,以利用后端微服务实例
  5. 部署 Compute Engine 实例,用于托管前端微服务
  6. 配置网络以允许通信

创建启动脚本

为了让实例自动配置为我们想要的方式,我们将使用一个启动脚本,该脚本会告知实例每次启动时要执行哪些操作。在 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 将应用作为守护程序运行。
  • 从 GCS 存储分区克隆应用的源代码并安装依赖项。
  • 将 Supervisor 配置为运行该应用。如果应用意外退出或者被管理员或进程停止,Supervisor 将确保应用重启。此外,它还会将应用的 stdout 和 stderr 发送到 syslog,以便 Logging 代理进行收集。

现在,将创建的 startup-script.sh 文件复制到我们之前创建的 GCS 存储分区中:

gsutil cp startup-script.sh gs://fancy-store-$DEVSHELL_PROJECT_ID

现在可通过以下网址访问此文件:https://storage.googleapis.com/[BUCKET_NAME]/startup-script.sh。[BUCKET_NAME] 代表 Cloud Storage 存储分区的名称。默认情况下,只有获得授权的用户和服务账号才能查看此文件,因此无法通过网络浏览器访问它。Google Compute Engine 实例能够自动通过其服务账号访问此文件。

将代码复制到 GCS 存储分区

实例启动后,会从 GCS 存储分区中拉取代码,因此我们可以在代码的“.env”文件中存储一些配置变量。

将克隆的代码复制到 GCS 存储分区:

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 实例,并将其标记为“后端”实例,以便我们稍后可以对其应用特定的防火墙规则:

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 存储分区:

cd ~
rm -rf monolith-to-microservices/*/node_modules
gsutil -m cp -r monolith-to-microservices gs://fancy-store-$DEVSHELL_PROJECT_ID/

部署前端实例

代码已配置完毕,现在来部署前端实例。执行以下命令来部署前端实例,此命令与前面的命令类似,但此实例已标记为“前端”,以用于防火墙用途。

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=frontend
gcloud 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] 是之前确定的外部 IP。该实例可能需要几分钟才能启动并完成配置。

尝试前往“商品”和“订单”页面,这些页面也应该可以正常工作。

为了让应用能够扩缩,需要创建托管式实例组,并将 frontend 和 backend 实例用作实例模板。

托管式实例组 (MIG) 包含多个相同实例,可将这些实例作为单个可用区内的单个实体进行管理。托管式实例组会主动让实例保持可用(即处于“正在运行”状态),以维持应用的高可用性。我们将为前端和后端实例使用托管式实例组,以提供自动修复、负载均衡、自动扩缩和滚动更新功能。

基于源实例创建实例模板

在创建托管式实例组之前,我们必须先创建实例模板,以用作实例组的基础。通过实例模板,您可以定义在创建新虚拟机实例时要使用的机器类型、启动磁盘映像或容器映像、网络和其他实例属性。您可以使用实例模板创建属于托管式实例组的实例,甚至是创建单独的实例。

若要创建实例模板,我们将使用之前创建的现有实例。首先,我们必须停止运行两个实例:

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-a
gcloud 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-fe
gcloud compute instance-groups managed create fancy-be-mig \
    --base-instance-name fancy-be \
    --size 2 \
    --template fancy-be

对于我们的应用,前端微服务在端口 8090 上运行,后端微服务在端口 8091(用于订单)和端口 8092(用于商品)上运行。这些是非标准端口,因此我们将指定已命名端口来标识它们。已命名端口是键值对元数据,代表服务名称以及运行服务的端口。可以将已命名端口分配给实例组,这表示该实例组中的所有实例都可以使用该服务。HTTP 负载均衡服务会使用这些信息,我们将在后面进行配置。

gcloud compute instance-groups set-named-ports fancy-fe-mig \ 
    --named-ports frontend:8090
gcloud compute instance-groups set-named-ports fancy-be-mig \
    --named-ports orders:8091,products:8092

配置自动修复

若要提高应用本身的可用性,验证应用能否正常响应,可以为托管式实例组配置自动修复政策。

自动修复政策依赖于基于应用的健康检查来验证应用能否按预期响应。默认行为是仅验证实例是否处于正在运行状态,相比之下,检查应用能否正常响应可以获得更加精准的结果。

创建如下健康检查:如果检查连续 3 次针对前端和后端返回“unhealthy”(健康状况不佳),则应修复实例:

gcloud compute health-checks create http fancy-fe-hc \
    --port 8090 \
    --check-interval 30s \
    --healthy-threshold 1 \
    --timeout 10s \
    --unhealthy-threshold 3
gcloud 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 300
gcloud 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

然后,对其中一个实例使用安全外壳 (SSH),其中 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 负载均衡器的结构如下:

  1. 转发规则将传入的请求定向到目标 HTTP 代理。
  2. 目标 HTTP 代理根据网址映射检查每个请求,为请求确定适当的后端服务。
  3. 后端服务根据关联后端的服务能力、可用区和实例健康状况,将每个请求定向到适当的后端。系统会通过 HTTP 健康检查来验证每个后端实例的健康状况。如果将后端服务配置为使用 HTTPS 或 HTTP/2 健康检查,系统会在将请求发送到后端实例的过程中会对其进行加密。
  4. 负载均衡器与实例之间的会话可以使用 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"

创建要与所创建的网址映射关联的代理。

gcloud compute target-http-proxies create fancy-proxy \
  --url-map fancy-map

创建一条全局转发规则,将公共 IP 地址和端口与该代理关联起来。

gcloud compute forwarding-rules create fancy-http-rule \
  --global \
  --target-http-proxy fancy-proxy \
  --ports 80

更新配置

现在我们有了新的静态 IP 地址,需要更新前端的代码,以指向这个新地址,不要使用先前指向 后端实例的临时地址。

在 Cloud Shell 中,切换到 react-app 文件夹,该文件夹中的“.env”文件内包含相关配置:

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 存储分区:

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 会将响应存储在 Cloud CDN 缓存中,这样便可使用缓存为后续请求查找响应。

更新实例模板

现有的实例模板不可修改;不过,由于我们的实例是无状态的,而且所有配置都是通过启动脚本完成的,因此,如果我们想更改核心映像本身,才真正需要更改实例模板。为了演示此流程,我们将进行简单的更改并推送该更改。

在本部分中,我们将更新 frontend 实例,该实例是实例模板的基础。在更新期间,我们会在更新版实例模板映像中添加一个文件,接着更新实例模板,部署新模板,然后确认托管式实例组的实例中是否存在该文件。

启动前端实例(如果尚未运行):

gcloud compute instances start frontend

通过安全 shell 登录实例:

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 &amp; 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 存储分区:

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、托管式实例组、负载均衡器和健康检查的使用经验!