如何将ALB与API Gateway进行私有连接?(附Fargate现有配置)
实现API Gateway与Fargate ALB的私有连接
要实现API Gateway和ALB的私有连接,核心是将ALB改为内部负载均衡器,并通过API Gateway的VpcLink建立VPC内的通信链路,具体步骤如下:
1. 调整Fargate ALB服务配置
将现有公网ALB改为内部ALB,同时让Fargate任务不再分配公网IP(更安全且符合私有通信需求):
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: false, // 任务无需公网IP,走VPC内部通信 publicLoadBalancer: false, // 将ALB设为内部类型 vpcSubnets: { // 指定部署到私有子网(若集群默认使用私有子网可省略) subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }, } );
2. 创建API Gateway VpcLink
VpcLink是API Gateway访问VPC内资源的桥梁,需关联目标内部ALB:
const vpcLink = new apigateway.VpcLink(this, "GithubReposVpcLink", { targets: [sbApp.loadBalancer], vpc: appCluster.vpc, });
3. 修改API Gateway集成配置
将原有的公网Http集成替换为使用VpcLink的私有集成,同时保留路径代理逻辑:
const api = new apigateway.RestApi(this, "GithubReposApi", { restApiName: "GithubReposApi", // 可选:将API设为私有,仅允许VPC内或通过VPN/Direct Connect的客户端访问 // endpointConfiguration: { // types: [apigateway.EndpointType.PRIVATE], // vpcEndpoints: [new ec2.VpcEndpoint(this, "ApiGwVpcEndpoint", { // vpc: appCluster.vpc, // service: ec2.InterfaceVpcEndpointAwsService.APIGATEWAY, // })], // }, }); const apiGithub = api.root.addResource("api"); const proxyResource = apiGithub.addResource("{proxy+}"); // 标准路径代理资源 proxyResource.addMethod( "GET", new apigateway.HttpIntegration( `http://${sbApp.loadBalancer.loadBalancerDnsName}/api/{proxy}`, { proxy: true, httpMethod: "GET", options: { requestParameters: { "integration.request.path.proxy": "method.request.path.proxy", }, vpcLink: vpcLink, // 关联VpcLink实现私有访问 connectionType: apigateway.ConnectionType.VPC_LINK, }, } ), { requestParameters: { "method.request.path.proxy": true, }, } );
关键配置检查
- 安全组规则:内部ALB的安全组需允许来自API Gateway VPC端点(若用私有API)或VpcLink所属安全组的8080端口流量。
- VPC路由:私有子网需配置正确的路由,确保API Gateway与Fargate任务之间的通信链路畅通。
- 私有DNS解析:内部ALB的私有DNS名称在VPC内可正常解析,无需额外配置(AWS默认支持)。
内容的提问来源于stack exchange,提问作者Orlando Macedo
相关产品推荐
相关产品推荐

