開始在 Compute Engine 中使用 Java

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

目標

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

費用

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

您可以使用 Pricing Calculator,根據預測用量估算費用。

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

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  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 role (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 API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  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 role (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 API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

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

    前往 Cloud Shell

    Cloud Shell 提供指令列,讓您直接從瀏覽器存取雲端資源。

  9. 如果同意複製存放區,請按一下「Confirm」(確認),下載程式碼範例並切換至應用程式目錄。

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

在 Cloud Shell 中執行應用程式

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

    mvn -Plocal clean jetty:run-exploded -DprojectID=YOUR-PROJECT-ID
    
  2. 按一下 Cloud Shell 中的 [Web preview] (網頁預覽),然後選取 [Preview on port 8080] (透過以下通訊埠預覽:8080)。系統會開啟新視窗,顯示執行中的應用程式。

    在網路瀏覽器中,您會看到本機機器提供的 Hello World 文字。

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

部署至單一執行個體

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

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

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

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

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

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

set -e
set -v

# Talk to the metadata server to get the project id
PROJECTID=$(curl -s "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google")

echo "Project ID: ${PROJECTID}"

# Install dependencies from apt
apt-get install -yq openjdk-11-jdk git maven

mvn --version

# Jetty Setup
mkdir -p /opt/jetty/temp
mkdir -p /var/log/jetty

# Get Jetty
curl -L https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-distribution/9.4.13.v20181111/jetty-distribution-9.4.13.v20181111.tar.gz -o jetty9.tgz
tar xf jetty9.tgz  --strip-components=1 -C /opt/jetty

# Add a Jetty User
useradd --user-group --shell /bin/false --home-dir /opt/jetty/temp jetty

cd /opt/jetty
# Add running as "jetty"
java -jar /opt/jetty/start.jar --add-to-startd=setuid
cd /

# Clone the source repository.
git clone https://github.com/GoogleCloudPlatform/getting-started-java
cd getting-started-java/gce

# Build the .war file and rename.
# very important - by renaming the war to root.war, it will run as the root servlet.
mvn clean package -q
mv target/getting-started-gce-1.0-SNAPSHOT.war /opt/jetty/webapps/root.war

# Make sure "jetty" owns everything.
chown --recursive jetty /opt/jetty

# Configure the default paths for the Jetty service
cp /opt/jetty/bin/jetty.sh /etc/init.d/jetty
echo "JETTY_HOME=/opt/jetty" > /etc/default/jetty
{
  echo "JETTY_BASE=/opt/jetty"
  echo "TMPDIR=/opt/jetty/temp"
  echo "JAVA_OPTIONS=-Djetty.http.port=80"
  echo "JETTY_LOGS=/var/log/jetty"
} >> /etc/default/jetty

# Reload daemon to pick up new service
systemctl daemon-reload

# Install logging monitor. The monitor will automatically pickup logs sent to syslog.
curl -sSO https://dl.google.com/cloudagents/add-logging-agent-repo.sh
sudo bash add-logging-agent-repo.sh --also-install

service google-fluentd restart &

service jetty start
service jetty check

echo "Startup Complete"

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

  • 安裝 Java 11 並設為預設版本。

  • 安裝並設定 Jetty。

  • 將 Java WAR 檔案從 Cloud Storage bucket 複製到 Jetty 的 webapps,並重新命名為 root.war。如此即可讓檔案成為根 Servlet,而無須在網址中為其命名。

  • 安裝 Cloud Logging 代理程式,並設定監控應用程式記錄。這表示系統會上傳您在本教學課程的先前步驟中所設定的記錄,如同使用 App Engine 彈性環境。

建立及設定 Compute Engine 執行個體

  1. 建立 Compute Engine 執行個體:

    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=gce/startup-script.sh
    --zone YOUR_ZONE
    --tags http-server
    將 YOUR_ZONE 替換為開發可用區,例如 us-central1-a。如要進一步瞭解區域和可用區,請參閱「地理位置與區域」。

    這會建立新的執行個體、允許該執行個體存取 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. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面。

    前往 VM 執行個體

  2. 在虛擬機器執行個體清單中,按一下您要連線的執行個體那一列的 SSH。
  3. 如要查看 Compute Engine 資源產生的所有記錄,請前往「Logs Explorer」頁面。

    前往「Logs Explorer」

    Cloud Logging 會自動設定,從各種常見服務 (包括 syslog) 收集記錄。

清除所用資源

為避免因為本教學課程所用資源,導致系統向 Google Cloud 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除個別資源

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

後續步驟