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)服务的推荐方式。


相关推荐
CHHC188013 分钟前
NetCore树莓派桌面应用程序
linux·运维·服务器
云栖梦泽2 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
si莉亚3 小时前
ROS2安装EVO工具包
linux·开发语言·c++·开源
Tingjct3 小时前
Linux常用指令
linux·运维·服务器
广州灵眸科技有限公司3 小时前
为RK3588注入澎湃算力:RK1820 AI加速卡完整适配与评测指南
linux·网络·人工智能·物联网·算法
IT界的老黄牛3 小时前
Linux 压缩命令实战:tar、gzip、bzip2、xz、zstd 怎么选?一篇讲清楚
linux·运维·服务器
IT WorryFree3 小时前
飞塔防火墙与第三方设备进行IPSEC故障诊断期间,用户可能会观察到以下错误:
linux·服务器·网络
12345,catch a tiger4 小时前
虚拟机ubuntu安装Vmware Tools
linux·运维·ubuntu
凉、介4 小时前
别再把 PCIe 的 inbound/outbound、iATU 和 eDMA 混为一谈
linux·笔记·学习·嵌入式·pcie
辰风沐阳4 小时前
OpenClaw 安装教程(Ubuntu 24.04 Desktop)
linux·ubuntu