When the error page carries Cloudflare branding, the 504 was returned by the origin server: Cloudflare acted as an intermediary, and the problem is on the site’s side, usually because an application did not respond in time. If the page is not branded, Cloudflare itself may have generated the error.
In either case, copy the Ray ID and the exact time of the error: this information can be used to locate the request.
If the error only appears with the domain proxied through Cloudflare and the site responds normally when you open it without the proxy, try Pause Cloudflare on Site, which pauses the proxy and sends traffic directly to the server. Don’t use Development Mode as a test: it suspends caching but leaves the WAF, rules, and SSL/TLS active. Both controls are explained in how to temporarily disable Cloudflare.
If the code you see is 524, not 504, Cloudflare connected to your server, but the server did not return a response before the Proxy Read Timeout, which is 125 seconds by default (Cloudflare Enterprise zones can increase it). In this case, the application took longer than Cloudflare’s limit, so the sections of this guide about slow actions and PHP performance apply as well.