【 Cloud 】部署 Node.js Express App 到 Fly.io 雲端平台
前言
- 因 Heroku 雲端平台將終止部分服務的免費使用額度,故轉移 App 到目前提供免費額度的 Fly.io 雲端平台。
內容
- 學習目標
- 前置準備作業
- 專案最終目錄結構
- 撰寫程式與設定檔
- 部署 App 到 Fly.io
學習目標
- 如何部署
Node.js Express App
到Fly.io
雲端平台
前置準備作業
- 已建立 Fly.io 帳號並能正常登入
- Fly.io 的網址為 https://fly.io/
- 已於電腦端安裝 Node.js
- 已於電腦端安裝 IDE,本範例使用 Visual Studio Code
- 已於電腦端安裝 flyctl
專案最終目錄結構
└── nodejs-sample
├── fly.toml → 執行完 flyctl 指令後會產生
├── package-lock.json
├── package.json
└── server.js
撰寫程式與設定檔
Step 1. 建立 server.js
之 Node.js 程式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const app = express(); | |
const port = process.env.PORT || 3000; | |
app.use(bodyParser.urlencoded({ extended: true })) | |
app.use(bodyParser.json()) | |
app.get('/', (req, res) => { | |
res.send('Node.js Express on fly.io !'); | |
}); | |
app.post('/store', (req, res) => { | |
res.send({ | |
run: req.body.run, | |
}); | |
}); | |
app.listen(port, () => { | |
console.log(`Example app listening on port ${port}!`) | |
}) |
部署 App 到 Fly.io
Step 1. 透過 flyctl 登入到 Fly.io
-
請在終端機輸入下方指令
flyctl auth login
Step 2. 建立 App
-
請在終端機輸入下方指令
flyctl launch
Step 3. 部署 App 到 Fly.io
-
請在終端機輸入下方指令
flyctl deploy
Step 4. 查看部署狀態
-
請在終端機輸入下方指令
flyctl status
Step 5. 開啟 App
-
請在終端機輸入下方指令
flyctl open
Step 6. 開啟 Fly.io