きっかけ
systemctlに登録していたAPIサーバー(node.js)のコードを修正した。
その際systemctl reloadをしたものの結果が反映されなかったので、ちゃんと理由を調べてみた。
違う点:プロセスを完全に止めているかどうか
整理してみると、
- configの修正であれば
reloadで対応できる - サーバーのコードを直接変更している場合は一度
restartで止めなければいけない。
| 観点 | reload(systemctl reload app) |
restart(systemctl restart app) |
|---|---|---|
| config の変更反映(SIGHUP 処理あり) | ✅ 反映される | ✅ 反映される |
| app.js の変更反映 | ❌ 反映されない | ✅ 反映される |
| PID の変更 | ❌ 変わらない | ✅ 変わる |
ちょっと調べてみる:手順
適当にサーバーを立てて、reloadとrestartを行い、以下の内容をチェック
- コードの編集が反映されている
- コンフィグの編集が反映されている
- PIDの変更が反映されている
環境はwin11のWLSを利用
コードそのままだと以下のようになる
$ curl http://localhost:3000
Message: config text : ver1
1. systemctl reload app
$ sudo systemctl status app | grep PID
Main PID: 3645 (MainThread)
$ curl localhost:3000
Message: config text : ver1
(コードをここで変更)
$ sudo systemctl reload app
$ curl localhost:3000
Message: config text : ver2
$ sudo systemctl reloasudo systemctl status app | grep PID
Process: 3686 ExecReload=/bin/kill -HUP $MAINPID (code=exited, status=0/SUCCESS)
Main PID: 3645 (MainThread)
| 観点 | reload(systemctl reload app) |
|---|---|
| config の変更反映(SIGHUP 処理あり) | ✅ 反映される |
| app.js の変更反映 | ❌ 反映されない |
| PID の変更 | ❌ 変わらない |
2. systemctl restart app
$ sudo systemctl status app | grep PID
Main PID: 3730 (MainThread)
$ curl localhost:3000
Message: config text : ver1
(コードをここで変更)
$ sudo systemctl restart app
$ curl localhost:3000
NewMessage: config text : ver2
$ sudo systemctl status app | grep PID
Main PID: 3776 (MainThread)
| 観点 | reload(systemctl reload app) |
|---|---|
| config の変更反映(SIGHUP 処理あり) | ✅ 反映される |
| app.js の変更反映 | ✅ 反映される |
| PID の変更 | ✅ 変わる |
コード類
// app.js
const fs = require("fs");
const express = require("express");
const app = express();
// 起動時に config.json を読み込む
let config = JSON.parse(fs.readFileSync("./config.json", "utf-8"));
// アクセスが来たら message を返す(NewMessageに変更)
app.get("/", (req, res) => {
res.send(`Message: ${config.message}`);
});
// systemctl reload が送る SIGHUP を受け取ったときの処理
process.on("SIGHUP", () => {
console.log("Reload signal received. Reloading config...");
try {
config = JSON.parse(fs.readFileSync("./config.json", "utf-8"));
console.log("Config reloaded:", config);
} catch (err) {
console.error("Failed to reload config:", err);
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// config.json
{
// ver2に変更
"message": "config text : ver1"
}