如果只是添加一條開機啟動的命令:
1. chmod +x /etc/rc.d/rc.local
2. 將命令寫到 /etc/rc.d/rc.local 這個文件中
3. reboot 🌼
一、添加開機自啟服務
在CentOS 7中添加開機自啟服務非常方便,只需要兩條命令(以Jenkins為例):
systemctl enable jenkins.service #設置jenkins服務為自啟動服務
sysstemctl start jenkins.service #啟動jenkins服務
二、添加開機自啟腳本
在centos7中增加腳本有兩種常用的方法,以腳本autostart.sh為例:
#!/bin/bash
#description:開機自啟腳本
/usr/local/tomcat/bin/startup.sh #啟動tomcat
方法一
1、賦予腳本可執行權限(/opt/script/autostart.sh是你的腳本路徑)
chmod +x /opt/script/autostart.sh
2、打開/etc/rc.d/rc.local或/etc/rc.local文件,在末尾增加如下內容
su - user -c '/opt/script/autostart.sh'
3、在centos7中,/etc/rc.d/rc.local的權限被降低了,所以需要執行如下命令賦予其可執行權限
chmod +x /etc/rc.d/rc.local
方法二
1、將腳本移動到/etc/rc.d/init.d目錄下
mv /opt/script/autostart.sh /etc/rc.d/init.d
2、增加腳本的可執行權限
chmod +x /etc/rc.d/init.d/autostart.sh
3、添加腳本到開機自動啟動項目中
cd /etc/rc.d/init.d
chkconfig --add autostart.sh
chkconfig autostart.sh on
二、自定義服務文件,添加到系統服務,通過Systemctl管理
1.寫服務文件
[Unit]:服務的說明
Description:描述服務
After:描述服務類別
[Service]服務運行參數的設置
Type=forking是后台運行的形式
ExecStart為服務的具體運行命令
ExecReload為重啟命令
ExecStop為停止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:啟動、重啟、停止命令全部要求使用絕對路徑
[Install]服務安裝的相關設置,可設置為多用戶
示例:nginx.service
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
[Install]
WantedBy=multi-user.target
redis.service
[Unit]
Description=Redis
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/bin/redis-server /etc/redis.conf
ExecStop=kill -INT `cat /tmp/redis.pid`
User=www
Group=www
[Install]
WantedBy=multi-user.target
2.保存目錄
以754的權限保存在目錄:
/usr/lib/systemd/system
3.設置開機自啟動
任意目錄下執行
systemctl enable nginx.service
4.其他命令
啟動nginx服務
systemctl start nginx.service
設置開機自啟動
systemctl enable nginx.service
停止開機自啟動
systemctl disable nginx.service
查看服務當前狀態
systemctl status nginx.service
重新啟動服務
systemctl restart nginx.service
查看所有已啟動的服務
systemctl list-units --type=service