CentOS8建立開機啟動服務

獵手家園發表於2021-06-10

1、以開機啟動EMQX為例。

2、建立開機啟動指令碼

[root@centos8 startup]$ vim emqx-startup.sh

#!/bin/bash
#description: emqx啟動服務

#獲取傳入命令
cmd=$1

#獲取emqx程式ID
pid=`ps -ef | grep run_erl | grep /usr/local/emqx/bin/emqx | awk '{print $2}'`

if [ ! $cmd ]; then
  echo "please input cmd {start|restart|stop|status}"
  exit
fi

#寫入日誌
echo "-----------------------------------------------------------------------------"  >> /root/startup/emqx.log
echo -e "`date +%Y/%D/%H:%M` emqx exec $cmd start." >> /root/startup/emqx.log

if [ $cmd == 'start' ]; then
  if [ ! $pid ]; then
    /usr/local/emqx/bin/emqx start
  else
    echo "emqx is running, pid is $pid."
  fi
fi

if [ $cmd == 'stop' ]; then
  if [ $pid ]; then
    /usr/local/emqx/bin/emqx stop
  else
    echo "emqx is already stop."
  fi
fi

if [ $cmd == 'status' ]; then
   /usr/local/emqx/bin/emqx_ctl status
fi

echo -e "`date +%Y/%D/%H:%M` emqx exec $cmd end." >> /root/startup/emqx.log
echo " " >> /root/startup/emqx.log

 

2、賦予指令碼可執行許可權

chmod +x emqx-startup.sh

 

3、驗證指令碼

[root@centos8 startup]$ ./emqx-startup.sh start

[root@centos8 startup]$ ./emqx-startup.sh stop

[root@centos8 startup]$ ./emqx-startup.sh status

 

4、進入進入systemd配置檔案目錄建立service服務

[root@centos8 ~]$ cd /usr/lib/systemd/system

[root@centos8 system]$ vim emqx-autorun.service

[Unit]
Description=emqx for auto start
Wants=network-online.target

[Service]
User=root
Type=forking
ExecStart=/usr/bin/bash /root/startup/emqx-startup.sh start
ExecStop=/usr/bin/bash /root/startup/emqx-startup.sh stop

[Install]
WantedBy=multi-user.target

 

5、重新載入systemd配置

[root@centos8 ~]# systemctl daemon-reload

 

6、新增開機自啟動

[root@centos8 system]# systemctl enable emqx-autorun.service
Created symlink /etc/systemd/system/multi-user.target.wants/emqx-autorun.service → /usr/lib/systemd/system/emqx-autorun.service.

 

7、啟動停止測試

[root@centos8 system]# systemctl start emqx-autorun
[root@centos8 system]# systemctl status emqx-autorun

 

8、重啟驗證

 

關於systemd配置說明,傳送門:https://www.cnblogs.com/hunttown/p/14872185.html

Systemd常用的幾個操作命令,傳送門:https://www.cnblogs.com/hunttown/p/15111186.html 

 

相關文章