CentOS8創建開機啟動服務


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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM