代码改变世界

CentOS8创建开机启动服务

  猎手家园  阅读(5297)  评论(0编辑  收藏  举报

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 

 

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示