23
25

More than 5 years have passed since last update.

Systemd Unit File チートシート

Posted at

Systemd のサービススクリプトを作る時に毎回調べているので、その負荷軽減のためにメモします。
サービススクリプトを作成する際にご利用ください。

サンプル

[Unit]
Description=名前
After=network-online.target

[Service]
ExecStart=実行ファイルの絶対パス
ExecStop=/bin/kill -INT ${MAINPID}
Restart=always
WorkingDirectory=実行ディレクトリの絶対パス

[Install]
WantedBy=multi-user.target

説明

サンプルのキモを説明します。

  • After 依存するサービス。network-online.targetでネットワーク起動後に作動する。サービスは大体ネットワークに依存するので、サンプルに記載。
  • ExecStop 停止コマンドで実行される。MAINPIDには本スクリプトで起動されたサービスのプロセスIDが入るので、どのコマンドでも(Ctrl + Cで終了できるコマンドは)このスクリプトで停止可能になります。
  • WorkingDirectory node.js等、実行ディレクトリにライブラリが配置される構成ではこれが有効。golangのワンバイナリ実行ファイル等の際は省略可能。
  • Restart サービスが異常停止した場合に再起動してくれる。
  • WantedBy ランレベル3で起動するサービスはmulti-user.target

ファイルの配置場所

/etc/systemd/system/

よく使うsystemctl系コマンド

sudo systemctl enable xxxx #有効化
sudo systemctl disable xxxx #無効化
sudo systemctl start xxxx #起動
sudo systemctl stop xxxx #起動
sudo systemctl status xxxx #状態確認
sudo systemctl daemon-reload #Unitファイルの変更を反映
journalctl -f #ログ確認

もっとカスタマイズしたい。

より良き仕様はここを見ること。

23
25
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
23
25