梦会成真的

乘舟侧畔千帆过,病树前头万木春。

在 CentOS 上为编译安装的 Nginx 设置 Systemd 服务

person  梦会成真的    watch_later 2024-04-23 15:11:26
visibility 589    class nginx    bookmark 分享

在 CentOS 上,使用编译安装方式安装 Nginx 是一种常见的做法,这样可以更灵活地配置和管理 Nginx 服务。然而,要使 Nginx 成为系统服务,并能够随系统启动自动运行,就需要将其配置为 Systemd 服务。本文将介绍如何在 CentOS 上为编译安装的 Nginx 设置 Systemd 服务。

步骤一:创建 Systemd 服务单元文件

首先,我们需要创建一个新的 Systemd 服务单元文件,该文件告诉 Systemd 如何启动和管理 Nginx 服务。我们将使用 nginx.service 作为文件名,并将其保存到 /etc/systemd/system/ 目录下。

sudo nano /etc/systemd/system/nginx.service

在编辑器中,粘贴以下内容:

[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=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

请注意,上述配置中的路径 /usr/local/nginx/ 可能需要根据你的实际安装路径进行调整。

步骤二:重新加载 Systemd 配置

当我们创建或修改 Systemd 服务单元文件时,需要通知 Systemd 重新加载配置文件以更新服务列表。使用以下命令重新加载配置:

sudo systemctl daemon-reload

步骤三:启动和管理 Nginx 服务

现在,你可以使用 Systemd 命令来启动、停止、重新加载和查看 Nginx 服务的状态了:

  • 启动 Nginx 服务:

    sudo systemctl start nginx
    
  • 停止 Nginx 服务:

    sudo systemctl stop nginx
    
  • 重新加载 Nginx 配置:

    sudo systemctl reload nginx
    
  • 查看 Nginx 服务状态:

    sudo systemctl status nginx
    
  • 设置 Nginx 开机启动:

    sudo systemctl enable nginx
    

通过上述步骤,你已经成功将编译安装的 Nginx 配置为 Systemd 服务,在 CentOS 上可以方便地管理 Nginx 服务,并确保它在系统启动时自动运行。

chat评论区
评论列表
menu