I was also getting random 502 bad gateway errors from my Azure web apps (API).
The endpoint is very basic stuff, get some input parameters (via header) and uses that to query a DB and returns a bunch of records.
Here is the thing that got me (very) confused. It was working in most cases. However when passing a parameter value that would return a higher number of records, then the app would fail and return a 502 bad gateway.
I randomly found that the fix was to change the app to 64 bits.
The thing that I don't understand is that the 502 error was returned instantly, it's like the code didn't even try to load the records.
I still don't understand what was happening here, but happy I found the fix.