終了後にプロセスを自動的に再起動

終了後にプロセスを自動的に再起動

nodejsで実行されるJavaScriptプログラムがあります。次のコマンドを実行すると:

node app.js

継続して実行されますが、時には終了します。しかし、終了したら自動的に再起動したいと思います。

Linuxでこれを行うコマンドはありますか? cronジョブを使用したくありません。

ベストアンサー1

迅速で汚い方法:bashを使用している場合、単純なbashスクリプトはどうですか?

#!/usr/bin/bash
while true
do
  node app.js
done

しかし、ジョブが終了した理由と妥当な理由がある可能性がある理由を考慮していないため、これは誤動作です。いいえ再起動してください。起動時にクラッシュが発生して死亡する可能性があります...


体系的なLinuxでより標準化された方法:(@Kusalanandaのコメントの一部として提案され、以下からインスピレーションを得ました。Linuxにノードアプリケーションをデプロイするための最終ガイド):

app.jsが#!/usr/bin/env node宣言で始まり、app.jsファイルが実行可能としてマークされていると仮定すると、

新しいサービス設計:システム全体に必要な場合、または次のようにユーザーにのみ必要な場合は、/etc/systemd/systemディレクトリに.serviceファイルを作成します。~/.config/systemd/user

[Unit]
Description=        #(Whatever String You Want)
After=              #(Any service that should be started before, ex. network.target)
[Service]
ExecStart=          #(Key in the absolute path of app.js)
Restart=always      #(This will ensure the automatic restart)
User=               #(TBD depending on your system & wishes)
Group=              #(TBD depending on your system & wishes)
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=   # (Absolute path of app.js working dir.)
[Install]
WantedBy=           # multi-user.target or default.target according to your needs

これで始めることができます:systemctl --user start service_filename

おすすめ記事