工作中部署的開源軟件很多需要進到程序的bin目錄執行start,每次都需要進入目錄,而且不便於管理。將這類服務或者自開發的程序添加到systemctl管理起來就方便很多。
一、systemd配置文件
systemd 默認從目錄/etc/systemd/system/讀取配置文件,但里面存放的大部分文件都是符號鏈接,指向目錄/usr/lib/systemd/system/,真正的腳本存放在這個目錄。
systemctl enable 命令用於在上面兩個目錄之間,建立符號鏈接關系。
/usr/lib/systemd/下有系統(system)和用戶(user)之分,需要開機啟動的服務放在/usr/lib/systemd/system目錄下.
CentOS7的每一個服務以.service結尾,一般會分為3部分:[Unit]、[Service]和[Install]
[Unit]部分主要是對這個服務的說明
Description 用於描述服務
After 用於描述服務類別
[Service]是服務的一些具體運行參數的設置.
Type=forking 是后台運行的形式,
User=users 是設置服務運行的用戶,
Group=users 是設置服務運行的用戶組,
PIDFile 為存放PID的文件路徑,
ExecStart 為服務的具體運行命令,
ExecReload 為重啟命令,
ExecStop 為停止命令,
PrivateTmp=True 表示給服務分配獨立的臨時空間
注意:[Service]部分的啟動、重啟、停止命令全部要求使用絕對路徑,使用相對路徑則會報錯!
[Install]是服務安裝的相關設置,可設置為多用戶
二、示例
添加廠商服務
tomcat
vim /usr/lib/systemd/system/tomcat.service
[Unit]
Description=java tomcat project
After=tomcat.service
[Service]
Type=forking
User=users
Group=users
PIDFile=/usr/local/tomcat/tomcat.pid
ExecStart=/usr/local/tomcat/bin/startup.sh
ExecReload=
ExecStop=/usr/local/tomcat/bin/shutdown.sh
PrivateTmp=true
[Install]
WantedBy=multi-user.target
chmod 754 /usr/lib/systemd/system/tomcat.service
systemctl enable tomcat.service
systemctl is-active tomcat.service
systemctl status tomcat.service
添加自開發服務
和廠商服務一樣只是自開發服務需要自己寫好啟動腳本和關閉腳本
啟動腳本
vim /home/services/mytestsvr-service/start.sh
#!/bin/sh
export JAVA_HOME=/usr/local/java/jdk1.8.0_91
export PATH=$JAVA_HOME/bin:$PATH
cd /home/services/mytestsvr-service
java -jar ./lib/mytestsvr-service.jar &
echo $! > /var/run/mytestsvr-service.pid
關閉腳本
vim /home/services/mytestsvr-service/stop.sh
#!/bin/sh
PID=$(cat /var/run/mytestsvr-service.pid)
kill -9 $PID
systemctl腳本
vim /usr/lib/systemd/system/**mytestsvr**.service
[Unit]
Description=the service description
After=network.target
[Service]
Type=forking
ExecStart=/home/services/mytestsvr-service/start.sh
ExecStop=/home/services/mytestsvr-service/stop.sh
[Install]
WantedBy=multi-user.target
chmod 754 /usr/lib/systemd/system/mytestsvr.service
systemctl enable mytestsvr.service
systemctl is-active mytestsvr.service
systemctl status mytestsvr.service