我正在尝试将一个由多个容器组成的水平扩展应用程序部署到EC2支持的AWS ECS。由于某些原因,我不能使用应用程序负载均衡器,但希望使用将端口80和443上的所有流量转发到反向代理容器的网络负载均衡器。我使用AWS CDK来定义设置。
当我试图将两个端口上的流量路由到代理时,遇到了问题。无论我做什么,创建的目标组中的所有目标都指向容器上的端口80。即,我得到了80->80443->80当我想要80->80443->443。
我的CDK代码如下:
const proxyService = new ecs.Ec2Service(this, 'ProxyService', {
serviceName: 'proxy',
cluster,
taskDefinition: proxyTaskDefinition,
minHealthyPercent: 0,
desiredCount: 1,
securityGroups: [securityGroup],
cloudMapOptions: {
name: 'proxy',
cloudMapNamespace: cluster.defaultCloudMapNamespace
}
})
const loadbalancer = new lb.NetworkLoadBalancer(this, 'NetworkLoadBalancer', {
vpc,
internetFacing: true
})
new cdk.CfnOutput(this, 'LoadBalancerDnsName', {
value: loadbalancer.loadBalancerDnsName
})
loadbalancer.addListener('HTTPListener', {
port: 80
})
.addTargets('HTTPTarget', {
port: 80,
targets: [proxyService]
})
loadbalancer.addListener('HTTPSListener', {
port: 443,
})
.addTargets('HTTPSTarget', {
port: 443,
// the proxyService seems to always register itself at port 80
// by calling its attachToNetworkTargetGroup method
targets: [proxyService]
})
}
为目标群体生成的云信息如下所示:
NetworkLoadBalancerHTTPListener792E96F1:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- TargetGroupArn:
Ref: NetworkLoadBalancerHTTPListenerHTTPTargetGroupCEAF8C0F
Type: forward
LoadBalancerArn:
Ref: NetworkLoadBalancer8E753273
Port: 80
Protocol: TCP
Metadata:
aws:cdk:path: SplitClusterStack/NetworkLoadBalancer/HTTPListener/Resource
NetworkLoadBalancerHTTPListenerHTTPTargetGroupCEAF8C0F:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Protocol: TCP
TargetType: ip
VpcId:
Ref: VPCB9E5F0B4
Metadata:
aws:cdk:path: SplitClusterStack/NetworkLoadBalancer/HTTPListener/HTTPTargetGroup/Resource
NetworkLoadBalancerHTTPSListenerAF8F470A:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- TargetGroupArn:
Ref: NetworkLoadBalancerHTTPSListenerHTTPSTargetGroup4BC6FF0B
Type: forward
LoadBalancerArn:
Ref: NetworkLoadBalancer8E753273
Port: 443
Protocol: TCP
Metadata:
aws:cdk:path: SplitClusterStack/NetworkLoadBalancer/HTTPSListener/Resource
NetworkLoadBalancerHTTPSListenerHTTPSTargetGroup4BC6FF0B:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Protocol: TCP
TargetType: ip
VpcId:
Ref: VPCB9E5F0B4
Metadata:
aws:cdk:path: SplitClusterStack/NetworkLoadBalancer/HTTPSListener/HTTPSTargetGroup/Resource
部署后,我可以在web控制台中编辑创建的目标组,以注册指向同一IP上443的新目标,并注销端口80以使其正常工作。
我如何创建一个负载均衡器目标:
- 指向ECS服务
- 使用端口443
如果它能帮助我解决这个问题,我很乐意自己构建它,甚至添加覆盖。
ECS服务公开了一个loadBalancerTarget
方法,可以用于此:
loadbalancer.addListener('HTTPSListener', {
port: 443,
})
.addTargets('HTTPSTarget', {
port: 443,
targets: [proxyService.loadBalancerTarget({
containerPort: 443,
containerName: 'proxy'
})]
})