1. 程式人生 > >新增服務到開機自動啟動(centos7開機自啟動nginx,php-fpm)

新增服務到開機自動啟動(centos7開機自啟動nginx,php-fpm)

說明

參考網路上其他人文章。將他人技術文章親自測試並總結補充。

開機自啟動nginx,php-fpm(其他服務類似)

centos 7以上是用Systemd進行系統初始化的,Systemd 是 Linux 系統中最新的初始化系統(init),它主要的設計目標是克服 sysvinit 固有的缺點,提高系統的啟動速度。 Systemd服務檔案以.service結尾,比如現在要建立nginx為開機啟動,如果用yum install命令安裝的,yum命令會自動建立nginx.service檔案,直接用命令systemcel enable nginx.service設定開機啟動即可。

systemcel enable nginx.service

原始碼安裝的手動建立nginx.service服務檔案

  1. 在系統服務目錄裡建立nginx.service檔案
    vi /lib/systemd/system/nginx.service
    寫入以下內容(路徑改成自己的)
    [Unit]
    Description=nginx
    After=network.target
    [Service]
    Type=forking
    ExecStart=/www/lnmp/nginx/sbin/nginx -c /www/lnmp/nginx/conf/nginx.conf
    ExecReload=/www/lnmp/nginx/sbin/nginx -s reload
    ExecStop=/www/lnmp/nginx/sbin/nginx -s quit
    PrivateTmp=true
    [Install]
    WantedBy=multi-user.target
    在系統服務目錄裡建立php-fpm.service檔案
    vi /lib/systemd/system/php-fpm.service
    寫入以下內容(路徑改成自己的)
    [Unit]
    Description=php-fpm
    After=network.target
    [Service]
    Type=forking
    ExecStart=/www/lnmp/php/sbin/php-fpm
    ExecStop=/bin/pkill -9 php-fpm
    PrivateTmp=true
    [Install]
    WantedBy=multi-user.target

    [Unit]:服務的說明
    Description:描述服務
    After:描述服務類別
    [Service]服務執行引數的設定
    Type=forking是後臺執行的形式
    ExecStart為服務的具體執行命令
    ExecReload為重啟命令
    ExecStop為停止命令
    PrivateTmp=True表示給服務分配獨立的臨時空間
    注意:[Service]的啟動、重啟、停止命令全部要求使用絕對路徑
    [Install]執行級別下服務安裝的相關設定,可設定為多使用者,即系統執行級別為3

  2. 測試並加入開機自啟
    先關閉nginx,php-fpm
    使用以下命令開啟
    systemctl start nginx.service             #如果服務是開啟狀態,使用此命令會啟動失敗。
    systemctl start php-fpm.service
    開啟成功,將服務加入開機自啟
    systemctl enable nginx.service                #注意後面不能跟空格
    systemctl enable php-fpm.service
    重啟伺服器,檢視是否啟動
    shutdown -r now        #重啟
    systemctl list-units --type=service           #檢視執行的服務

其他命令

systemctl start nginx.service              #啟動nginx服務
systemctl enable nginx.service             #設定開機自啟動
systemctl disable nginx.service            #停止開機自啟動
systemctl status nginx.service             #檢視服務當前狀態
systemctl restart nginx.service           #重新啟動服務
systemctl list-units --type=service        #檢視所有已啟動的服務