hoge-hogeoのひきこもごも

インフラエンジニアだけど形を持ったインフラを触ったことがない人の徒然

Systemctlのサービスを作る

参考

enakai00.hatenablog.com

enakai00.hatenablog.com

■serviceファイル作成

vim /usr/lib/systemd/system/nginx.service
############################################
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIFfile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/bin/kill -s HUP $MAINPID
ExecStop=/usr/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
  
############################################

  
■list-unit-filesに認識されているか確認
$ sudo systemctl list-unit-files --type=service|grep nginx
nginx.service                     disabled
  
■有効化する
$ sudo systemctl enable nginx.service
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

確認

■起動確認
$ sudo systemctl start nginx.service
$ ps -ef|grep ngin
root      9887     1  0 16:29 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     9888  9887  0 16:29 ?        00:00:00 nginx: worker process
root      9971 32341  0 16:29 pts/1    00:00:00 grep --color=auto ngin
  
■systemctl statusで確認
□確認項目
・PIDがpsで引いたものと合致しているか
・ExecStart, ExecStartPreがそれぞれ動いたか
  
$ sudo systemctl status nginx.service
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2018-04-16 16:29:35 JST; 42s ago
     Docs: http://nginx.org/en/docs/
  Process: 9886 ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
  Process: 9883 ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 9887 (nginx)
   CGroup: /system.slice/nginx.service
       ├─9887 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
       └─9888 nginx: worker process
Apr 16 16:29:35 ip-10-56-79-94.ap-northeast-1.compute.internal systemd[1]: Starting nginx - high performance web server...
Apr 16 16:29:35 ip-10-56-79-94.ap-northeast-1.compute.internal nginx[9883]: nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
Apr 16 16:29:35 ip-10-56-79-94.ap-northeast-1.compute.internal nginx[9883]: nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
Apr 16 16:29:35 ip-10-56-79-94.ap-northeast-1.compute.internal systemd[1]: Started nginx - high performance web server.
Hint: Some lines were ellipsized, use -l to show in full.
  
■停止確認
$ sudo systemctl stop nginx.service
$ ps -ef|grep ngin
root     14815 32341  0 16:34 pts/1    00:00:00 grep --color=auto ngin