nginx.service : Can‘t open PID file /run/nginx.pid (yet?) after start: Operation not permitted

在 Ubuntu 20.04 上解决 Nginx 服务因 nginx.pid 文件丢失导致服务挂掉的问题

环境介绍

在 Ubuntu 20.04 上,Nginx 被用作反向代理和 HTTP 服务器,系统通过 systemd 管理 Nginx 服务。Nginx 的正常运行依赖于其 PID 文件 (nginx.pid),该文件用于记录 Nginx 主进程的进程 ID (PID)。当使用 systemctl 操作 Nginx 时,systemd 需要通过此文件跟踪 Nginx 的状态。

然而,在某些情况下,使用 Nginx 的原生停止命令 (nginx -s stop) 会导致 nginx.pid 文件被意外删除,导致 systemd 无法继续管理 Nginx 服务。这会造成服务挂掉,并且 systemctl 无法正确启动或停止 Nginx。

问题描述

在不可控因素或使用 nginx -s stop 之类的命令后,Nginx 的 nginx.pid 文件可能被删除。由于 systemd 需要此文件来管理服务,当文件丢失时,systemctl 无法找到 Nginx 主进程的 PID,导致以下问题:

  • 通过 systemctl 无法启动或停止 Nginx,出现错误:
nginx.service: Can't open PID file /run/nginx.pid (yet?) after start: No such file or directory

nginx.service: Can't open PID file /run/nginx.pid (yet?) after start: Operation not permitted
  • 通过 systemctl status nginx 查看服务状态时,显示找不到 PID 文件。
  • 通过 systemctl status nginx 查看服务状态时,显示权限不足。
原因分析

当使用 nginx -s stop 停止 Nginx 时,Nginx 会删除 nginx.pid 文件,这是其正常的行为。但在 Ubuntu 系统中,systemd 需要此文件来管理服务的生命周期。由于文件丢失,systemctl 无法操作 Nginx 服务,从而导致服务无法被正常控制。

解决方法

为了解决这个问题,有两种方法可以修复丢失的 PID 文件问题:

1. 手动写入 nginx.pid 文件
  • 首先,找到 Nginx 主进程的 PID,运行以下命令:
 ps aux | grep nginx

确定主进程的 PID(通常是父进程的 PID,例如 12345)。

  • 将该 PID 手动写入 /var/run/nginx.pid 文件中:

    echo 12345 > /var/run/nginx.pid
    

    (注意:nginx.pid 文件的路径可能会因 Nginx 的配置不同,请通过 /etc/nginx/nginx.conf 确认实际路径。)

  • 完成后,可以通过 systemctl 正常管理 Nginx,例如:

    sudo systemctl restart nginx
    
2. 使用 nginx -c 重新启动 Nginx

另一种方式是使用 root 权限重新启动 Nginx,以重新生成 PID 文件:

sudo nginx -c /etc/nginx/nginx.conf

这条命令将加载 Nginx 的配置文件并自动生成新的 nginx.pid 文件。

注意:Nginx 的默认 PID 路径

在 Nginx 的官方默认配置中,PID 文件通常位于 /var/log/nginx/nginx.pid。然而,在通过 Ubuntu 的 apt 包管理器安装 Nginx 时,PID 文件的路径被设置为 /var/run/nginx.pid。这是为了与 systemd 更好地集成和兼容。因此,建议在 Ubuntu 环境中使用 /var/run/nginx.pid,确保系统服务管理的正常运行。

避免问题
  1. 避免使用 nginx -s stop:在通过 systemd 管理 Nginx 的系统上,建议使用 systemctl 命令来管理 Nginx 服务,而不是 Nginx 的原生命令。例如:

    • 停止服务:
      sudo systemctl stop nginx
      
    • 启动服务:
      sudo systemctl start nginx
      
    • 重启服务:
      sudo systemctl restart nginx
      
  2. 确保 Nginx 配置文件中的 PID 路径正确:在 /etc/nginx/nginx.conf 文件中,检查并确认 pid 配置项指向 /var/run/nginx.pid。如果该路径配置错误,可能导致系统无法找到或生成 PID 文件,影响服务管理。

总结

在 Ubuntu 20.04 系统中,Nginx 使用其原生停止命令 (nginx -s stop) 时,可能会导致 nginx.pid 文件丢失,进而导致 systemctl 无法正常管理 Nginx 服务。通过手动修复 PID 文件,或者使用 root 权限重新启动 Nginx 可以解决此问题。建议在使用 systemd 管理服务的环境下,始终使用 systemctl 管理 Nginx 服务,以避免类似问题的发生。

额外
pkill -9 nginx # 强制关闭nginx所有进程
参考

https://askubuntu.com/questions/1113319/nginx-service-cant-open-pid-file-run-nginx
https://stackoverflow.com/questions/66469385/after-the-first-reload-nginx-error-open-var-run-nginx-pid-failed-2-n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值