systemctl 設置自定義服務管理(以nginx爲例)

1.創建服務文件

文件路徑nginx

vim /usr/lib/systemd/system/nginx.service

文件內容web

[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

文件說明vim

[Unit]:服務的說明
Description:描述服務
After:依賴,當依賴的服務啓動以後再啓動自定義的服務

[Service]服務運行參數的設置
Type=forking是後臺運行的形式
ExecStart爲服務的具體運行命令
ExecReload爲重啓命令
ExecStop爲中止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:啓動、重啓、中止命令所有要求使用絕對路徑

[Install]服務安裝的相關設置,可設置爲多用戶
Type
  • Type=simple(默認值):systemd認爲該服務將當即啓動。服務進程不會fork。若是該服務要啓動其餘服務,不要使用此類型啓動,除非該服務是socket激活型。socket

  • Type=forking:systemd認爲當該服務進程fork,且父進程退出後服務啓動成功。對於常規的守護進程(daemon),除非你肯定此啓動方式沒法知足需求,使用此類型啓動便可。使用此啓動類型應同時指定 PIDFile=,以便systemd可以跟蹤服務的主進程。測試

  • Type=oneshot:這一選項適用於只執行一項任務、隨後當即退出的服務。可能須要同時設置 RemainAfterExit=yes使得systemd在服務進程退出以後仍然認爲服務處於激活狀態rest

  • Type=notify:與 Type=simple相同,但約定服務會在就緒後向systemd發送一個信號。這一通知的實現由 libsystemd-daemon.so提供。code

  • Type=dbus:若以此方式啓動,當指定的 BusName 出如今DBus系統總線上時,systemd認爲服務就緒。orm

PIDFile : pid文件路徑
ExecStartPre :啓動前要作什麼,上文中是測試配置文件 -t

2.保存目錄

/usr/lib/systemd/system

3.設置開機自啓動

任意目錄下執行server

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
相關文章
相關標籤/搜索