第一個 Google App Engine 筆記

Google App Engine 有什麼好處呢?當有大流量使用需求的時候很好用,不用自己管理 load balance 的問題。Google會幫你自動開關 instances,使用多少就付多少,頻寬超高的使用 Google App Engine 幾乎沒有什麼延遲。就我個人的觀點,純 app developer 很適合用 Google App Engine。省去自己架設機器部署軟體的麻煩,更不用知道底層系統是怎麼運作的。可以讓開發者專心的開發程式,把產品快速上線,且網頁服務具備scale-in & scale-out的能力。對於有大量的訂單或是搶票系統有需求的真的可以好好考慮使用 App Engine。

首先,當然先註冊 Google Cloud Platform 開始試用,目前新註冊的人可以享有 一年 300 美金的試用。記得找一張信用卡輸入才能開始適用,理論上在試用階段還沒正式開始使用 Google 不會為向你收費。

再來,前往 Google Cloud SDK 下載適合的版本到你的電腦。我是使用 mac 版本 所以我下載 google-cloud-sdk-153.0.0-darwin-x86_64.tar.gz 解壓縮後複製到 /Applications/google-cloud-sdk,然後開啟終端機 打下列指令:

$ cd /Applications/google-cloud-sdk/
$ ./install.sh

之後進入 Google Cloud Console 在左邊選 App Engine

你可以建立新的專案 或是直接使用已經存在的 My Cloud Project or My First Project,接下來按 Your first app 後就會有教學 按照 Google 的導引還蠻容易上手

不過我想要直接選 左邊的 Development

建立新的 Repository 按 CREATE REPOSITORY 輸入你想要的名稱

我建立 helloworld 的 repository 按照上面的指示 可以把本機端的程式上傳 google 的 Cloud Repository 也可以把 Cloud Repository 複製回來本機端 當然可以從其他 GitHub or Bitbucket 複製到 Cloud Repository ,因為是第一支程式所以我選擇 “Push code from a local Git repository to your Cloud Repository” 上傳到 Cloud Repository

在上傳之前必須在終端機內先建立好該有的環境所以我按照指示打了下列的指令,這個指令可以讓你的環境初始化,也可以選擇你要使用的專案等,裡面會有些互動的對話自己選擇一下

$ gcloud init && git config credential.helper gcloud.sh

由於我本機端還沒有任何程式,所以沒辦法按照指示完成下列指令:

$ git remote add google https://source.developers.google.com/p/trans-mind-315/r/helloworld

所以我反向把 Google Cloud Repository 抓空的目錄回來

$ gcloud source repos clone helloworld –project=trans-mind-315

然後進入遠端抓回來的目錄 helloworld 並編寫要上傳的程式,app.yaml 是 app engine 的描述檔,由於我是選用php所以在 runtime 上面指定 php55 然後 script 裡面主要要呼叫的程式 在這個範例裡面直接呼叫 helloworld.php

$ cd helloworld
$ vi app.yaml

runtime: php55
api_version: 1

handlers:
– url: /.*
script: helloworld.php

$ vi helloworld.php
< ? php echo "hello world!!";

再用下列指令把程式推上 Google Cloud Repository

$ git add .
$ git commit -m ‘initial helloworld app commit’
$ git push -u origin master

這樣在 Google Cloud Repository 就可以看到上傳的 codes

由於在自己的環境下,並沒有把 php 設立好,所以借助 google 所提供的 shell 環境,右上方可以找到這個下列圖示的按鈕,開啟 Cloud Shell

然後把剛剛上傳的程式抓到 Cloud Shell 內 並進入 helloworld

$ gcloud source repos clone helloworld –project=trans-mind-315
$ cd helloworld

用下列指令啟動 app engine 測試環境,驗證剛剛所寫的程式

$ dev_appserver.py –php_executable_path=/usr/bin/php-cgi $PWD

然後按左上方 Preview on port 8080

就可以看到測試的結果,這還不是正式把程式部署到 app engine 環境,必須回到剛剛的 Google Cloud Shell 按 Ctrl + C 終止它

把剛剛測試ok的程式部署上去 Google App Engine

$ gcloud app deploy app.yaml –project trans-mind-315

在 App Engine 內點選 Services 可以看到 default

點選 default 之後就可以看到 helloworld 程式被部署到 Google App Engine 而且也有得到 https 的服務 https://trans-mind-315.appspot.com/

恭喜!這樣第一個 Google App Engine 就上線了

最後,假設你要把專案移除可以用下列指令

$ gcloud projects delete trans-mind-315

ps 當使用量大的時候燒錢的速度也是很驚人,如果沒有用的話記得關起來以免不小心 GG 了

可以看到 instances autoscaled 的威力,做好的服務真的需要燒很多錢!

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.