普通文組 2.5

「部屬Express.js App至Google App Engine」相關筆記

總結

  • 同樣是在搭配使用 MongoDB 的情境下,整體流程比感覺比部屬至 Heroku 簡單許多
  • 缺點:無法處理「對資料庫導入種子資料」的需求;雖然 App Engine 提供runtime: customDockerfile來處理一定程度的客製化需求,但無法配合docker-compose.yml來安裝 mongoDB

環境

Google Cloud SDK: 346.0.0
os: Windows_NT 10.0.18363 win32 x64

部屬前設定

app.js

// 新增process.env.PORT,讓App可以讀取Google App Engine分配的埠號
const port = process.env.PORT || 5000;

// 追加以下內容
app.set("trust proxy", true);
  • 關於app.set('trust proxy', true)
    • 參考官方文件內容:HTTPS and forwarding proxies
    • App Engine terminates HTTPS connections at the load balancer and forwards requests to your application. Some applications need to determine the original request IP and protocol. The user’s IP address is available in the standard X-Forwarded-For header. Applications that require this information should configure their web framework to trust the proxy.
    • With Express.js, use the trust proxy setting: app.set('trust proxy', true)

config/mongoose.js

// 於config/mongoose.js中追加process.env.MONGODB_URI
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/login-passport'
mongoose.connect(MONGODB_URI, { ... })

app.yaml

runtime: nodejs12
env_variables:
  MONGODB_URI: "mongodb+srv://<DB使用者帳號>:<DB密碼>@<MongoDB cluster名稱>.8glc1.mongodb.net/<MongoDB cluster名稱>?retryWrites=true&w=majority"

package.json

"scripts": {
  "start": "node app.js"
},
"engines": {
  "node": "^12.0.0"
}
  • Google App Engine 預設執行node server.js來啟動 App,可以透過 package.json 中的start scripts 修改執行內容(本次練習中改為node app.js
  • 參考官方文件:By default, the runtime starts your application by running node server.js. If you specify a start script in your package.json file, the runtime runs the specified start script instead.

部屬流程

  1. 在 Google Cloud Platform 建立新專案
  2. 安裝 Google Cloud SDK
  1. 安裝完畢後,移動到要部屬到 Google App Engine 的專案的資料夾,在終端機輸入gcloud init

  2. 完成布署前設定後,即可執行gcloud app deploy,部屬完畢後終端機會顯示 App URL(類似https://<專案ID>.de.r.appspot.com/),可直接開啟該 URL 瀏覽專案

  3. 若 URL 打開後沒有載入任何內容,則進入 App Engine → 版本 → 診斷 → 記錄檔中查看錯誤訊息

    demo 1 demo 2

練習結果

關於種子資料