# 使用 NSSM 在 Windows 上部署 FastAPI 伺服器 [TOC] ## 🧩 補充 FastAPI 專案結構建議(背景假設) 本教學假設你已有 FastAPI 專案結構 ``` linebot/ ├── main.py ├── app/ │ └── init.py ├── venv/ └── logs/ ``` ## 🛠 安裝並設定 NSSM ### ✅ 1. 下載 NSSM * 官網:[https://nssm.cc/download](https://nssm.cc/download) * 解壓後路徑例如:`C:\tools\nssm-2.24\win64\nssm.exe` --- ### ✅ 2. 加入 NSSM 到系統環境變數(可選但推薦) 這樣你未來就能直接在命令列輸入 `nssm`,不需要每次打長長的路徑。 1. **打開系統環境變數:** - Win + S → 搜尋「環境變數」→ 點選「編輯系統環境變數」 2. 點選下方的【環境變數(N)...】 3. 在「系統變數」區域找到並編輯 **Path** 4. 點【新增】,加入你的 NSSM 路徑,例如: C:\tools\nssm-2.24\win64\ --- ### ✅ 3. 設定 NSSM(GUI 視窗) 1. 開啟命令提示字元(管理員) | 是否nssm加入環境變數 | 指令| | -------- | -------- | | 加入 | `nssm install fastapi-linebot` | | 未加入 | `C:\tools\nssm-2.24\win64\nssm.exe install fastapi-linebot` | 2. nssm指令輸入 | 欄位 | 設定值 |說明| | --------- | ----- | --- | | **Application Path** | `C:\Users\UserName\projects\linebot\venv\Scripts\python.exe` |執行的python 環境| | **Startup directory** | `C:\Users\UserName\projects\linebot` |有main.py的檔案資料夾| | **Arguments** | `-m uvicorn main:app --host 127.0.0.1 --port 8000` | | --- ### ✅ 4. 設定 log 輸出(I/O 頁籤) - 可選 * **stdout path**: `C:\Users\UserName\projects\linebot\logs\fastapi-out.log` * **stderr path**: `C:\Users\UserName\projects\linebot\logs\fastapi-err.log` --- ### ✅ 5. 啟用服務 1. 開啟命令提示字元(管理員) 2. 輸入 `nssm start fastapi-linebot` --- ## ▶️ 操作 NSSM 服務 | 動作 | 指令 | | -------- | ----------------------------------- | | 啟動服務 | `nssm start fastapi-linebot` | | 修改服務 | `nssm edit fastapi-linebot` | | 停止服務 | `nssm stop fastapi-linebot` | | 重新啟動 | `nssm restart fastapi-linebot` | | 移除服務 | `nssm remove fastapi-linebot confirm` | | 編輯設定 | `nssm edit fastapi-linebot` | | 檢查狀態 | `sc query fastapi-linebot` | --- ## 🔍 測試服務是否正常 * 瀏覽器開啟:[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) * 或用 curl 測試: ```bash curl http://127.0.0.1:8000/ ``` --- ## 查看stderr.log 需使用powershell查看,查看尾巴1000行 ``` Get-Content .\stderr.log -Tail 1000 ``` 清除檔案內容 ``` Clear-Content .\stderr.log ``` ## 🧠 小提醒 * 請確保 log 檔案夾存在,否則 NSSM 啟動會失敗 * 登出帳號後服務仍會保持執行 * 可搭配 Windows 工作排程實現進一步自動控制 - 定時啟動或停止 FastAPI 服務(如每日早上 8 點啟動,晚上 9 點關閉) - 定期重新啟動服務以釋放資源 - 開機自動啟動(若未設定 NSSM 自動啟動) --- 📌 ChatGPT 協作 📅 建立:2025-06-12
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up