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      #查看所有已啟動的服務

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM