我有一个使用 API Gateway、Lambda 和自定义域的 CloudFormation 堆栈。当我完全拆除堆栈并重新部署它时,我经常发现 API Gateway 处于这样的状态:对于通过自定义域发出的每个 API 请求,它都会返回“502 Bad Gateway”。
以下是一些其他观察结果:
- 我仍然可以使用标准执行 URL(例如
<api-id>.execute-api.us-east-1.amazonaws.com
)成功调用 API - AWS 控制台中的所有域设置(API 网关和 Route 53)均显示正确
- 在 AWS 控制台中,我可以手动创建具有相同设置的备用自定义域,并且它可以正常工作
- 我尝试手动删除自定义域并使用相同的设置重新创建它,但还是以同样的方式失败
- 唯一的解决办法似乎是删除堆栈并等待一两天重新部署
这“感觉就像”一个 API 网关缓存错误,它仍在尝试将我的自定义域路由到旧的(自删除后)API 实例(即使 AWS 控制台显示正确的值)。
知道什么可能导致此问题或如何调试它吗?我查看的日志似乎没有帮助,因为错误发生在我的 API 实际到达之前。
我的 CloudFormation 的相关部分如下所示:
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
...
ApiDomainName:
Type: AWS::ApiGatewayV2::DomainName
Properties:
DomainName: !Ref DomainName
DomainNameConfigurations:
- CertificateArn: !Ref CertificateArn
ApiMapping:
Type: AWS::ApiGatewayV2::ApiMapping
Properties:
ApiId: !Ref ServerlessHttpApi
DomainName: !Ref ApiDomainName
Stage: !Ref ServerlessHttpApiApiGatewayDefaultStage
DNSRecord:
Type: AWS::Route53::RecordSet
Properties:
Name: !Ref DomainName
Type: A
AliasTarget:
DNSName: !GetAtt ApiDomainName.RegionalDomainName
HostedZoneId: !GetAtt ApiDomainName.RegionalHostedZoneId
HostedZoneId: !Ref HostedZoneId
> curl https://api.example.com
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
</body>
</html>
> curl https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com
{"message":"Hello World"}%
交叉发布到此处的 aws 开发论坛: https://forums.aws.amazon.com/thread.jspa?messageID=960826
最佳答案
您似乎正在构建一个无服务器应用程序。为此,我将使用无服务器应用程序模型(SAM):https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started.html
切换后,自定义域名的声明将如下所示:
MyApi:
Type: AWS::Serverless::Api
Properties:
BinaryMediaTypes: [image~1jpg]
StageName: !Ref Stage
EndpointConfiguration: REGIONAL
Domain:
DomainName: api.example.com
CertificateArn: <ARN of the Certificate from ACM>
EndpointConfiguration: REGIONAL
Route53:
HostedZoneId: <Hosted zone id from route 53>
关于aws-cloudformation - 为什么通过自定义域访问时 API Gateway 有时会卡住返回 "502 Bad Gateway",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64450035/