1:背景描述
最近根據工作需要,需要服務實現開機自啟動的效果,因為平時只使用過nohup的后臺掛起操作,很少接觸開機,鏡像裝機服務自啟動的功能,因此,這里簡單記錄一下。
注意,開機自啟動和上面的hohup的表現不一樣,開機自啟動保證了系統重啟,新開的機器都會自動運行該服務,而nohup只是后臺掛起,服務伴隨系統的生命周期,當
機器重啟,服務自動停止,不會自動運行
2:實現步驟
(1)進入到/etc/systemd/system目錄下,
cd /etc/systemd/system
里面很多軟鏈接,如下
這里有目錄也有文件,文件的后綴都是.service
,目錄內的文件也是.service
的文件,都是系統命令可以直接啟動systemctl
。
(2)編寫service文件
這里我以一個test.py文件為例,想要實現它的開機自啟動,這里可以仿照其中的一個.service文件內容為例,做了如下修改。
源.service文件
[Unit]
Description=API Server <-----------------服務描述需要改
After=syslog.target network.target <-----------------------設置你要自啟動服務要在哪些服務啟動之后啟動,比如網絡狀態[Service]
Type=simple
NotifyAccess=all
TimeoutStartSec=0
TimeoutStopSec=10min
Restart=always <------------------------這個配置設置了后,即便人為殺掉進程,也會自動重啟服務
User=api
ExecStart=/usr/bin/api --config-file /etc/api/api.conf <------------啟動服務時的執行命令[Install]
WantedBy=multi-user.target
按照上面描述的需要修改的內容,新建一個叫 test.service的文件,保存后退出
[Unit]
Description= Test Print Hello World
After=syslog.target network.target[Service]
Type=simple
NotifyAccess=all
TimeoutStartSec=0
TimeoutStopSec=10min
Restart=always
User=root
ExecStart=python3 /home/lwh/test.py[Install]
WantedBy=multi-user.target
(3)設置自啟動
創建軟鏈接,允許systemctl啟動
systemctl enable test
結果如下
root@vm10-0-0-75:/etc/systemd/system# systemctl enable test
Created symlink /etc/systemd/system/multi-user.target.wants/test.service → /etc/systemd/system/test.service.
啟動test服務
systemctl start test
查看服務進程
root@vm10-0-0-75:/etc/systemd/system# ps aux | grep python
root 12987 0.0 0.0 14904 8488 ? Ss 17:34 0:00 /usr/bin/python3 /home/lwh/test.py
root 12999 0.0 0.0 6432 652 pts/0 S+ 17:34 0:00 grep --color=auto python
說明啟動成功
(4)重啟系統驗證
reboot -n
這里 -n 表示跳過重啟時的init步驟
重啟后再次查看進程如下結果
說明設置自啟動成功
3:取消開機自啟動
systemctl stop test.service # 停止服務
systemctl disable test.service #清除軟鏈接
rm -f test.service # 刪除寫的自啟動文件