centos 7開機自啓動有兩種不一樣的設置方式,若是是yum直接安裝的軟件服務,則直接開啓便可,若是是源碼編譯安裝的,則須要在系統服務(system)建立service文件,而後才能設置。
centos 7以上是用Systemd進行系統初始化的,Systemd 是 Linux 系統中最新的初始化系統(init),它主要的設計目標是克服 sysvinit 固有的缺點,提升系統的啓動速度。關於Systemd的詳情介紹在這裏。css
Systemd服務文件以.service
結尾,好比如今要創建nginx爲開機啓動,若是用yum install
命令安裝的,yum命令會自動建立nginx.service
文件,直接用命令:linux
systemcel enable nginx.service
在這裏我是用源碼編譯安裝的,因此要手動建立nginx.service
服務文件。開機沒有登錄狀況下就能運行的程序,存在系統服務(system)裏,即:nginx
/lib/systemd/system/
在系統服務目錄裏建立nginx.service文件vim
vim /lib/systemd/system/nginx.service
寫入內容以下:centos
[Unit] Description=nginx After=network.target [Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true [Install] WantedBy=multi-user.target
[Unit]:服務的說明
Description:描述服務
After:描述服務類別
[Service]服務運行參數的設置
Type=forking是後臺運行的形式
ExecStart爲服務的具體運行命令
ExecReload爲重啓命令
ExecStop爲中止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:[Service]的啓動、重啓、中止命令所有要求使用絕對路徑
[Install]運行級別下服務安裝的相關設置,可設置爲多用戶,即系統運行級別爲3ui
保存退出。spa
systemctl enable nginx.service
systemctl status nginx.service
很奇怪,明明啓動成功了,爲何顯示Active: inactive (dead)?設計
(base) [root@cssc system]# systemctl status nginx.service ● nginx.service - nginx Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: inactive (dead)
殺死nginx重啓nginxcode
pkill -9 nginx ps aux | grep nginx systemctl start nginx
再次查看狀態,變成了active,搞定。blog
(base) [root@css system]# systemctl status nginx.service ● nginx.service - nginx Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2020-05-17 13:44:25 CST; 9s ago Process: 114106 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS) Main PID: 114107 (nginx) CGroup: /system.slice/nginx.service ├─114107 nginx: master process /usr/local/nginx/sbin/nginx └─114108 nginx: worker process May 17 13:44:25 cssbjqnffcsvic systemd[1]: Starting nginx... May 17 13:44:25 cssbjqnffcsvic systemd[1]: Started nginx.
啓動nginx服務
systemctl start nginx.service
設置開機自啓動
systemctl enable nginx.service
中止開機自啓動
systemctl disable nginx.service
查看服務當前狀態
systemctl status nginx.service
從新啓動服務
systemctl status nginx.service
查看全部已啓動的服務
systemctl list-units --type=service