laravel - How to fix 502 Bad Gateway Error in nginx php

When huge request hits on nginx server it returns 502 bad gateway error. I have tried multiple answer from stackoverflow including this How to fix 502 Bad Gateway Error in production(Nginx)? But nothing works for me. Someone help for me

worker_processes  1;
daemon off;
user root;

events {
   worker_connections  1024;
}

http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  sendfile on;
  keepalive_timeout  330;
  client_max_body_size 512M;
  server_tokens off;
  gzip on;
  gzip_types application/json;

  access_log /dev/stdout;
  error_log /dev/stdout;

  # Adding proxy timeout
  proxy_read_timeout 330;
  proxy_connect_timeout 330;
  proxy_send_timeout 330;

  server {
    listen 80;
    server_name _;
    root /var/www/html/public;
    index index.php index.html index.htm;
    underscores_in_headers on;

    access_log /dev/stdout;
    error_log /dev/stdout;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
        fastcgi_send_timeout 330;
        fastcgi_read_timeout 330;
        fastcgi_busy_buffers_size 16k;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }
 }
}

Answer

Solution:

When huge request hits probably means, your script (which is behind a loadbalancer) works longer than the LB timeout is... while your script is working (and hasn't answered yet), the LB will think it's crashed and drop the IP connection. BANG! Bad gateway.

LB timeouts are usually 60-120 seconds, but in rare cases up to 5 minutes.

What you can try:

  • Reduce the script runtime to be lower than the LB timeout
  • Send output to the client while working (traffic will have to pass through the proxy to keep the IP connection alive)
  • Change the concept (like put data to a offline queue)

Source