Linux配置开机自启动

先了解一下Linux一些脚本启动的顺序

/etc/rc.local -> /etc/profile -> 自定义脚本

通过系统提供的自启动脚本

(这种方式适合添加需要开机自启的应用程序,比如 redis、nginx 等等)

Linux 系统提供了一个开机启动的脚本( /etc/rc.local 或 /etc/rc.d/rc.local  这两个文件实际上是一个文件)

1、编辑 /etc/rc.local

vi /etc/rc.local

2、添加要执行的命令

注意:这里的执行命令都必须是全路径的,就算你添加到了 PATH 路径,自启动的时候,也是识别不到的(因为启动顺序是 /etc/rc.local -> /etc/profile )

例如,我这里添加的 redis 自启动:

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
# redis 启动命令/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf

TIPS:如何你是第一次使用该脚本文件,需要给脚本文件授权可执行,命令如下:

chmod +x /etc/rc.local

chmod 说明:

  • + 表示增加权限、- 表示取消权限、= 表示唯一设定权限
  • r 表示可读取,w 表示可写入,x 表示可执行

 

通过 chkconfig 添加自定义的启动脚本

(推荐用于linux开机自启动 java 程序)

1、切换到 init.d 目录

cd /etc/rc.d/init.d/

2、创建一个自启动脚本,这里就创建一个名为 autostart.sh 的脚本吧(名字自取)

touch autostart.sh    //创建 autostart.sh 脚本文件

3、编辑脚本

vi autostart.sh    //打开autostart.sh,进行编辑

4、编写脚本内容

(注意:为了防止脚本执行时,/etc/profile 里 export 的路径未生效,需要手动 source 一下,使配置立即生效)

#!/bin/sh
#chkconfig: 2345 80 90
#description:开机自动启动的脚本程序

# 防止在脚本运行的时候,没有加载 JDK 在 /etc/profile 的PATH添加的路径配置
if [ ${JAVA_HOME} == '']; then
 echo "source /etc/profile,使环境变量加载"
 source /etc/profile
fi

# 以下是脚本内容(自己根据需要进行编写)
# 待启动的application 路径
app_path_array=(
"/opt/eureka/"
"/opt/admin/"
)

for app_path in ${app_path_array[*]}; do
 # 这里,很重要,如果不切换到 jar 包的文件夹,那么下面脚本执行的路径就是根路径(/),这会导致 springboot 读取不到 jar包下的 ./config/ 文件夹,而去读取根目录下的配置 /config 文件夹
 cd ${app_path}
 # 找到以后缀 .jar 结尾的文件
 APP_NAME=`find -name *.jar `
 # 启动
 nohup java -jar ${APP_NAME} &
done

脚本文件内容说明:

  第一行 “#!/bin/sh” 告诉系统使用的shell

  第二行 “#chkconfig: 2345 80 90” 表示在2/3/4/5运行级别启动,启动序号(S80),关闭序号(K90);

    第三行 “#description”  表示的是服务的描述信息

 (注意:第一行和第二行必须写,否则后面使用 chkconfig 命令注册脚本到开机启动项时会报错 “服务 autostart.sh 不支持 chkconfig”)

 

扩展资料

  Linux启动级别:
  0   关机
  1   单用户
  2-5  多用户图形界面
  6   重启

5、给脚本赋可执行权限

chmod +x autostart.sh

6、将脚本添加到开机启动项中,并启动脚本

chkconfig --add autostart.sh
chkconfig autostart.sh on

 

另:如果启动的脚本未达到想要的效果,可以查看脚本执行的日志来分析

查看脚本执行日志的方式(以脚本 autostart.sh为例):

1)journalctl -u autostart

2) systemctl status autostart

通过自定义service服务

(很少用到这种方式,不做评价)

这种方式的启动,推荐一篇博客:https://blog.csdn.net/tianlong1569/article/details/100539200

以下是对上述博客的补充:

service脚本分为3个部分:[Unit] [Service] [Install]

1、Unit

Unit表明该服务的描述。最常用的场景就是定义该脚本执行的顺序,比如:

After=dbus.service

表示该service 在 dbus.service 之后再执行

 

2、Service

Service是脚本的关键部分,这一部分用于设置一些关键参数:

Type=forking: 后台运行模式

PIDFile: 存放PID文件的位置

ExecStart=xxx: 服务运行的具体执行命令

ExecReload=xxx: 服务重启的执行命令

EexcStop=xxx: 服务停止的执行命令

 

注:

该服务执行后,会有服务系统的日志

posted @ 2020-04-16 11:58  lkc9  阅读(1432)  评论(2编辑  收藏  举报