Resolving 502 Bad Gateway errors

in MagentoStabilityTroubleshooting Tags: PHPTroubleshooting

A 502 Bad Gateway error indicates there has been an internal error with PHP, so the site could not be rendered and you will see an error in your browser.

Verify whether 502 errors have occurred

Log in on your Hypernode and issue this command (--yesterday works too):

$ pnl --today --filter status=502

It will tell you those requests that could not be handled by PHP.

Causes

Memory depletion

The main cause is that PHP has ran out of memory. This does not normally happen, but if it happens, it is likely due to two reasons:

  1. The code base is very large (many installed modules or very large/complex modules)
  2. One or more Magento modules leak memory.

Hypernodes can generally cope with high memory usage, but in extreme cases the Hypernode will perform an automatic recovery restart of the PHP service. This might take a few seconds, during which visitors might get a 502 response.

To verify this situation, log in to your Hypernode and check the memory usage (in KB) of PHP processes:

$ pgrep -f fpm | xargs ps -o rss=
28720
39408
251184

This shows memory usage of 28, 39 and 251 MB. The average memory usage per process on our platform (across all customers and sizes) is 63 MB. If you are well above this figure, it might indicate an issue with your code. The solutions are:

  1. Fix the code, or replace a faulty Magento module. This requires a memory profiler, or the laborious process of trial and error.
  2. Upgrade to a Hypernode with more memory.

Low level PHP error

In very rare cases, PHP might crash for other reasons than memory depletion (a so called “SEGFAULT”). If this happens, the server process will automatically be restarted in a few seconds. If you encounter this often (verify with /var/log/php-fpm/php-fpm.log), it will likely help to switch PHP versions (from PHP 5.5 to 7).

1