Linux使用systemctl自啟動服務
systemctl
指令碼存放在:/usr/lib/systemd/
,有系統(system
)和使用者(user
)之
分,需要開機不登陸就能執行的程式,存在系統服務裡,即:/usr/lib/systemd/system
目錄下.
每一個服務以.service
結尾,一般會分為3部分:[Unit]
、[Service]
和[Install]
[Unit]
部分主要是對這個服務的說明,內容包括Description和After,Description 用於描述服務,
After用於描述服務類別
[Service]部分是服務的關鍵,是服務的一些具體執行引數的設定.
Type=forking是後臺執行的形式,
User=users是設定服務執行的使用者,
Group=users是設定服務執行的使用者組,
PIDFile為存放PID的檔案路徑,
ExecStart為服務的具體執行命令
ExecReload為重啟命令
ExecStop為停止命令,
PrivateTmp=True表示給服務分配獨立的臨時空間
[Service]
注意:[Service]部分的啟動、重啟、停止命令全部要求使用絕對路徑,使用相對路徑則會報
錯!
[Install]
[Install]部分是服務安裝的相關設定,可設定為多使用者的
首先,使用systemctl start [ 服務名(也是檔名) ] 可測試服務是否可以成功執行,如果不能執行 則可以使用systemctl status [ 服務名(也是檔名) ]檢視錯誤資訊和其他服務資訊,然後根據報
錯進行修改,直到可以start,如果不放心還可以測試restart和stop命令。
接著,只要使用systemctl enable xxxxx就可以將所編寫的服務新增至開機啟動即可。
[Unit] Description=springboot webapp After=springboot-webapp.service [Service] WorkingDirectory=/home/hlooc/app/springboot-webapp Type=forking Environment="JAVA_HOME=/home/hlooc/app/jdk1.8.0_202" Environment="PATH=/home/hlooc/app/jdk1.8.0_202/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/hlooc/.local/bin:/home/hlooc/bin" Environment="CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar" User=hlooc Group=hlooc PIDFile=/home/hlooc/app/springboot-webapp/upp.pid ExecStart=/home/hlooc/app/springboot-webapp/start.sh ExecStop=/home/hlooc/app/springboot-webapp/stop.sh PrivateTmp=true [Install] WantedBy=multi-user.target
服務操作
新增可執行許可權:
chmod 754 /usr/lib/systemd/system/springboot-webapp.service
設定為開機自啟動:
systemctl enable springboot-webapp.service
常用指令(以springboot-webapp服務為例):
啟動某服務
systemctl start springboot-webapp.service
停止某服務
systemctl stop springboot-webapp.service
重啟某服務
service springboot-webapp restart
systemctl restart springboot-webapp.service
使某服務自動啟動(如springboot-webapp服務)
systemctl enable springboot-webapp.service
使某服務不自動啟動
systemctl disable springboot-webapp.service
檢查服務狀態
systemctl status springboot-webapp.service (服務詳細資訊)
systemctl is-active springboot-webapp.service(僅顯示是否Active)
顯示所有已啟動的服務
systemctl list-units --type=service