AWS の 502 エラー:原因と解決策502
エラーの概要 502 Bad Gateway は、API Gateway や Application Load Balancer(ALB)がバックエンド(EC2、Lambda、ECS など)から不正な応答を受け取った、あるいは応答を得られなかったことを示すエラーです。AWS 環境では、バックエンドサービスの一時的な障害やタイムアウト、リソース不足など複数の原因で発生しやすいステータスコードです。 実際のエラーメッセージ例 API Gateway から返されるレスポンス例: { "message": "502 Bad Gateway" } CloudWatch Logs に記録されるロードバランサーのログ例: [ALB] 2024-01-15T10:23:45Z app/my-app/1234567890abcdef 192.0.2.1:54321 10.0.1.100:8080 0.050 0.100 0 502 - - arn:aws:elasticloadbalancing:ap-northeast-1:123456789012:targetgroup/my-targets/1234567890abcdef "GET http://example.com/ HTTP/1.1" "Mozilla/5.0" - arn:aws:acm:ap-northeast-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 - ecs default - - よくある原因と解決手順 原因1:バックエンドのタイムアウトまたはクラッシュ Lambda 関数や EC2 インスタンス上のアプリケーションが処理中にタイムアウトするか、予期せず停止している場合、ALB や API Gateway は 502 を返します。 Before(タイムアウト設定が不適切): # Lambda 関数がタイムアウト時間内に完了できない import time def lambda_handler(event, context): time.sleep(35) # デフォルトのタイムアウト 30秒を超える return {"statusCode": 200} After(タイムアウトを延長し、処理を最適化): ...