使用socket方式连接Nginx优化php-fpm性能
导读
Nginx连接fastcgi的方式有2种:TCP和unix domain socket
什么是Unix domain socket?—— 维基百科
Unix domain socket 或者 IPC socket是一种终端,可以使同一台操作系统上的两个或多个进程进行数据通信。与管道相比,Unix domain sockets 既可以使用字节流和数据队列,而管道通信则只能通过字节流。Unix domain sockets的接口和Internet socket很像,但它不使用网络底层协议来通信。Unix domain socket 的功能是POSIX操作系统里的一种组件。
Unix domain sockets 使用系统文件的地址来作为自己的身份。它可以被系统进程引用。所以两个进程可以同时打开一个Unix domain sockets来进行通信。不过这种通信方式是发生在系统内核里而不会在网络里传播。
TCP和unix domain socket方式对比
TCP是使用TCP端口连接127.0.0.1:9000
Socket是使用unix domain socket连接套接字/dev/shm/php-cgi.sock(很多教程使用路径/tmp,而路径/dev/shm是个tmpfs,速度比磁盘快得多)
1、PHP7默认是以socket方式运行,但是我们要修改nginx配置文件才可以,要想用socket运行PHP,必须要有个socket才行,所以创建一个socket touch /dev/shm/php7-fpm.sock2、修改nginx网站配置文件: vi /etc/nginx/conf.d/affdalao.conf # location ~ \.php$ { location ~ .*\.php(\/.*)*$ { root /home/affdalao;# fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/dev/shm/php7-fpm.sock;(修改成这一行) fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /home/affdalao$fastcgi_script_name; include fastcgi_params; } }3、修改PHP的www文件 vi /usr/local/php/etc/php-fpm.d/www.conf user = nobodygroup = nobody ; 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. ;listen = 127.0.0.1:9000listen = /dev/shm/php7-fpm.sock (修改这一行) ; Set listen(2) backlog.; Default Value: 511 (-1 on FreeBSD and OpenBSD) ;listen.backlog = 511; Set permissions for unix socket, if one is used. In Linux, read/write ; permissions must be set in order to allow connections from a web server. Many ; BSD-derived systems allow connections regardless of permissions. ; Default Values: user and group are set as the running user ; mode is set to 0660listen.owner = nobody (修改这两行,把注释去掉,不然会报nginx 502 bad gateway) listen.group = nobody4、重启PHP-fpm和nginx systemctl restart php-fpm systemctl restart nginx
评论(0)