CentOS7.5 设置 Nginx 开机自启动

centos 7开机自启动有两种不一样的设置方式,若是是yum直接安装的软件服务,则直接开启便可,若是是源码编译安装的,则须要在系统服务(system)建立service文件,而后才能设置。

1、 前言

centos 7以上是用Systemd进行系统初始化的,Systemd 是 Linux 系统中最新的初始化系统(init),它主要的设计目标是克服 sysvinit 固有的缺点,提升系统的启动速度。关于Systemd的详情介绍在这里css

2、yum直接安装Nginx服务

Systemd服务文件以.service结尾,好比如今要创建nginx为开机启动,若是用yum install命令安装的,yum命令会自动建立nginx.service文件,直接用命令:linux

systemcel enable nginx.service

3、源码编译安装

在这里我是用源码编译安装的,因此要手动建立nginx.service服务文件。开机没有登录状况下就能运行的程序,存在系统服务(system)里,即:nginx

/lib/systemd/system/

一、建立nginx.service文件

在系统服务目录里建立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

三、查看nginx状态

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

五、Systemd 命令和 sysvinit 命令的对照表

file

相关文章
相关标签/搜索