document.writeln('');
可行但需用Type=notify+sdnotify.Ready(),因Type=simple僅等待進程fork完成,不確保Gin真正就緒;必須配置NotifyAccess=all、絕對路徑ExecStart、明確WorkingDirectory,并在DB連接、路由注冊完成后調用sdnotify.Ready()再啟動server。

直接用 systemd 管理 Gin 服務是可行的,但默認寫法大概率會出問題:服務狀態顯示 active (running),實際 HTTP 還沒 listen 完、DB 沒連上、健康檢查失敗,下游依賴就已開始調用——這是 Type=simple 的典型誤用。
因為 Type=simple 下 systemd 只等 Go 進程 fork 完就標記為 “started”,根本不管你的 Gin 服務器是否真正 ready。Gin 啟動本身很快,但真實就緒要等配置加載、DB 連接池初始化、中間件注冊完成——這些都在 http.ListenAndServe 或 engine.Run 之前。
systemctl start mygin 后立刻 curl http://localhost:8080/health 返回 connection refusedType=notify + sdnotify.Ready() 主動通知就緒點光改 Type=notify 不夠,缺一不可:
NotifyAccess=all 必須加,否則 Go 在 goroutine 里調用 sdnotify.Ready() 會被 systemd 拒絕(默認只接受 main PID 的通知)GuessMainPID=yes,它和 Type=notify 沖突,會導致 READY 消息被丟棄ExecStart 必須是絕對路徑,比如 /opt/mygin/bin/mygin,不能寫 ./myginWorkingDirectory=/opt/mygin 要明確指定,否則 os.Open("config.yaml") 會找不到文件別在 main() 開頭就發,得等所有初始化完成、HTTP server 準備就緒之后再發:
立即學習“go語言免費學習筆記(深入)”;
sdnotify.Ready() —— 這一步告訴 systemd:“我可以收請求了”router.Run(":8080") 或 http.ListenAndServe1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
兩個獨立但常同時出現的問題:
journalctl -u mygin 查不到日志?檢查 service 文件里有沒有 StandardOutput=journal 和 StandardError=journal;Gin 默認用 log 包輸出到 stderr,但舊版 systemd(如 CentOS 7)默認不采集 stderrsignal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT),收到后調用 router.Shutdown() 或 http.Server.Shutdown()log.Fatal 或 panic 后直接退出,這會讓 systemd 認為 crash,按 Restart=on-failure 策略拉起,但可能反復失敗最易被忽略的是:READY=1 和 Shutdown 之間沒有原子性保障——如果 systemd 在你發完 READY 后、啟動 server 前就發 SIGTERM,程序會卡在監聽前。務必把 sdnotify.Ready() 放在所有初始化完成、且 server 已準備好 accept 連接的那一刻。