CentOS 7 设置 Nginx 开机自启(使用 Systemd)

CentOS 7 设置 Nginx 开机自启(使用 Systemd)

概述

本文档将指导您如何在 CentOS 7 上使用 Systemd 设置 Nginx 开机自启。Systemd 是 Linux 的系统和服务管理器,负责在系统启动时初始化系统环境、启动和管理系统进程。

步骤

1. 创建或编辑 nginx.service 文件

  • 检查文件是否存在

    首先检查 /etc/systemd/system/ 目录下是否存在 nginx.service 文件。

    bash 复制代码
    ls /etc/systemd/system/ | grep nginx.service
  • 创建或编辑文件

    如果文件不存在,使用以下命令创建并编辑:

    bash 复制代码
    sudo vim /etc/systemd/system/nginx.service

    如果文件已存在,则直接编辑该文件。

2. 添加服务配置

nginx.service 文件中添加以下内容(根据实际情况调整路径):

ini 复制代码
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

说明

  • PIDFile:指定 Nginx 的 PID 文件路径。
  • ExecStartPre:在启动 Nginx 之前执行的命令,用于测试 Nginx 配置文件的语法。
  • ExecStart:启动 Nginx 的命令。
  • ExecReload:重新加载 Nginx 配置的命令。
  • ExecStop:停止 Nginx 的命令。

3. 重新加载 systemd

编辑完成后,重新加载 systemd 以扫描新的或有变动的单元:

bash 复制代码
sudo systemctl daemon-reload

4. 设置开机自启

启用 Nginx 服务,使其在系统启动时自动启动:

bash 复制代码
sudo systemctl enable nginx.service

5. 启动 Nginx 服务

立即启动 Nginx 服务:

bash 复制代码
sudo systemctl start nginx.service

6. 验证服务状态

检查 Nginx 服务的状态,确保它正在运行:

bash 复制代码
sudo systemctl status nginx.service

如果服务正常运行,您将看到类似以下的输出:

复制代码
● nginx.service - The NGINX HTTP and reverse proxy server
   Loaded: loaded (/etc/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since ...

注意事项

  • 路径正确性 :确保 nginx.service 文件中的路径与 Nginx 的实际安装路径一致。

  • 权限问题 :确保 nginx.service 文件和 Nginx 可执行文件具有正确的权限。

  • 配置文件语法 :在对 Nginx 配置文件进行任何修改后,建议先测试其语法是否正确:

    bash 复制代码
    nginx -t
  • 系统兼容性:使用 Systemd 方法是管理现代 Linux 发行版(如 CentOS 7)服务的推荐方式。


相关推荐
大路谈数字化4 分钟前
Centos中内存CPU硬盘的查询
linux·运维·centos
luoqice1 小时前
linux下查看 UDP Server 端口的启用情况
linux
倔强的石头_2 小时前
【Linux指南】动静态库与链接机制:从原理到实践
linux
赏点剩饭7782 小时前
linux中的hostpath卷、nfs卷以及静态持久卷的区别
linux·运维·服务器
神鸟云2 小时前
DELL服务器 R系列 IPMI的配置
linux·运维·服务器·网络·边缘计算·pcdn
herderl3 小时前
**僵尸进程(Zombie Process)** 和**孤儿进程(Orphan Process)**
linux·运维·服务器·网络·网络协议
lepton_yang3 小时前
Zephyr下控制ESP32S3的GPIO口
linux·嵌入式硬件·esp32·zephyr
泽02023 小时前
Linux 编译器 gcc 与 g++
linux·运维·服务器
水冗水孚3 小时前
图文并茂讲解nginx中http升级https(部署SSL证书)知识点总结
nginx·http·https