生产环境中添加以非root用户进行nginx、tomcat、nodejs等开机自启动

一、添加开机自启服务
在centos7中添加开机自启服务非常方便,只需要两条命令(以nginx为例):
# systemctl enable nginx.service #设置nginx服务为自启动服务
# sysstemctl start  nginx.service #启动nginx服务
 
二、添加开机自启脚本
在centos7中增加脚本有两种常用的方法,以脚本autostart.sh为例:
# cat autostart.sh
 
#!/bin/bash
# description: 开机自启脚本
/opt/tomcat/bin/startup.sh  #启动tomcat
 
方式一:
1、赋予脚本可执行权限(/opt/script/autostart.sh是你的脚本路径)
# chmod a+x /opt/script/autostart.sh
 
2、打开/etc/rc.d/rc.local文件,在末尾增加如下内容
/opt/script/autostart.sh
 
3、在centos7中,/etc/rc.d/rc.local的权限被降低了,所以需要执行如下命令赋予其可执行权限
# chmod a+x /etc/rc.d/rc.local
 
方式二:
1、将脚本移动到/etc/rc.d/init.d目录下
# cp  /opt/script/autostart.sh /etc/rc.d/init.d
 
2、增加脚本的可执行权限
# chmod a+x  /etc/rc.d/init.d/autostart.sh
 
3、添加脚本到开机自动启动项目中
# cd /etc/rc.d/init.d
# chkconfig --add autostart.sh
# chkconfig autostart.sh on
 
 
 
直接使用# sudo -u app sh /opt/tomcat/bin/startup.sh   无法正常启动tomcat,因为未正常读取到java的环境变量,即便是在app用户家目录下.bash_profile定义java环境变量仍然是无法正常启动。
解决办法:
在startup.sh中增加java环境变量,则可解决问题。
 
如果不使用 sudo -u app bash /opt/tomcat/bin/startup.sh,使用 su - app -c "bash /opt/tomcat/bin/startup.sh" 可正常启动。
 
坑:
centos7系统的/etc/rc.d/rc.local默认没有执行权限,所以如果将开机自启动的命令写在该处,这需增加执行权限
# chmod a+x /etc/rc.d/rc.local
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/wplvqj/p/10537026.html