启用rc-local服务

编辑/lib/systemd/system/rc-local.service,在文件尾部添加以下内容

[Install]
WantedBy=multi-user.target  
Alias=rc-local.service

创建/etc/rc.local文件并输入以下内容

#!/bin/sh
# 
# 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.

# 在此输入开机运行的命令
date >> /tmp/test.log

exit 0
sudo chmod 755 /etc/rc.local
# 添加执行权限

systemctl daemon-reload
# 重载配置

systemctl enable rc-local.service
# 启用rc-local服务

设置开机启动

修改/etc/rc.local文件

exit 0上方插入你要开机执行的命令

# nodejs start
/etc/nodejs start

如果启动的程序需要在依赖的程序启动后启动,则可以在启动前添加延迟 sleep

# nodejs start
sleep 5
/etc/nodejs start

系统在启动时会自动执行rc.local文件,需要注意的是,系统默认以root用户执行命令 ,假如需要以其他用户执行命令,比如Python,因为用户piroot可能会安装不同的模块,使用root执行pi开发的程序可能会提示所需的模块不存在,一种方法是root用户安装相同模块,另一种方式是指定命令执行时的user

注意以其他用户身份执行的话,要给执行的命令内容加上引号

# python test.py start
cd /usr/local/etc/myproject
su pi -c 'nohup python3 -u /usr/local/etc/myproject/test.py &'

如果启动失败,可以通过 systemctl status rc-local.service 查看错误输出

使用进程守护软件

使用Supervisor、pm2等进程守护软件可以更好的监控程序的运行状态

使用Systemctl

这也是目前Linux唯一推荐的方式,查看如何配置service文件

https://www.cnblogs.com/-mrl/p/13831344.html

https://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html