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
Author And Source
この問題について(Ubuntu16.04以降でsystemdを使ってforeverを自動起動する), 我々は、より多くの情報をここで見つけました https://qiita.com/subaru44k/items/eb19b8549a294145b103著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .