開始在 Compute Engine 上使用 Go

這個教學課程說明如何開始使用 Compute Engine。請按照這個教學課程中的指示,將 Hello World Go 網頁應用程式部署至 Compute Engine。如需開始使用 App Engine 的相關說明,請參閱 App Engine 標準環境

目標

  • 使用 Cloud Shell 下載及部署 Hello World 範例應用程式。
  • 使用 Cloud Build 建構 Hello World 範例應用程式。
  • 將 Hello World 範例應用程式部署至單一 Compute Engine 執行個體。

費用

在本文件中,您會使用下列 Google Cloud的計費元件:

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Compute Engine and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Compute Engine and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. 在 Google Cloud 控制台中,於 Cloud Shell 開啟應用程式。

    前往 Cloud Shell

    Cloud Shell 可讓您直接在瀏覽器中使用指令列工具存取雲端資源。

  9. 如果同意複製存放區,請按一下「確認」,下載程式碼範例並變更為應用程式目錄。

  10. 在 Cloud Shell 中,將 gcloud CLI 設為使用新的 Google Cloud 專案:
    # Configure gcloud for your project
    gcloud config set project YOUR_PROJECT_ID

在 Cloud Shell 中執行應用程式

  1. 在 Cloud Shell 中啟動本機網路伺服器:

    go build -o app
    ./app
    
  2. 按一下 Cloud Shell 中的 [Web preview] (網頁預覽),然後選取 [Preview on port 8080] (透過以下通訊埠預覽:8080)。這會開啟新視窗,顯示執行中的應用程式。

    網路瀏覽器會顯示 Hello, World!

  3. 準備好繼續時,請在 Cloud Shell 中按下 Control+C 停止本機網路伺服器。

部署至單一執行個體

這個部分的內容會逐步引導您在 Compute Engine 中執行單一應用程式執行個體。

單一執行個體的部署作業。

您可以透過 Cloud Shell 將應用程式部署至單一 Compute Engine 執行個體虛擬機器 (VM),藉此執行應用程式。

使用 Cloud Build 建構應用程式

Cloud Build 會建構應用程式、將其壓縮為 tar 檔案,並將檔案上傳至 Cloud Storage bucket。值區是在 Cloud Storage 中存放資料的基本容器。

  1. 在終端機視窗中,建立 Cloud Storage bucket,其中 YOUR_BUCKET_NAME 代表 bucket 名稱:

    gcloud storage buckets create gs://YOUR_BUCKET_NAME

    您可以為 Cloud Storage bucket 選擇任何名稱。建議使用與您專案 ID 相同的名稱來為值區命名。整個Google Cloud內的值區名稱不得重複,因此您有時可能無法使用專案 ID 做為值區名稱。

  2. 啟動 Cloud Build 程序:

    gcloud builds submit --substitutions=_DEPLOY_DIR=gs://YOUR_BUCKET_NAME,_DEPLOY_FILENAME=app.tar.gz

    gcloud builds submit 指令會使用 --substitutions 設定要將產生的 tar 檔案上傳至哪個位置。稍後,系統會將 tar 檔案下載至 Compute Engine 執行個體。

    Cloud Build 會使用 YAML 設定檔定義建構作業所需的步驟。

    steps:
      # Print the Go version being used.
      - name: 'mirror.gcr.io/library/golang'
        args: ['go', 'version']
      # Make a deploy directory we'll tar after building the app.
      - name: 'debian'
        args: ['mkdir', '-p', 'deploy/etc/systemd/system/', 'deploy/usr/bin']
      # Build the app.
      - name: 'mirror.gcr.io/library/golang'
        env: [
          'GO111MODULE=on',
          'GOPROXY=https://proxy.golang.org,direct',
          'GOOS=linux',
          'GOARCH=amd64'
        ]
        args: ['go', 'build', '-o', 'deploy/usr/bin/app', '.']
      # Copy the systemd service file into the deploy directory.
      - name: 'debian'
        args: ['cp', 'my-app.service', 'deploy/etc/systemd/system/']
      # Compress the deploy directory.
      - name: 'debian'
        args: ['tar', '-czf', '${_DEPLOY_FILENAME}', '-C', './deploy', '.']
    # Upload the tarball to Cloud Storage.
    artifacts:
      objects:
        location: '${_DEPLOY_DIR}'
        paths: ['${_DEPLOY_FILENAME}']

