Nginx与PHP-FPM进程间的两种通信方式(转载)

Most PHP programmers have used PHP strictly in a web server environment. In such an environment, PHP is a CGI/Fast GGI or server module called and controlled by the HTTP server (usually Apache, IIS, Nginx, or similar). The HTTP server receives a request for a PHP-based web page and calls the PHP process to execute it, which usually returns output to the HTTP server to be sent on to the end user.


1 Nginx和PHP-FPM的进程间通信有两种方式

1.1 一种是TCP;

1.2 一种是UNIX Domain Socket.


其中TCP是IP加端口,可以跨服务器,而UNIX Domain Socket不经过网络,只能用于Nginx跟PHP-FPM都在同一服务器的场景.


2.用哪种取决于你的PHP-FPM配置

2.1 方式1: php-fpm.conf: listen = 127.0.0.1:9000

nginx.conf: fastcgi_pass 127.0.0.1:9000;


2.2 方式2: php-fpm.conf: listen = /tmp/php-fpm.sock

nginx.conf: fastcgi_pass unix:/tmp/php-fpm.sock;

其中php-fpm.sock是一个文件,由php-fpm生成,类型是srw-rw----.


3 通信方式解析

UNIX Domain Socket可用于两个没有亲缘关系的进程,是目前广泛使用的IPC机制,比如X Window服务器和GUI程序之间就是通过UNIX Domain Socket通讯的.这种通信方式是发生在系统内核里而不会在网络里传播.UNIX Domain Socket和长连接都能避免频繁创建TCP短连接而导致TIME_WAIT连接过多的问题.对于进程间通讯的两个程序,UNIX Domain Socket的流程不会走到TCP那层,直接以文件形式,以stream socket通讯.


如果是TCP Socket,则需要走到IP层,对于非同一台服务器上,TCP Socket走的就更多了.

3.1 UNIX Domain Socket: Nginx <=> socket <=> PHP-FPM

3.2 TCP Socket(本地回环): Nginx <=> socket <=> TCP/IP <=> socket <=> PHP-FPM

3.3 TCP Socket(Nginx和PHP-FPM位于不同服务器): Nginx <=> socket <=> TCP/IP <=> 物理层 <=> 路由器 <=> 物理层 <=> TCP/IP <=> socket <=> PHP-FPM


4 像mysql命令行客户端连接mysqld服务也类似有这两种方式


使用Unix Socket连接(默认): mysql -uroot -p --protocol=socket --socket=/tmp/mysql.sock

使用TCP连接: mysql -uroot -p --protocol=tcp --host=127.0.0.1 --port=3306


5 PHP-FPM配置文件 listen 参数解析

; 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 IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.




备注: 来源 Nginx中fastcgi_pass的配置问题


评论0条