Ubuntu16.04以降でsystemdを使ってforeverを自動起動する


やりたいこと

Ubuntuが再起動等した際にウェブサーバーを自動起動したいので、foreverコマンドが勝手に走るようにしたい。
AWSやAzureでは、トラブル等があると予告なくインスタンスを再起動することがあるので自動起動設定しておかないとダメだよとAzureの講師の人に言われたので対処する。

Ubuntu16.04にて自動起動

Ubuntu14.04まではSysVinitが使われていたようだが、Ubuntu16.04からはsystemdになったようで、systemdを使って自動起動設定を行う。

設定

基本的には以下のURLの通りに実施すれば良いが、落とし穴もあったので順に書いていく。
https://askubuntu.com/a/895333

serviceの作成

/etc/systemd/system/forever.serviceを以下の内容で作成。

[Unit]
Description=forever service
After=network.target

[Service]
ExecStart=/home/george/.npm-global/bin/forever start /home/ubuntu/server/bin/www
ExecStop=/home/george/.npm-global/bin/forever stop /home/ubuntu/server/bin/www
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=forever-example

[Install]
WantedBy=multi-user.target

ExecStartとExecStopの内容は、which forever等実行して環境に合わせて変更する。

serviceの自動起動設定

以下のコマンドを実行し、登録したサービスを実行&自動実行設定する。

sudo systemctl start forever.service
sudo systemctl enable forever.service

変だと思ったら/var/log/syslogを見るとログが出ている。

クラッシュの修正

ただし、この通りに実行すると、自動起動後に

error: Forever detected script was killed by signal: SIGKILL

というログとともにforeverが殺されたので、以下を追加しないといけない。

Type=forking

環境変数の設定

forever実行時にNODE_ENV=productionの環境変数を付与するために、以下も追加する。

Environment="NODE_ENV=production"

最終型

上記を踏まえて、サービスの設定ファイルは以下とする。

[Unit]
Description=forever service
After=network.target

[Service]
Type=forking
Environment="NODE_ENV=production"
ExecStart=/home/george/.npm-global/bin/forever start /home/ubuntu/server/bin/www
ExecStop=/home/george/.npm-global/bin/forever stop /home/ubuntu/server/bin/www
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=forever-example

[Install]
WantedBy=multi-user.target

自動起動を有効にする。

sudo systemctl start myforever.service
sudo systemctl enable myforever.service

あとは、以下コマンドを実行して状態を確認する。

systemctl status forever.service

また、以下コマンドにて再起動して、ちゃんとサーバー立ち上がれば間違いない。

sudo shutdown -r now