Node.js: 快速開始
學習如何在 Stackhero 上快速且安全地部署 Node.js 服務
👋 歡迎來到 Stackhero 文檔!
Stackhero 提供即用型的 Node.js 雲端 解決方案,帶來多項優勢,包括:
- 只需一個簡單的
git push,即可在幾秒鐘內 部署您的應用程式。- 使用您自己的域名,並享受 HTTPS 證書的自動配置以增強安全性。
- 享受自動備份、一鍵更新,以及簡單、透明且可預測的定價,讓您高枕無憂。
- 憑藉專用的私人 VM,獲得最佳的性能和強大的安全性。
節省時間並簡化您的生活:只需 5 分鐘即可嘗試 Stackhero 的 Node.js 雲端託管 解決方案!
在 Stackhero 上部署您的 Node.js 服務設計上就是要快速、高效且可靠。本指南將帶您一步步完成部署應用程式的基本流程,讓您的應用在幾分鐘內上線,同時兼顧安全性與效能。
啟動 Node.js 服務
首先,讓我們在 Stackhero 上建立一個 Node.js 服務。這將作為您應用部署的基礎,並讓您享有 Stackhero 雲端主機的所有優勢。
先決條件
在開始之前,請確保您已準備好以下工具:
- Git: 您可以從 https://git-scm.com/downloads 下載。
- Windows 使用者: 為了獲得更順暢的體驗,建議使用 Microsoft Store 上的 Windows Terminal。
設定您的服務
主要的設定步驟是更新您的 SSH 公鑰。這個金鑰讓 Stackhero 能安全地存取您的程式碼儲存庫。
要找到您的公鑰,請在終端機執行下列其中一個指令:
cat ~/.ssh/id_rsa.pub
或
cat ~/.ssh/id_ed25519.pub
如果您尚未有 SSH 金鑰對,可以在 Linux 或 macOS 執行 ssh-keygen,或在 Windows 執行 ssh-keygen.exe 來產生。
取得公鑰後,請登入 Stackhero 控制台,選擇您的 Node.js 服務,進入設定區塊,並將您的金鑰貼到指定欄位。
Tip: 如果您希望 SSH 公鑰能套用到所有未來建立的服務,可以全域設定。只需前往 Stackhero 控制台,點選右上角的大頭貼,進入「您的個人檔案」,然後將 SSH 公鑰貼上即可。
複製範例專案
為了協助您快速上手,我們提供了一個 Node.js 範例應用,展示如何在 Stackhero 上部署。您可以用以下指令複製儲存庫:
git clone https://github.com/stackhero-io/nodejsGettingStarted.git stackhero-nodejs-getting-started
cd stackhero-nodejs-getting-started
設定遠端儲存庫伺服器
透過 Git 在 Stackhero 上部署應用非常簡單。在您的服務主頁會看到一條新增 Git 遠端的指令,類似如下:
git remote add stackhero ssh://stackhero@<XXXXXX>.stackhero-network.com:222/project.git
您可以直接複製這條指令到終端機來設定遠端。
部署您的 Node.js 應用程式
要部署,只需將您的程式碼推送到 Stackhero:
git push stackhero main
第一次推送時,系統會要求您確認金鑰指紋。請輸入「yes」繼續。
幾秒鐘後,您的應用就會上線。您可以在 Stackhero 控制台看到網站網址(例如 https://<XXXXXX>.stackhero-network.com),用來檢查應用狀態。
就是這麼簡單,您的應用已經部署完成。
如果需要修改,只要更新 app.js 檔案,提交並推送您的變更:
git add -A .
git commit -m "Update app.js"
git push stackhero main
部署現有應用程式
如果您已經有 Node.js 應用,只需如上所述新增 Stackhero 遠端,然後推送您的程式碼:
git push stackhero main
處理錯誤 "failed to push some refs to '[...]'"
如果遇到以下錯誤:
error: failed to push some refs to '[...]'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
(e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
這代表您的本地儲存庫與遠端不同步。您可以強制推送:
git push -f stackhero main
處理錯誤 "src refspec main does not match any"
如果推送時看到以下訊息:
error: src refspec main does not match any
error: failed to push some refs to 'ssh://<XXXXXX>.stackhero-network.com:222/project.git'
這通常表示 main 分支不存在。請嘗試改推送 master 分支:
git push stackhero master
處理推送時 "Everything up-to-date" 錯誤
如果 Git 顯示「Everything up-to-date」但您的變更沒有部署,可能是忘記提交。請執行:
git add -A .
git commit -m "您的 commit 訊息"
git push stackhero main
如果沒有任何變更但仍想觸發部署,可以強制建立一個空提交:
git commit --allow-empty -m "Force update"
git push stackhero main
部署非 main 分支
如果您想部署 main 以外的分支,例如 production,可以這樣做:
git push stackhero production:main
部署標籤(tag)
如果您使用標籤並想部署特定標籤(例如 v1.0),請執行:
git push stackhero 'v1.0^{}:main'
^{} 會確保推送與該標籤相關聯的 commit。
回溯或部署特定 commit
如果需要部署特定 commit,先用 git log 找到 commit hash,然後這樣部署:
git push -f stackhero <HASH>:main
部署到多個環境
您可能會需要分開 production 與 staging 環境。要將現有遠端從 stackhero 重新命名為 stackhero-staging,請執行:
git remote rename stackhero stackhero-staging
接著,在 Stackhero 控制台建立新的 Node.js 服務,並新增為 stackhero-production:
git remote add stackhero-production ssh://stackhero@<XXXXXX>.stackhero-network.com:222/project.git
之後即可分別部署到不同環境:
git push stackhero-production main
或
git push stackhero-staging main
將 SSH 私鑰密碼儲存到 macOS 金鑰圈
在 macOS 上,您可能每次推送都會被要求輸入 SSH 金鑰密碼。為了方便與安全,您可以用以下指令將密碼儲存到 macOS 金鑰圈:
/usr/bin/ssh-add --apple-use-keychain ~/.ssh/id_rsa
這個指令會將您的金鑰密碼儲存起來,未來部署時就不會再被要求輸入。
管理機密資訊(secrets)
在 staging 與 production 環境下,安全管理像是 token 或密碼等機密資訊非常重要。建議不要將 secrets 存在儲存庫中,而是使用環境變數來提升安全性。
您可以在 Stackhero 控制台新增環境變數,並在 Node.js 程式碼中存取。例如,若您定義了一個名為 mySecret 的變數,可以這樣存取:
process.env.mySecret
開啟其他網路埠口
如果您的應用需要使用 HTTP 以外的協定,可以在 Stackhero 控制台直接開啟額外的 TCP 或 UDP 埠。只需指定公開入口埠、Node.js 服務上的目標埠,以及協定(TCP 或 UDP)。
儲存檔案
若需儲存使用者檔案(如照片),建議使用物件儲存(object storage)方案。這樣可讓多個服務與實例共用檔案,並將程式碼與資料分離。我們推薦 MinIO,這是一個快速、簡單且功能強大的解決方案,並相容於 Amazon S3 協定。
如果您偏好本地儲存,也可以使用 Node.js 實例內建的持久儲存空間,路徑為 /persistent/storage/。
注意: 請務必將資料儲存在
/persistent/storage/資料夾內。儲存在此資料夾以外的資料,若實例重啟或推送程式碼時,可能會遺失。
優雅關閉(Graceful shutdown)
當您部署新版本應用時,舊版本會先收到終止訊號再關閉。這讓您的應用有時間關閉資料庫連線與其他服務,確保平順關閉。
終止訊號 SIGTERM 會傳送給您的應用。您可以在程式碼中這樣處理:
process.on('SIGTERM', () => {
// 這個 log 會顯示在 Stackhero 控制台的「logs」分頁
console.info('SIGTERM signal received.');
// 在這裡關閉資料庫連線或其他服務
// ...
});
讓程式碼運行於多核心 CPU
預設情況下,Node.js 只會使用單一核心與一個執行緒。若要善用所有可用 CPU 核心,建議使用 Node.js 的 cluster API。官方文件請參考:https://nodejs.org/api/cluster.html。
以下是一個簡單範例,建立一個使用所有 CPU 的 HTTP 伺服器:
const cluster = require('cluster');
const http = require('http');
const cpusCount = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < cpusCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers 會共用任何 TCP 連線,這裡是 HTTP 伺服器
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}