Can’t open PID file /var/run/nginx.pid (yet?) after start: Too many levels of symbolic links

现象:Nginx启动时卡住,无法自动执行完启动命令,显示下一个命令提示符

可通过systemctl status nginx -l命令查看nginx详细状态信息

或直接查看/var/log/messages信息
systemd: Starting nginx - high performance web server…
systemd: Can’t open PID file /var/run/nginx.pid (yet?) after start: Too many levels of symbolic links

解决方法1

检查目录 /var/run 是否为软链接 (symbolic link) 到/run目录

1
2
# ls -ld /var/run
lrwxrwxrwx. 1 root root 6 Sep 14 2020 /var/run -> ../run

同时也检查下目录 /run 是否也是软链接

1
2
# ls -ld /run
drwxr-xr-x 24 root root 780 Oct 28 06:20 /run

检查nginx配置中的pid路径:

1
2
# grep -ir pid /etc/nginx 
/etc/nginx/nginx.conf:pid /var/run/nginx.pid;

建立软链接时采用的是相对路径,所以才会产生这样的错误,解决方式是采用绝对路径建立软链接

1
# mv /var/run /var/run_orig && ln-s /run /var/run && ls-ld /var/run

解决方法2

检查nginx配置中的pid路径:

1
2
# grep -ir pid /etc/nginx
/etc/nginx/nginx.conf:pid /var/run/nginx.pid;

找到配置文件nginx.conf中的pid行

1
# pid /var/run/nginx.pid;

变更为

1
pid /run/nginx.pid;

使用sed命令替换pid路径

1
sed -i 's/pid /var/run/nginx.pid/pid /run/nginx.pid/' /etc/nginx/nginx.conf

编辑nginx.service

1
# vim /lib/systemd/system/nginx.service

变更pid路径

1
PIDFile=/var/run/nginx.pid

变更为

1
PIDFile=/run/nginx.pid

应用修改

1
# systemctl daemon-reload

然后重启服务

1
# systemctl restart nginx

最后查看下服务状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# systemctl status nginx.service
● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
Active: active (running) since Wed 2021-10-27 23:12:02 CST; 7h ago
Docs: http://nginx.org/en/docs/
Process: 1724 ExecStop=/bin/sh -c /bin/kill -s TERM $(/bin/cat /run/nginx.pid) (code=exited, status=0/SUCCESS)
Process: 1325 ExecReload=/bin/sh -c /bin/kill -s HUP $(/bin/cat /run/nginx.pid) (code=exited, status=0/SUCCESS)
Process: 1729 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Main PID: 1730 (nginx)
CGroup: /system.slice/nginx.service
├─1730 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
├─1731 nginx: worker process
├─1732 nginx: worker process
├─1733 nginx: worker process
└─1734 nginx: worker process

Oct 27 23:12:02 my202108112 systemd[1]: Starting nginx - high performance web server...
Oct 27 23:12:02 my202108112 systemd[1]: Started nginx - high performance web server.

注意:这个问题不仅会影响 nginx,还会影响 mysql 或 fail2ban 以及其他服务。