Dave Schweisguth
Dave Schweisguth

Reputation: 37647

How to map both ports 80 and 443 from an ELB to the same ECS container?

I'm building a CloudFormation stack. I have

When I define a Service, I can only specify one load balancer element; although LoadBalancers is plural, documentation says only one load balancer is allowed, and specifying two load balancer elements doesn't work. How, then, to map both ports?

Here's the service part of my CloudFormation JSON with only the HTTPS parts, which works. Can it be extended to route HTTP to the same container? If not, what's the best solution?

"Service": {
  "Type": "AWS::ECS::Service",
  "DependsOn": ["AutoScalingGroup", "HTTPSListener"],
  "Properties": {
    "Cluster": { "Ref": "Cluster" },
    "DesiredCount": { "Ref": "InstanceCount" },
    "LoadBalancers": [
      {
        "TargetGroupArn": { "Ref": "HTTPSTargetGroup" },
        "ContainerName": "nginx",
        "ContainerPort": "9002"
      }
    ],
    "Role": { "Ref": "ServiceRole" },
    "TaskDefinition": { "Ref": "TaskDefinition" }
  }
}

A CloudFormation solution would be ideal, but an API solution would also be of interest.

I could create a second Service for HTTP, with a separate load balancer and container instances, but that would be neither simple nor economical.

Upvotes: 3

Views: 2509

Answers (2)

Dave Schweisguth
Dave Schweisguth

Reputation: 37647

A partial solution is to register the instances with the HTTP target group manually through the API after the stack is created:

autoscaling = boto3.client('autoscaling')
auto_scaling_groups = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[auto_scaling_group_name])
instances = auto_scaling_groups['AutoScalingGroups'][0]['Instances']

elbv2 = boto3.client('elbv2')
for instance in instances:
    elbv2.register_targets(
        TargetGroupArn=http_target_group_arn,
        Targets=[{'Id': instance['InstanceId'], 'Port': instance}]
    )

This isn't a fully acceptable answer since instances created by the autoscaling group in the future wouldn't automatically be registered with the HTTP target group. It ought to be possible to rig the instances up to register themselves; I'll look in to that.

Upvotes: 0

Andreas
Andreas

Reputation: 984

I would suggest one of these options:

a) Registering the task (container) at two different task definitions of the same load balancer as part of the container boot process instead of using the build in feature of the ECS service.

b) Defining another ECS service each of them connected with it's own target group. Both target groups linked with the same ALB.

Upvotes: 2

Related Questions