Linux——开机自启动

 

前言

有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务,这里介绍CentOS开机自启动的几种方法。

 

CentOS 6.X

方式一. 修改/etc/rc.d/rc.local脚本

1、在 /etc/rc.d/rc.local 文件的内容未尾加入相关命令(可以是启动命令,也可以是启动脚本文件)

  • 加入启动命令
vim /etc/rc.d/rc.local
/usr/local/service/redis-2.8.3/src/redis-server --port 6379 &

注:切忌 命令行末尾要加上 [  &  ] 符号, 表示任务在后台执行。否则会阻塞后面添加的命令行执行。

  • 加入启动脚本文件

首先创建shell文件filebeat.sh:

#!/bin/bash
nohup /opt/elk/filebeat-7.14.0-linux-x86_64/filebeat -e -c /opt/elk/filebeat-7.14.0-linux-x86_64/filebeat.yml >/opt/elk/filebeat-7.14.0-linux-x86_64/filebeat.log 2>&1 &

然后给shell赋执行权限:

chmod +x filebeat.sh

最后加入启动脚本文件:

vim /etc/rc.d/rc.local
/opt/elk/filebeat-7.14.0-linux-x86_64/filebeat.sh

2、给 rc.local 赋执行权限

chmod +x /etc/rc.d/rc.local

 

方式二. chkconfig

1. 编写脚本autostart.sh(这里以开机启动redis服务为例),脚本内容如下:

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

# 开启redis服务 端口为6379
/usr/local/service/redis-2.8.3/src/redis-server --port 6379 &

脚本第一行 “#!/bin/sh” 告诉系统使用的shell; 
脚本第二行 “#chkconfig: 2345 80 90” 表示在2/3/4/5运行级别启动,启动序号(S80),关闭序号(K90); 
脚本第三行 表示的是服务的描述信息

注意: 第二行和第三行必写,负责会出现如“服务 autostart.sh 不支持 chkconfig”这样的错误。

2. 将写好的autostart.sh脚本移动到/etc/rc.d/init.d/目录下

3. 给脚本赋可执行权限

cd /etc/rc.d/init.d/
chmod +x autostart.sh

4. 添加脚本到开机自动启动项目中

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

 

CentOS 7.X

1. 进入自启动目录:

cd /lib/systemd/system
vim filebeat.service

2. 编写filebeat.service:

[Unit]
Description=filebeat
Wants=network-online.target
After=network-online.target

[Service]
User=root
ExecStart=/opt/elk/filebeat-7.14.0-linux-x86_64/filebeat -e -c /opt/elk/filebeat-7.14.0-linux-x86_64/filebeat.yml  #/opt/elk/filebeat-7.14.0-linux-x86_64为filebeat的安装目录
Restart=always  #设置为掉线自动重启,进程强制杀掉后会自动重新启动

[Install]
WantedBy=multi-user.target

3. 启动验证:

systemctl daemon-reload             #加载配置
systemctl enable filebeat               #设置开机自启动
systemctl disable filebeat              #停止开机自启动

systemctl start filebeat                #启动filebeat服务
systemctl restart filebeat             #重新启动服务

systemctl status filebeat               #查看服务当前状态
systemctl list-units --type=service      #查看所有已启动的服务

 

posted on 2021-10-12 16:17  曹伟雄  阅读(1172)  评论(0编辑  收藏  举报

导航