CentOS 7.9 Nginx 设置开机自启动

发布时间 2023-10-10 01:27:56作者: 龙凌云端

CentOS 7.9 Nginx 设置开机自启动


 

一、前言

如果在联网的情况下,可以通过如下命令进行安装 Nginx:

yum install -y nginx

通过 yum 命令安装的 Nginx 服务,会自动配置系统文件 nginx.service,可以使用如下系统命令:

# 停止服务
systemctl stop  nginx

#查看服务状态
systemctl status nginx

#启动服务
systemctl start  nginx

#重启服务
systemctl restart  nginx

 

如果在没有网络的情况下,不能使用 yum 命令,只能通过解压  tar 文件进行收到安装,如:nginx-1.22.1.tar.gz

此方式不会自动生成 nginx.service 文件,如何配置 nginx 服务开机自启动呢?

Nginx 服务启动命令如下:

/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

 

 

二、实现步骤

1、编写 Nginx 系统启动文件

/lib/systemd/system 目录下创建 nginx.service 文件

vi /lib/systemd/system/nginx.service

编写内容如下:

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

[Install]
WantedBy=multi-user.target

说明:ExecStart= 后配置实际的 Nginx 启动命令。

 

2、重载所有服务

systemctl daemon-reload

 

3、设置开机自启动

systemctl enable nginx

 

4、查看开机启动状态

systemctl is-enabled nginx

 

5、查看 Nginx 服务状态

systemctl status nginx

 

6、启动 Nginx 服务

systemctl start nginx

 

7、停止 Nginx 服务

systemctl stop nginx

 

8、重启 Nginx 服务

systemctl restart nginx