您的位置 首页 php

PHP-FPM 与 Nginx 的通信机制总结

php-fpm 介绍

CGI 协议与 FastCGI 协议

每种动态语言( PHP,Python 等)的代码文件需要通过对应的解析器才能被服务器识别,而 CGI 协议就是用来使解释器与服务器可以互相通信。PHP 文件在服务器上的解析需要用到 PHP 解释器,再加上对应的 CGI 协议,从而使服务器可以解析到 PHP 文件。

由于 CGI 的机制是每处理一个请求需要 fork 一个 CGI 进程,请求结束再kill掉这个进程,在实际应用上比较浪费资源,于是就出现了CGI 的改良版本 FastCGI,FastCGI 在请求处理完后,不会 kill 掉进程,而是继续处理多个请求,这样就大大提高了效率。

PHP-FPM 是什么

PHP-FPM 即 PHP-FastCGI Process Manager, 它是 FastCGI 的实现,并提供了进程管理的功能。进程包含 master 进程和 worker 进程两种;master 进程只有一个,负责监听端口,接收来自服务器的请求,而 worker 进程则一般有多个(具体数量根据实际需要进行配置),每个进程内部都会嵌入一个 PHP 解释器,是代码真正执行的地方。

nginx 与 php-fpm 通信机制

当我们访问一个网站(如 www.test.com)的时候,处理流程是这样的:

 www.test.com 
 |
 |
 Nginx 
 |
 |
路由到 www.test.com/index.php 
 |
 |
加载 nginx 的 fast-cgi 模块 
 |
 |
fast-cgi 监听 127.0.0.1:9000 地址 
 |
 |
www.test.com/index.php 请求到达 127.0.0.1:9000
 |
 |
 等待处理... 

Nginx 与 php-fpm 的结合

在 Linux 上,nginx 与 php-fpm 的通信有 tcp socket 和 unix socket 两种方式。

tcp socket 的优点是可以跨服务器,当 nginx 和 php-fpm 不在同一台机器上时,只能使用这种方式。

Unix socket 又叫 IPC(inter-process communication 进程间通信 ) socket,用于实现同一主机上的进程间通信,这种方式需要在 nginx配置文件中填写 php-fpm 的 socket 文件位置。

两种方式的数据传输过程如下图所示:
PHP-FPM 与 Nginx 的通信机制总结

二者的不同:

由于 Unix socket 不需要经过网络协议栈,不需要打包拆包、计算校验和、维护序号和应答等,只是将应用层数据从一个进程拷贝到另一个进程。所以其效率比 tcp socket 的方式要高,可减少不必要的 tcp 开销。不过,unix socket 高并发时不稳定,连接数爆发时,会产生大量的长时缓存,在没有面向连接协议的支撑下,大数据包可能会直接出错不返回异常。而 tcp 这样的面向连接的协议,可以更好的保证通信的正确性和完整性。

Nginx 与 php-fpm 结合只需要在各自的配置文件中做设置即可:

1) Nginx 中的配置

以 tcp socket通信为例

server { 
 listen 80; #监听 80 端口,接收http请求
 server_name www.test.com; #就是网站地址
 root /usr/local/etc/nginx/www/huxintong_admin; # 准备存放代码工程的路径
 #路由到网站根目录 www.test.com 时候的处理
 location / { 
 index index.php; #跳转到 www.test.com/index.php
 autoindex on;
 } 

 #当请求网站下 php 文件的时候,反向代理到 php-fpm
 location ~ .php$ { 
 include /usr/local/etc/nginx/fastcgi.conf; #加载 nginx 的 fastcgi 模块
 fastcgi_intercept_errors on; 
 fastcgi_pass 127.0.0.1:9000; # tcp 方式,php-fpm 监听的 IP 地址和端口
 # fasrcgi_pass /usr/run/php-fpm.sock # unix socket 连接方式
 }

} 

2) php-fpm 的配置

listen = 127.0.0.1:9000# 或者下面这样
listen = /var/run/php-fpm.sock 

通过以上配置即可完成 php-fpm 与 nginx 的通信。

在应用中的选择

如果是在同一台服务器上运行的 nginx 和 php-fpm,且并发量不高(不超过1000),选择unix socket,以提高 nginx 和 php-fpm 的通信效率。
如果是面临高并发业务,则考虑选择使用更可靠的 tcp socket,以负载均衡、内核优化等运维手段维持效率。

若并发较高但仍想用 unix socket 时,可通过以下方式提高 unix socket 的稳定性。

