如何对nginx设置开机自启动 - 教程

使用 systemd(适用于 CentOS 7+/Ubuntu 16.04+/Debian 8+ 等新系统)**

步骤:
  1. 创建 systemd 服务文件(如果安装 Nginx 时未自动生成):
    编辑文件 /etc/systemd/system/nginx.service,写入以下内容:

    [Unit]
    Description=The NGINX HTTP and reverse proxy server
    After=network.target
    [Service]
    Type=forking
    PIDFile=/run/nginx.pid
    ExecStartPre=/usr/sbin/nginx -t
    ExecStart=/usr/sbin/nginx
    ExecReload=/usr/sbin/nginx -s reload
    ExecStop=/bin/kill -s QUIT $MAINPID
    PrivateTmp=true
    [Install]
    WantedBy=multi-user.target
  2. 启用开机自启动

    sudo systemctl enable nginx

    输出提示:Created symlink ... → .../nginx.service 表示成功。

  3. 启动服务并验证状态

    sudo systemctl start nginx # 立即启动
    sudo systemctl status nginx # 检查运行状态

但在运行时报错:nginx.service: Failed to parse PID from file /run/nginx.pid

原因是Nginx 配置中 pid 路径(如 /run/nginx.pid)与 systemd 文件中的 PIDFile 不一致,两者需要保证一致才行。

确保Nginx的主配置文件(通常位于/etc/nginx/nginx.conf)中设置了正确的pid文件路径。
在配置文件中应该有一行类似于:
pid /run/nginx.pid;

posted @ 2025-08-10 22:29  wzzkaifa  阅读(26)  评论(0)    收藏  举报