Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm building a CloudFormation stack. I have

  • a web app in an ECS container which has PortMappings for ContainerPorts 9000 and 9002, mapped to HostPorts 80 and 443, and
  • an application load balancer (AWS::ElasticLoadBalancingV2::LoadBalancer) with Listeners and TargetGroups for HTTP on port 80 and HTTPS on port 443

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.

like image 510
Dave Schweisguth Avatar asked Dec 13 '25 07:12

Dave Schweisguth


1 Answers

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.

like image 53
Andreas Avatar answered Dec 16 '25 05:12

Andreas