Usually 502 error happens when Cloudfront unable to reach origin endpoint. Some of the common reasons are:
Backend is busy: Origin endpoint ( ELB -> EC2) is busy or load is higher than given threshold. If this is happening reguarly, its better to get more instance in auto scaling group or increase existing instance for larger capacity.
WAF rule: Some request might get blocked by WAF rule. So check cloudFront logs to verfiy, if needed modify your application or disable WAF rule ( not recommended).
DNS: If Endpoint has custom DNS, make sure DNS is reachable.
EC2 instances: All EC2 instances in origin endpoint are down or unhealthy.
Usually AWS CloudFont has timeout setting to wait responses from origin end points. If response takes more than default time out period, it throws 504 timeout error. So of common solutions are below.
Backend taking too much time to response:
CloudFront origin, by default has `Origin Response time’ of 60 sec, if endpoint ( usually EC2 instance / ELB) taking more than 60 sec to response then it throws 504 timeout error. So increasing timeout on CloudFront origin.
Unable to reach any of the origin:
Origin endpoint may be down or spinning new instance. Make sure endpoints are running and accessible. Quick way to check is by IP to insure that its running.