將 Mastra 部署至 Amazon EC2
將你的 Mastra 伺服器部署至 Amazon EC2。伺服器會在你管理的基礎設施上運行,並可支援長時間運行的 Agent 和 Workflow。
資訊
本指南涵蓋如何部署 Mastra 伺服器。如你使用伺服器適配器或網頁框架,請依照該框架慣常的方式部署。
開始之前開始之前 的直接連結
你需要:
- 一個 Mastra 應用程式
- 一個已安裝 Git 和 Node.js 22.13.0 或以上版本的 EC2 執行個體(Ubuntu 或 Amazon Linux)
如要用於生產環境,你亦需要:
部署部署 的直接連結
連線至你的 EC2 執行個體並複製儲存庫:
- 公開儲存庫
- 私人儲存庫
git clone https://github.com/<your-username>/<your-repository>.gitgit clone git@github.com:<your-username>/<your-repository>.git前往儲存庫目錄:
cd "<your-repository>"安裝依賴套件:
- npm
- pnpm
- Yarn
- Bun
npm installpnpm installyarn installbun install建立
.env檔案並加入環境變數:touch .env請記得設定運行應用程式所需的環境變數(例如模型 Provider 的 API 金鑰):
OPENAI_API_KEY=<your-openai-api-key># Add other required environment variables建置應用程式:
- npm
- pnpm
- Yarn
- Bun
npm run buildpnpm run buildyarn buildbun run build運行應用程式:
node --env-file=".env" .mastra/output/index.mjs這是一個基本範例。在生產環境中,請使用 PM2 或 systemd 等程序管理器,讓應用程式持續運行並處理重新啟動。
注意對外公開端點前,請先設定驗證。
你的 Mastra 伺服器現已在連接埠 4111 上運行,但只能從本機存取。
你可以在 EC2 安全群組中開啟連接埠 4111 以直接存取,或設定反向代理(例如 nginx)監聽連接埠 80 和 443,並將請求轉送至
http://localhost:4111。在生產環境中,你應使用反向代理,以便設定 HTTPS。HTTPS 會加密網絡流量,而且大多數 webhook 整合和 Agent 互動的外部服務均要求使用 HTTPS。
在
https://<your-ec2-address>/api/agents驗證部署;該網址應會傳回 Agent 的 JSON 清單。你現在可以透過 HTTP 呼叫 Mastra 端點。