systemdにサービスを追加

2017/7/4


rc.local

以前は/etc/rc.localにいろいろ追記していたが、systemdではこれが使えないらしい。

systemdではどうすればよいのか

  1. シェルスクリプトを用意
    実行するコマンド他でもいいが、めんどうな記述が多いのでスクリプトをつくる
    #!/bin/bash
    #/opt/ntpdate.sh
    ntpdate 10.1.2.3
  2. Unit定義ファイルをつくる
    /etc/systemd/system/以下にUnit定義を/etc/systemd/system/ntpdate.serviceとしてつくる。ntpdate.serviceは、後にsystemctlコマンドで参照するので、名称をよく考えること。 /etc/systemd/system/ntpdate.service
    [Unit]
    Description = ntpdate 
    #ntpdate の後にntpを起動し、ntpと同時に起動できない
    #conflicts=ntp.service
    #Before=ntp.service
    
    [Service]
    ExecStart = /opt/ntpdate.sh
    Restart = no
    #Restart = no リブート後1回だけ実行
    #Restart = always にすると5秒毎に/opt/ntpdate.shを実行する
    Type = simple
    
    [Install]
    WantedBy = multi-user.target
    
  3. ntpdate.serviceを確認
    systemctl list-unit-files --type=service|grep ntpdate

    サービスを登録する。次回リブート時に自動起動する。
    systemctl enable ntpdate
    systemctl list-unit --type=service |grep ntpdate

    サービスをマニュアルで起動し動作確認する
    systemctl start ntpdate

  4. 操作方法
    systemctl list-units
    systemctl list-units --type=service
    systemctl list-unit-files
    systemctl enable ntpdate
    systemctl disable ntpdate
    systemctl start ntpdate
    systemctl stop ntpdate
    systemctl restart ntpdate
    systemctl status ntpdate
    systemctl list-dependencies ntpdate
    systemctl list-dependencies ntpdate --all

[参照]
めもめも http://enakai00.hatenablog.com/entry/20130914/1379146157
Linux女子部 systemd徹底入門! https://www.slideshare.net/enakai/linux-27872553
Qiita Systemdを使ってさくっと自作コマンドをサービス化してみる http://qiita.com/DQNEO/items/0b5d0bc5d3cf407cb7ff