使用開機指令碼初始化執行個體

您必須採用可指示執行個體下載及執行程式碼的方法。執行個體可以含有開機指令碼,這個指令碼一律會在執行個體初次啟動或重新啟動時執行。

開機指令碼會在執行個體首次啟動時執行。

set -ex

# Install logging monitor. The monitor will automatically pickup logs sent to syslog.
curl "https://storage.googleapis.com/signals-agents/logging/google-fluentd-install.sh" --output google-fluentd-install.sh
checksum=$(sha256sum google-fluentd-install.sh | awk '{print $1;}')
if [ "$checksum" != "ec78e9067f45f6653a6749cf922dbc9d79f80027d098c90da02f71532b5cc967" ]; then
    echo "Checksum does not match"
    exit 1
fi
chmod +x google-fluentd-install.sh && ./google-fluentd-install.sh
service google-fluentd restart &

APP_LOCATION=$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/attributes/app-location" -H "Metadata-Flavor: Google")
gsutil cp "$APP_LOCATION" app.tar.gz
tar -xzf app.tar.gz

# Start the service included in app.tar.gz.
service my-app start

開機指令碼會執行以下工作:

  • 安裝並設定 Cloud Logging 代理程式,藉此監控應用程式記錄。

  • 下載並解壓縮部署 tar 檔案。

  • 啟動 systemd 服務來執行應用程式。

建立及設定 Compute Engine 執行個體

  1. 建立 Compute Engine 執行個體:

    Linux/macOS

    gcloud compute instances create my-app-instance \
    --image-family=debian-10 \
    --image-project=debian-cloud \
    --machine-type=g1-small \
    --scopes userinfo-email,cloud-platform \
    --metadata-from-file startup-script=startup-script.sh \
    --metadata app-location="gs://YOUR_BUCKET_NAME/app.tar.gz" \
    --zone YOUR_ZONE \
    --tags http-server

    YOUR_ZONE 替換為開發作業的所在區域,例如 us-central1-a。如要進一步瞭解地區和區域,請參閱地理位置與地區

    --metadata app-location 旗標會告知啟動指令碼要從何處下載應用程式 tar 檔案。

    Windows

    gcloud compute instances create my-app-instance ^
    --image-family=debian-10 ^
    --image-project=debian-cloud ^
    --machine-type=g1-small ^
    --scopes userinfo-email,cloud-platform ^
    --metadata-from-file startup-script=startup-script.sh ^
    --metadata app-location="gs://YOUR_BUCKET_NAME/app.tar.gz" ^
    --zone YOUR_ZONE ^
    --tags http-server

    YOUR_ZONE 替換為開發作業的所在區域,例如 us-central1-a。如要進一步瞭解地區和區域,請參閱地理位置與地區

    --metadata app-location 旗標會告知啟動指令碼要從何處下載應用程式 tar 檔案。

    這麼做會建立新的執行個體,並允許該執行個體存取 Google Cloud服務及執行開機指令碼。執行個體的名稱為 my-app-instance

  2. 查看執行個體建立作業的進度:

    gcloud compute instances get-serial-port-output my-app-instance --zone YOUR_ZONE
    

    開機指令碼執行完畢之後,您會看見下列訊息:

    startup-script: INFO Finished running startup scripts.
    
  3. 建立防火牆規則,藉此允許流量傳送至執行個體:

    gcloud compute firewall-rules create default-allow-http-80 \
        --allow tcp:80 \
        --source-ranges 0.0.0.0/0 \
        --target-tags http-server \
        --description "Allow port 80 access to http-server"
    

  4. 取得執行個體的外部 IP 位址:

    gcloud compute instances list
    
  5. 如要查看應用程式的運作情形,請在瀏覽器中輸下列網址:

    http://YOUR_INSTANCE_IP
    

    YOUR_INSTANCE_IP 替換為執行個體的外部 IP 位址。

管理及監控執行個體

您可以使用 Google Cloud 控制台來監控及管理執行個體。

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.
  3. 如要查看 Compute Engine 資源產生的所有記錄,請前往「記錄檔探索工具」頁面。

    前往記錄檔探索工具

    系統會自動將 Cloud Logging 設為從多項常見服務收集記錄檔,包括 syslog

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除個別資源

gcloud compute instances delete my-app-instance --zone=YOUR_ZONE --delete-disks=all
gcloud compute firewall-rules delete default-allow-http-80

後續步驟