我使用 ALB 有以下 Fargate 服务:
const sbApp = new ApplicationLoadBalancedFargateService(
this,
"GithubReposApp",
{
cluster: appCluster,
desiredCount: 1,
cpu: 256,
memoryLimitMiB: 512,
taskImageOptions: {
image: ecs.ContainerImage.fromAsset(".."),
containerPort: 8080,
secrets: {
GITHUB_TOKEN: ecs.Secret.fromSecretsManager(
appSecrets,
"githubToken"
),
},
},
assignPublicIp: true,
publicLoadBalancer: true,
}
);
我设法将 Rest API 连接到 ALB,但使用公共 DNS。
const api = new RestApi(this, "GithubReposApi", {
restApiName: "GithubReposApi",
});
const apiGithub = api.root.addResource("api");
const proxyResource = new ProxyResource(this, "GithubReposProxy", {
parent: apiGithub,
anyMethod: false,
});
proxyResource.addMethod(
"GET",
new HttpIntegration(
`http://${sbApp.loadBalancer.loadBalancerDnsName}/api/{proxy}`,
{
proxy: true,
httpMethod: "GET",
options: {
requestParameters: {
"integration.request.path.proxy": "method.request.path.proxy",
},
},
}
),
{
requestParameters: {
"method.request.path.proxy": true,
},
}
);
有没有办法将 API 网关与 ALB 进行私有连接?我知道它一定有,但我已经尝试了很多东西,但似乎没有任何效果。
感谢您的帮助。
您可能想要尝试的是将
publicLoadBalancer
和 assignPublicIp
设置为 false
,以获得私有 ALB 和 ECS 服务。
然后,如果可能,您应该使用较新的 HTTP API 网关而不是较旧的 REST API 网关。 HttpApi
可以在 aws-cdk-lib/aws-apigatewayv2
库中找到。您想要切换到 HTTP API 的原因是能够使用 HttpAlbIntegration
库中的 aws-cdk-lib/aws-apigatewayv2-integrations
,它提供了一种使用 VPC-Link 将 API 网关连接到 ALB 的简单方法,如下所示:
import { HttpApi, HttpMethod } from 'aws-cdk-lib/aws-apigatewayv2';
import { HttpAlbIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
// Create a HTTP API
const api = new HttpApi(this, 'GithubReposApi');
api.addRoutes({
path: '/{proxy+}',
methods: [ HttpMethod.ANY ],
// Use the `HttpAlbIntegration` here:
integration: new HttpAlbIntegration(
'GithubReposAppIntegration',
// The `ApplicationLoadBalancedFargateService` construct provides a
// `listener` attribute which can be passed in here:
sbApp.listener,
),
});
如果您无法从 REST API 网关切换到 HTTP API 网关,您可以尝试使用
AwsIntegration
库中的 aws-cdk-lib/aws-apigateway
构造,但不幸的是我从未尝试过。
您应该注意的一件事是在 ECS 集群使用的 VPC 上将
restrictDefaultSecurityGroup
设置为 false
,这是我花了 2 天才发现的错误:
const vpc = new Vpc(
this,
'ClusterVpc',
{
maxAzs: 2,
// Add this:
restrictDefaultSecurityGroup: false,
},
);
这将禁止删除 API 网关能够通过 VPC-Link 访问 VPC 所需的某些安全组规则。