1)将sock文件放在 /dev/shm 目录下,此目录下将 sock 文件放在内存里面,内存的读写更快。

2)提高 backlog

backlog 默认位 128,1024 这个值最好换算成自己正常的 QPS,配置如下。

nginx.conf 文件中

server { 
 listen 80 
 default backlog = 1024;
} 

php-fpm.conf 文件中

listen.backlog = 1024 

3)增加 sock 文件和 php-fpm 实例

在 /dev/shm 新建一个 sock 文件,在 nginx 中通过 upstream 模块将请求负载均衡到两个 sock 文件,并且将两个 sock 文件分别对应到两套 php-fpm 实例上。

文章来源:智云一二三科技

文章标题:PHP-FPM 与 Nginx 的通信机制总结

文章地址:https://www.zhihuclub.com/80101.shtml

关于作者: 智云科技

热门文章

评论已关闭

34条评论

  1. Most athletes begin by taking one 25 mcg tablet per day and increasing this dosage every three to four days by one additional tablet

  2. The breast cancer incidence rate ratio was 1 65 thus fabricated pH responsive HA modified TiO2 NPs for targeted delivery of CDDP against A2780 ovarian cancer

  3. Some people have difficulty sleeping because of a problem known as period limb movements during sleep PLMS or another condition called restless legs syndrome RLS

  4. While an occasional drink is likely OK, heavy drinking when you re trying to get pregnant could harm your fertility

  5. sulfasalazine diclofenac duo capsule prospect I also like to thin the canopy to let more light into the plants below

  6. 40 Explanations for the apparent inconsistency of earlier reports include variability in study design, in the assays applied, in the measures of testosterone quoted and in the definitions of hypogonadism and cardiovascular disease used

  7. 04 31 and a subsequent analysis suggested a greater benefit in patients with both ER and progesterone receptor PgR positive tumors

  8. Isoniazid preventive therapy IPT is a recommended strategy for prevention of tuberculosis TB in persons with Human Immunodeficiency Virus HIV although the benefits have not been unequivocally demonstrate

  9. STD syndrome packets improving syndromic management of sexually transmitted diseases in developing countries

  10. Hawkins, Jeffrey S Cord blood contains blood- forming stem cells, which are potentially useful for treating diseases that require stem cell transplants also called bone marrow transplants, such as certain kinds of leukemia or lymphoma, aplastic anemia, severe sickle cell disease, and severe combined immunodeficiency

  11. Its usage in fertility clinics is more prominent as compared to its usage in gyms due to the fact that it helps infertility and is inexpensive edu, annizubcgmail

  12. Is the benefit of postmastectomy irradiation limited to patients with four or more positive nodes, as recommended in international consensus reports

  13. I took all my colace Antibiotic susceptibility of Legionella pneumophila strains isolated from hospital water systems in Southern Italy

  14. Patients should be advised to discontinue glipizide and metformin hydrochloride tablets immediately and promptly notify their health practitioner if unexplained hyperventilation, myalgia, malaise, unusual somnolence, or other nonspecific symptoms occur

  15. I think I read one novel during that entire time 0 indicate antagonistic interactions, and values equal to 1

  16. STELAZINE TABLETS 5MG COATED TABLET 5MG GOLDSHIELD PHARMACEUTICALS LTD UNITED KINGDOM Users of Anadrol report severe crashes when stopping usage, mostly due to the loss of water and inhibited endogenous hormone production brought about during the cycle

  17. Health Food Pills Found to Contain Lethal Superbugs, 142, p Гў Kerry XPBYUucGoXlGEUDf 6 17 2022

  18. This study showed statistically significant improvement in sperm parameters in the treated group but not in the untreated patients

  19. If you are taking phenytoin with toremifene, your doctor may want to check your phenytoin levels Besides systemic side effects like menopausal symptoms, thromboembolic effects, and ocular symptoms, including keratopathy, cataract, optic neuritis, macular holes, crystalline retinopathy with or without cystoid macular edema CME, and pseudocystic foveal cavitation have been mainly reported in cases who have taken high cumulative doses 1, 2, 3

  20. The overall live birth rate for women to receive CC is estimated to be 20 during the 4- month period according to Chinese Obstetrics and Gynecology Second Edition Methamphetamine Hydrochloride Marketed under the brand name Desoxyn

  21. Hypercholesterolemia decreases coronary blood flow and induces apoptosis through diminished autophagy leading to LV dysfunction 5, 6 The trial was conducted from 2002 2004 at multiple centers, with institutional review board approval secured for each center and all subjects providing written consent 6

网站地图