Nginx错误日志connect() to unix:/tmp/php-cgi-56.sock failed (2 No such file or directory)

在配置Nginx + ThinkPHP5.0的时候,Nginx error log出现类似这样的错误:

1
2
3
4
2020/09/14 13:29:35 [crit] 2872#0: *6 connect() to unix:/tmp/php-cgi-56.sock failed 
(2: No such file or directory) while connecting to upstream, client: 119.136.91.154,
server: www.xxx.com, request: "GET /login/index.html HTTP/1.1",
upstream: "fastcgi://unix:/tmp/php-cgi-56.sock:", host: "xxx.com"

什么原因呢?一般原因有如下几种,都是针对于 php-cgi-56.sock 这个sock文件
根本就没有这个文件,因此找不到
有这个文件, 但是路径错误,导致找不到
有这个文件且路径正常,但权限错误,也会导致找不到

首先我们来看下这个文件的产生环境和作用,在php-fpm配置文件 php-fpm.conf 或者 ./php-fpm.d/www.conf 里面能看到这样的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses on a
; specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
; listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php-cgi-56.sock

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1

其中一项配置listen =是关于CGI处理的方式,有tcp、也有socket,一般tcp的方式就是ip:port,也就是127.0.0.1:9000
但是这里我们要介绍socket方式,unix socket的优势是比tcp快

以上的配置是说CGI监听这个socket文件

而我们还需要Nginx配置,把请求发送到这个socket去处理

1
2
3
4
5
location ~ [^/]\.php(/|$) {
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi-56.sock;
fastcgi_index index.php;
}

Nginx把php相关的请求发到php-cgi-56.socket了

因此/tmp/php-cgi-56.socket是php-fpm生成的,Nginx只是找到这个sock文件,然后把数据发给这个sock而已

所以遇到如上问题,就仔细排查下,
1、这个文件是否生成
2、php-fpm写的文件路径 和 Nginx配置的路径 是否一致
3、Nginx是否有权限去操作这个文件

坚持原创技术分享,谢谢鼓励我继续创作!