Search code examples
phpcodeigniternginxcronforge

502 bad gateway when running cron job


I have a codeIgniter project deployed on laravel forge server. A Cron job is scheduled to run every night. But when ever the cron job runs it gives

HTTP request sent, awaiting response... 502 Bad Gateway 2019-08-27 06:03:54 ERROR 502: Bad Gateway.

This error comes after 60-70 seconds approximately. The Cron job is supposed to send email reminders to a bunch of users (50-70 users). The code of my cron.php class that sends emails is

foreach($reminders as $job) {

        $job_ids[]=$job->id;

        $email_message=$this->load->view('email_templates/job_reminder', array('job'=>$job), TRUE);
        $message=$this->load->view('email_templates/template', array('content'=>$email_message, 'header_image'=>'header_proof_reminder'), TRUE);
        $subject='blablabla: '.format_job_name($job->id, $job->job_number, $job->name).' is still awaiting approval';

        $sent = $this->send_job_reminder_emails($job, $subject, $message);

        if($sent){ //Log if an email was sent
            $this->debug_string .= "<p>Email sent for job: ".$job->id."</p>";
        }else{
            $this->debug_string .= "<p>Didn't send email for job: ".$job->id."</p>";
        }
        $this->debug_string .= "<p><br/></p>";

    }

send_job_reminder_emails function is the one that sends emails. around 20,30 emails are sent everytime cron runs but after that it stops sending emails because of the 502 error I think.

The command I am using for cron is wget https://mysite.url/cron/send_reminders

The php-fpm settings are:

max_execution_time = 1000
max_input_time = 200
memory_limit = 512M

In nginx.conf: keepalive_timeout=300

site-nginx.cong:

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_read_timeout 600;
    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;
    fastcgi_connect_timeout 600;
    fastcgi_send_timeout 600;
}

To test, i just run this cron command manually on the server

I am not sure what is causing this issue. Is it an fpm or nginx issue or should I handle it somehow in codebase.

Thanks


Solution

  • Do not use long operations through web proxying. Use console commands, there are no gateways and no timeouts.

    For cron use the same user as php-fpm.

    /path/to/bin/php -f /path/to/cron/app-reminder-wrapper.php