How can I resolve the recv() failed (104: Connection reset by peer) error in Nginx with FastCGI?

I’ve been having some issues with my website and I’m receiving 502 Bad Gateway errors. After checking the error logs, I noticed the following message: “recv() failed (104: Connection reset by peer) while reading response header from upstream”.

This is possible that the error “recv() failed (104: Connection reset by peer)” could cause the 502 Bad Gateway errors on your website. Here are some possible reasons for the error.

  1. Interruptions or issues with the network connection between Nginx and the upstream server can result in recv() failures.

  2. If either Nginx or the upstream server is running low on resources such as memory or CPU, this can lead to problems handling incoming and outgoing data, causing recv() failures.

  3. Incorrect settings in Nginx or the upstream server, such as incorrect timeouts or buffer sizes, can cause recv() failures if they prevent the server from handling incoming data correctly.

  4. Issues with the upstream server, such as crashes or exceptions, can cause recv() failures when Nginx tries to receive data from it.

  5. Sudden spikes in traffic can cause recv() failures if Nginx or the upstream server cannot handle the increased load.

Possible Solutions

  1. First, try restarting your fastcgi_process / server

  2. Try increasing the memory limit

# in PHP file
ini_set('memory_limit','512M');

# in php.ini
memory_limit = 512M
  1. Try increasing execution time.
# PHP file
ini_set('max_execution_time', '300');

# php.ini
max_execution_time = 30
  1. Try changing FastCGI timeouts in your Nginx configuration file.
fastcgi_read_timeout 300;
fastcgi_send_timeout 300;
fastcgi_connect_timeout 300;
  1. Try increasing the output buffering size.
output_buffering = 65535
  1. Try changing Nginx keepalive_requests
    In your Nginx configuration file, change the keepalive_requests as per your need.
keepalive_requests 600;

Use the same value in pm.max_requests in PHP-FPM config file.

pm.max_requests = 600
  1. Try increasing socket timeout.
default_socket_timeout = 300

I had a similar problem, and none of the solutions worked. I had to remove the FastCGI to fix the problem.

location ~* \.php$  {
    internal;
}