CentOS新增自定義系統服務並設定開機自啟動
因為各種需要,需要在CentOS 啟動或重啟(reboot 命令)後,啟動常用服務。而不是手動一個個再啟動服務。
1.建立服務檔案
系統服務新增路徑: /usr/lib/systemd/system/
服務安裝路徑: /usr/local/xxxx
依次新增檔案 xxxx.service 服務,並儲存
1.nginx.service , nginx 的安裝路徑為: /usr/local/nginx/
[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
2.mysql.service , Mysql 的安裝路徑為: /usr/local/mysql/
[Unit] Description=mysql After=network.target remote-fs.target nss-lookup.target [Service] Type=forking ExecStart=/usr/local/mysql/support-files/mysql.server start #ExecReload=/usr/local/mysql/support-files/mysql.server restart #ExecStop=/usr/local/mysql/support-files/mysql.server stop #PrivateTmp=true [Install] WantedBy=multi-user.target
3.php-fpm.service , php 的安裝路徑為: /usr/local/php/, php-fpm 的路徑為: /usr/local/php/sbin/php-fpm
[Unit]
Description=php
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/php/sbin/php-fpm
[Install]
WantedBy=multi-user.target
4.redis.service , redis 的安裝路徑為: /usr/local/redis/
[Unit]
Description=Redis
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/redis /etc/redis.conf
ExecStop=kill -INT `cat /tmp/redis.pid`
User=www
Group=www
[Install]
WantedBy=multi-user.target
5.supervisord.service , supervisord的安裝路徑為: /usr/bin/supervisord/
[Unit]
Description=Process Monitoring and Control Daemon
After=rc-local.service
[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
檔案內容解釋
[Unit]:服務的說明
Description:描述服務
After:描述服務類別
[Service]服務執行引數的設定
Type=forking是後臺執行的形式
ExecStart為服務的具體執行命令
ExecReload為重啟命令
ExecStop為停止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:啟動、重啟、停止命令全部要求使用絕對路徑
[Install]服務安裝的相關設定,可設定為多使用者
2.儲存目錄
以755的許可權儲存在目錄: /usr/lib/systemd/system
3.設定開機自啟動
可在任意目錄下執行
systemctl enable nginx.service
4.其他命令
以下以nginx 為例
啟動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