CentOS7安装Nginx并添加成服务【转】

当我们使用Nginx作为 Web 服务器时,将其添加为系统服务可以更方便地管理它的启动和停止。下面是 CentOS 7 将 Nginx 添加系统服务的方法步骤:

创建nginx服务配置文件

首先,创建一个 nginx 服务配置文件,并将以下内容复制到文件中:

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
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
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • [Unit] 段是服务的元数据和运行级别配置。
  • [Service] 段是服务的主要操作和启动命令,包括PID 文件声明、预启动命令、启动命令、重载命令、停止命令和进程命名空间声明。
  • [Install] 段是运行级别的依赖项声明。

将配置文件保存为 /usr/lib/systemd/system/nginx.service

将上述配置保存为 nginx.service,并将其移动到 CentOS 7 系统服务的目录(/usr/lib/systemd/system/):

$ sudo mv nginx.service /usr/lib/systemd/system/

启动Nginx

要启动 nginx 服务,可以使用以下命令:

$ sudo systemctl start nginx

配置为开机自启

要将 nginx 服务配置为开机自启,可以运行以下命令:

$ sudo systemctl enable nginx

其他命令

要停止 nginx 服务,可以使用以下命令:

$ sudo systemctl stop nginx

要重新加载 nginx 配置文件,可以使用以下命令:

$ sudo systemctl reload nginx

以上是 CentOS 7 将 Nginx 添加系统服务的方法步骤,下面是两条实际的示例说明:

示例1:安装Nginx

  1. 安装依赖包:
$ sudo yum install gcc pcre-devel zlib-devel openssl-devel -y
  1. 下载 Nginx:
$ cd /usr/local/src
$ sudo wget http://nginx.org/download/nginx-1.18.0.tar.gz
  1. 解压并编译:
$ sudo tar xvf nginx-1.18.0.tar.gz
$ cd nginx-1.18.0/
$ sudo ./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/local/nginx/sbin/nginx \
--conf-path=/usr/local/nginx/conf/nginx.conf \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-file-aio
$ sudo make && sudo make install
  1. 测试 nginx 是否正常运行:
$ sudo /usr/local/nginx/sbin/nginx -t

如果没有错误,将输出 “nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful”。

  1. 启动 nginx:
$ sudo /usr/local/nginx/sbin/nginx
  1. 访问网站,将显示nginx欢迎页面。

示例2:添加Nginx系统服务

在安装 nginx 后,我们可以将其添加为系统服务。请参照上面的 CentOS 7 将 Nginx 添加系统服务的方法步骤。

$ sudo nano nginx.service

输出nginx的系统服务文本。

保存文件后,将文件移动到 /usr/lib/systemd/system/ 目录:

$ sudo mv nginx.service /usr/lib/systemd/system/

启动 Nginx 系统服务:

$ sudo systemctl start nginx

通过输入计算机的 IP 地址即可访问 nginx 首页。

转自

CentOS7将Nginx添加系统服务的方法步骤 - Python技术站
https://pythonjishu.com/pspgqqaindjliur/

posted @ 2023-10-27 15:15  paul_hch  阅读(342)  评论(0编辑  收藏  举报