Home  >  Article  >  Operation and Maintenance  >  What is the difference between unix socket and tcp socket in Nginx

What is the difference between unix socket and tcp socket in Nginx

WBOY
WBOYforward
2023-05-16 13:37:061625browse

There are two ways for Nginx to connect to fastcgi: unix domain socket and TCP. Unix domain socket or IPC socket is a terminal that allows two or more processes on the same operating system to communicate with each other. In contrast to pipes, Unix domain sockets can use both byte streams and data queues, while pipe communication can only be through byte streams. The interface of Unix domain sockets is very similar to Internet sockets, but it does not use the underlying network protocol to communicate. The function of Unix domain socket is a component in the POSIX operating system.

Comparison between TCP and unix domain socket methods

TCP uses the TCP port to connect to 127.0.0.1:9000, and Socket uses the unix domain socket to connect to the socket /dev/shm/php-cgi. sock (many tutorials use the path /tmp, and the path /dev/shm is a tmpfs, which is much faster than the disk)

fastcgi_pass unix:/tmp/php-cgi.sock
fastcgi_pass 127.0.0.1:9000

When the server pressure is not high, there is not much difference between tcp and socket, but in When the pressure is high, the socket method is indeed better.

The following is the configuration method for changing TCP to socket mode in PHP 5.3 and above:

Modify php-fpm.conf (/usr/local/php/etc/php-fpm.conf)

;listen = 127.0.0.1:9000
listen = /dev/shm/php-cgi.sock

Modify the configuration of the server section of the nginx configuration file and change the http mode to the socket mode

location ~ .*.(php|php5)?$
{
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}

Restart php-fpm and nginx

service nginx restart
service php-fpm restart
ls -al /dev/shm

You can see php-cgi .sock file unix socket type. In theory, unix socket does not go through the network and is more efficient, but the stability is not very ideal.

The above is the detailed content of What is the difference between unix socket and tcp socket in Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete