最近一个项目部署需要开启一个web服务,这个需要人工启动才可以,一旦电脑重启就会导致该服务关闭,如果后面忘记启动或者是维护就会导致前端项目无法访问到后台数据,所以最好的解决办法就是做一个自启动的脚本任务,将这个任务加入到Linux的系统启动中,这样系统初始化完成后可以直接自动执行我们自定义的脚本任务,接下来记录一下整个实践过程。
网上其实有很多讲解的文章,这里我选择的方式是修改 /etc/rc.local 文件来实现我的需求。
首先看下原始文件的内容,如下所示:
#!/bin/sh -e## rc.local## This script is executed at the end of each multiuser runlevel.# Make sure that the script will "exit 0" on success or any other# value on error.## In order to enable or disable this script just change the execution# bits.## By default this script does nothing.# Generate the SSH keys if non-existentif [ ! -f /etc/ssh/ssh_host_rsa_key ]then# else ssh service start in dpkg-reconfigure will failsystemctl stop ssh.socket||true# dpkg-reconfigure openssh-serverdpkg --force-confdef --force-confold --configure -afiexit 0
这里我们项目中使用到的web服务为github上面的开源项目,地址在这里。简介如下所示:
我们可以从这里下载可以直接使用的可执行文件,根据自己的系统平台对应选择即可, 支持Linux、arm和windows,还是很强大的。
我们下周的是红框里面对应的版本,系统是Ubuntu16.04版本的。
下载后处理命令如下:
unzip ran_linux_amd64.zipchmod +x ran_linux_amd64nohup ./ran_linux_amd64 -l -p 8888 >> ran.out &
执行完成之后就已经成功启动了web服务了,下面看下日志输出:
可以看到ran服务已经启动了,访问端口是8888,端口可以根据自己的需要去修改。
我们今天的需求就是需要将上面的后台运行ran的命令配置为Linux的自启动脚本任务。
首先创建ran的执行sh脚本,创建命令如下:
vim start_ran.sh
该脚本内容如下:
#!/bin/bash### BEGIN INIT INFO# Provides:# Required-Start: $local_fs $network# Required-Stop:$local_fs# Default-Start:2 3 4 5# Default-Stop:0 1 6# Short-Description: tomcat service# Description: tomcat service daemon### END INIT INFOcd /path/to/ran_linux_amd64nohup ./ran_linux_amd64 -l -p 8888 >> ran.out &
之后修改执行权限:
chmod +x start_ran.sh
接着可以简单地直接进行一下测试:
sh start_ran.sh
会发现ran服务已经成功执行了,接下来就开始配置自启动服务。
vim /etc/rc.local
加入刚刚编写的执行脚本,内容变为下面:
#!/bin/sh -e## rc.local## This script is executed at the end of each multiuser runlevel.# Make sure that the script will "exit 0" on success or any other# value on error.## In order to enable or disable this script just change the execution# bits.## By default this script does nothing.# Generate the SSH keys if non-existentif [ ! -f /etc/ssh/ssh_host_rsa_key ]then# else ssh service start in dpkg-reconfigure will failsystemctl stop ssh.socket||true# dpkg-reconfigure openssh-serverdpkg --force-confdef --force-confold --configure -afish /path/to/start_ran.shexit 0
这里尤其要注意的是 sh /path/to/start_ran.sh 一定要写在 exit 0 的上面,之前我就是在这里卡住了,很多博文里面说的sh /path/to/start_ran.sh 要卸载rc.local最后一行,这句话其实是不对的,要注意。
修改完成后,重新赋权:
chmod 777 rc.local
这一步同样是很重要的,给可执行权限。
最后就可以重启了
sudo reboot
重启后查找指定的进程查看启动状态即可:
ps -aux|grep ran_linux_amd64
亲测可行,结果截图如下:
记录一下备忘,同时也希望帮到有同样需要的人。
如果觉得《Ubuntu16.04 设置自启动脚本 系统重启自动执行自定义脚本任务》对你有帮助,请点赞、收藏,并留下你的观点哦!