LoginSignup
752
708

More than 5 years have passed since last update.

Systemdを使ってさくっと自作コマンドをサービス化してみる

Last updated at Posted at 2015-06-19

Systemdの仕組みをつかうと、自分で作ったコマンドを簡単にサービスとして登録することができます。

例として、hello worldを延々とファイルに書き込むコマンドをサービス化してみましょう。

1. コマンドを作る

/opt/hello.sh というスクリプトを用意します。

sudo nano /opt/hello.sh
/opt/hello.sh
#!/bin/bash
while true
do
   echo hello world >> /tmp/hello.log
   sleep 1
done

実行権限を与えます。

sudo chmod 0755 /opt/hello.sh

2. /etc/systemd/system/ の下にUnit定義ファイルを作る

sudo nano /etc/systemd/system/hello.service

中身はこんなんです。

/etc/systemd/system/hello.service
[Unit]
Description = hello daemon

[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

ExecStartに実行したいコマンドを書きます。
Restart = always はプロセスやサーバが不意に落ちた時に自動再起動するモードです。

Unitファイルの詳しい書き方については下記記事を参考にしてください。
Systemd入門(1) - Unitの概念を理解する - めもめも
Systemd入門(4) - serviceタイプUnitの設定ファイル - めもめも

(Type = simpleはデフォルトでそうなってるので書く必要ないのですが、書いたほうがわかりやすい
ので明示的に書く方がよいでしょう)

3. UnitがServiceとして認識されたか確認する

systemctl list-unit-files --type=serviceの出力に現れればOKです。

$ sudo systemctl list-unit-files --type=service | grep hello
hello.service                              disabled

OK!

4. enableしてstartする

ここまでくれば、後はいつものように普通のサービスとして扱えます。

# 自動起動on
$ sudo systemctl enable hello
# 起動
$ sudo systemctl start hello

ステータス確認

$ sudo systemctl status hello

hello.service - hello daemon
   Loaded: loaded (/etc/systemd/system/hello.service; enabled)
   Active: active (running) since 金 2015-06-19 09:02:19 UTC; 2min 54s ago
 Main PID: 551 (hello.sh)
   CGroup: /system.slice/hello.service
           ├─ 551 /bin/bash /opt/hello.sh
           └─2062 sleep 1

 6月 19 09:02:19 localhost.localdomain systemd[1]: Started hello daemon.

ファイルへの書き込みが行われているか確認

[vagrant@localhost ~]$ tailf /tmp/hello.log
hello world
hello world
hello world
hello world
hello world

動いてました!

5. マシンを再起動して、サービスがちゃんと自動起動するか確認

$ sudo reboot

再起動後、マシン内でちゃんとhelloサービスが稼働していればOKです。

supervisordの代わりにsystemdで代用できそう

従来はコマンドのサービス化をするツールとしてはsupervisordやdaemontoolsなどが代表的でしたが、今後はSystemdだけでいけるかもしれません。

アプリケーションサービスなどもsystemd管理下へ
init だとクラッシュした時の再起動がないので、よくアプリケーションサービスなどを supervisord や daemontools を使って別に起動させていた方も多いと思いますが、基本的には systemd がこれらも含めてすべて見るようにするのが理想的ということです。cgroupを使ってプロセスツリー全体のリソースも管理でき、ログ管理機能もあるのでsystemd管理下に置くほうがシステム全体として整合性も取れるような印象です。
また従来はdaemonizeすることが多かったところsystemdではdaemontoolsのようにforegroundで実行するのが基本的なスタイルになるようです。Typeを変えればforkするデーモンにも対応可能です。

ぐぐってもあまり事例が出てこなかったのですが、すでに本番でsystemdによるサービス化をやってるよ、などがあればコメントで教えていただけると幸いです。

752
708
1

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
752
708