ubuntu15.4、16.4、17.4設置nginx自啓動
1.建立服務文件
文件路徑
vim /usr/lib/systemd/system/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
文件說明
[Unit]:服務的說明
Description:描述服務
After:依賴,當依賴的服務啓動之後再啓動自定義的服務
[Service]服務運行參數的設置
Type=forking是後臺運行的形式
ExecStart爲服務的具體運行命令(需要根據路徑適配)
ExecReload爲重啓命令(需要根據路徑適配)
ExecStop爲停止命令(需要根據路徑適配)
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:啓動、重啓、停止命令全部要求使用絕對路徑
[Install]服務安裝的相關設置,可設置爲多用戶
Type
-
Type=simple(默認值):systemd認爲該服務將立即啓動。服務進程不會fork。如果該服務要啓動其他服務,不要使用此類型啓動,除非該服務是socket激活型。
-
Type=forking:systemd認爲當該服務進程fork,且父進程退出後服務啓動成功。對於常規的守護進程(daemon),除非你確定此啓動方式無法滿足需求,使用此類型啓動即可。使用此啓動類型應同時指定 PIDFile=,以便systemd能夠跟蹤服務的主進程。
-
Type=oneshot:這一選項適用於只執行一項任務、隨後立即退出的服務。可能需要同時設置 RemainAfterExit=yes使得systemd在服務進程退出之後仍然認爲服務處於激活狀態
-
Type=notify:與 Type=simple相同,但約定服務會在就緒後向systemd發送一個信號。這一通知的實現由 libsystemd-daemon.so提供。
-
Type=dbus:若以此方式啓動,當指定的 BusName 出現在DBus系統總線上時,systemd認爲服務就緒。
PIDFile : pid文件路徑
ExecStartPre :啓動前要做什麼,上文中是測試配置文件 -t
2.保存目錄
/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