4
1

More than 3 years have passed since last update.

Node.js製サーバの起動方法をforeverからsystemdに移行する

Posted at

foreverで起動していたExpressのサーバをOS再起動時に自動起動させたかったのでSystemd管理に移行します。
initd向けにforeverの自動起動の仕組みを提供するinitd-foreverというパッケージもあったり、forever自体を起動する方向もアリですが、Systemdでは自動再起動の制御が細かくなっているなど、foreverに期待していた役割自体も担えそうでしたのでシンプルにSystemd → Nodeにしました。
最低限の設定をイメージしてこんな感じになりました。

/etc/systemd/system/mydaemon.service
[Unit]
Description=My Node.js Daemon

[Service]
User=myuser
Group=mygroup
#Environment="NODE_ENV=production"
WorkingDirectory=/path/to/
ExecStart=/usr/bin/node app.js
Restart=always

[Install]
WantedBy=multi-user.target

あとは
systemctl enable mydaemon.service で自動起動有効化し、
systemctl start mydaemon.service で起動します。

User/Groupは指定しなければrootになってしまうため指定しています。
Environmentは今回不要でしたがExpressで使う機会が多そうなのでコメントアウト状態でサンプルとして入れています。
対象のスクリプトはnode app.jsで起動して、Ctrl+Cで終了させるような動きになっている必要があります。
Restart=alwaysによってプロセスが落ちても自動的に復帰させます。
デフォルトで10秒に5回の再起動に制限されますがStartLimitInterval StartLimitBurst で調整できます。

foreverのwatchに対応する機能は無さそうですが今回の目的には不要でした。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1