Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save brainfoolong/bd53a5484c458d746e29f87157011ef6 to your computer and use it in GitHub Desktop.

Select an option

Save brainfoolong/bd53a5484c458d746e29f87157011ef6 to your computer and use it in GitHub Desktop.
Caddy Server PHP FCGI - Load Balance one upstream - Prevent 502 errors

If you are using caddy and you have a FCGI handler running on a port (that even automatically restarts after close), you probably will be confrontend with 502 errors when one FCGI stops and the next restarts.

On windows, FCGI default closes after 500 requests, which you can increase but it does not properly solve the issue, it just delays it.

In caddy, you can load balance between the same upstreams to easily wait for the next upstream to restart.

This config balances between same upstreams and gracefully retry a few times (each 250ms for 5s) to serve the request.

Caddy config:

php_fastcgi 127.0.0.1:9000 127.0.0.1:9000 {
  ...
  lb_retries 5
  lb_try_duration 5s
  ...
}

For windows, this is the .bat script that automatically start/restart a closed CGI handler. One heavy loaded environments, you even can increase PHP_FCGI_MAX_REQUESTS a bit to make the restarts less happen less often.

set PHP_FCGI_MAX_REQUESTS=500
:start
    PATHTO/php-cgi.exe -b 127.0.0.1:9000
    goto start

With all this, you should be able to maintain constants CGI responses without 502 gateway timeouts/errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment